Dev.to AI 🤖 Ai 👁 0 📖 10 min read

Putting AI Inside a Workflow Contract: How HagiCode Uses OpenSpec to Curb Hallucinations and Scope Drift

Introduction When coding with AI, the most frustrating failure mode is rarely that the model cannot write code—it is that the model acts too fast without permission. You ask a clarifying question, and it has already ed

Introduction

When coding with AI, the most frustrating failure mode is rarely that the model cannot write code—it is that the model acts too fast without permission. You ask a clarifying question, and it has already edited three files and queued a git commit. You ask for a frontend tweak, and it "helpfully" modifies a backend service. When a requirement leaves a detail ambiguous, it silently invents an assumption and keeps coding until tests fail.

Early teams tried to fix this by appending reminders like "do not exceed scope" or "plan before coding" to the end of a prompt. That helps briefly, until the conversation grows or the model changes. In HagiCode, the OpenSpec workflow takes a different approach: instead of hoping the AI will behave politely, it encodes behavioral boundaries into a backend state machine, structured metadata contracts, exclusive stage guardrails, mechanical verification, and human-in-the-loop pause gates.

Drawing on HagiCode's current backend implementation and prompt templates, this article breaks down how its OpenSpec pipeline narrows the space for AI hallucinations and enforces predictable behavior from start to finish.

Background: Why Prompts Alone Fail to Curb AI Hallucinations

In software engineering, AI hallucinations are not limited to inventing nonexistent APIs. More often, they show up as uncontrolled behavior and context drift:

  1. Blurred stages: Exploring, drafting a proposal, editing source files, and committing changes all happen inside the same chat turn, so the model skips planning and leaves unreviewed side edits behind.
  2. Verbal-only scope: In multi-repository projects, which repositories are editable and which are read-only rely on repeated chat reminders; once forgotten, edits spill across repository boundaries.
  3. Hidden assumptions: Facing an unclear requirement or missing setup (such as an uninitialized openspec/ directory), the model tends to guess silently or create directories as side effects, disguising uncertainty as fact.
  4. Self-certified completion: A checklist item asks to verify layout rules or tests, and the model ticks - [x] after a quick glance without running any real check.

Packing more "please be careful" sentences into a single large prompt cannot reliably stop these four failures. HagiCode shifts enforcement into orchestration and template contracts.

Defense 1: Separating Four Stages with a State Machine and Exclusive Boundaries

In HagiCode, an OpenSpec change never runs end-to-end from a single fire-and-forget prompt. Instead, it is split into explicit lifecycle stages driven by ProposalSessionGrain and ProposalSessionHandler, where each command advances at most one boundary:

flowchart LR
    INIT["Init / Optimizing / Drafting"] -->|"proposal generate"| OPEN["Openspecing (new -> explore -> ff)"]
    OPEN -->|"ValidateProposalFiles passes"| REV["Reviewing"]
    REV -->|"proposal annotate"| OPEN
    REV -->|"proposal execute"| EXEC["Executing (apply)"]
    EXEC -->|"Structured question raised"| WAIT["WaitingForReply"]
    WAIT -->|"User answers and run resumes"| EXEC
    EXEC -->|"Implementation ends"| DONE["ExecutionCompleted"]
    DONE -->|"proposal archive"| ARCH["Archiving -> Archived"]

This separation blocks premature execution and scope creep at three levels:

  1. Multi-step queueing without premature transitions: When proposal generate runs, the backend enqueues openspec-v1-new, optional openspec-v1-explore, and openspec-v1-ff in order based on Explore mode. Step 1 uses MessageAssociationType.ProposalGenerationStart, which intentionally keeps the session in Openspecing so it cannot jump to Reviewing early. Only after ProposalGeneration finishes and OpenSpecValidationService.ValidateProposalFiles confirms that openspec/changes/<proposalName>/proposal.md exists on disk does the session transition to Reviewing.
  2. Exclusive guardrails at the top of every prompt: Every stage template (new, explore, ff, apply, archive) opens with strict exclusions defining what the model must not do in that stage:
    • Planning (new / explore / ff): Strictly forbids modifying source code, config, or test files, checking boxes in tasks.md, running openspec archive, or running git add/commit/push. It also forbids writing non-implementation work—such as archiving, syncing main specs, committing, opening PRs, or deploying—into tasks.md. Both new and archive additionally ban background subagents or out-of-session research paths so the model stays grounded in session context.
    • Implementation (apply): Strictly forbids archiving, creating new changes, or rewriting the goals of proposal.md, design.md, or specs. If legacy tasks include archiving or committing, the agent must skip them as out of scope without checking them off.
    • Archive (archive): Handles completion checks, delta spec syncing into openspec/specs/, directory archiving, and optional archive commits, while strictly forbidding implementing unfinished code tasks. Even when commit_when_archive is enabled, Git commits are restricted exclusively to the MonoSpecs root repository and never touch code repositories under repos/.
  3. No hidden chaining: Returning from a command only means the request was queued. Each stage settles at Reviewing or ExecutionCompleted and waits for a human decision—sending revision notes via proposal annotate, or explicitly invoking execute or archive.

Beyond stage isolation, the Execution Scenarios workspace lets teams assign different Agents and fallback crews to specific scenarios (such as proposal review or auto-composing commits), matching each stage to the model suited for it.

Defense 2: Locking Repository Scope and Write Paths with Structured Contracts

In multi-repository setups, two common failure modes are inventing directory paths and editing reference-only repositories. HagiCode replaces free-form instructions with structured authority.

Single Authority from Session Metadata: RepositoryScopeTable

During proposal generation, when the repository-scope planning direction is enabled, the backend reads structured targetRepositories metadata from the session and renders a fixed four-column table through RepositoryScopeTable:

## Involved Repositories
| Repository Name | Path | Edit Permission | Purpose |
| --- | --- | --- | --- |
| Web App | repos/web | [editable] | Current change context |
| Core API | repos/hagicode-core | - | Current change context |

Permission markers are hardcoded on the backend: [editable] means confirmed write, and - means confirmed read. The prompt includes an explicit rule forbidding the model from rewriting, upgrading, downgrading, or inferring any permission, or adding unlisted repositories. If no repository scope has been confirmed, the backend never prints an empty table; it emits a fixed NoScopeStatement ("No repository scope is confirmed. Do not infer write permission.").

On the CLI side (hagi proposal create), --chief-complaint must start with a Repository scope block listing Writable repositories: and Read-only repositories: (using none for empty lists), taking paths strictly from hagi project repositories.

Even Smart Scope—which helps users pre-select repositories from request text—runs inside a tool-less smart-scope-selection prompt. Its JSON response is checked item by item on the server against the caller's candidate catalog: unlisted items are dropped and non-editable items are downgraded to reference, making privilege escalation impossible.

Blocking Silent Initialization and Blind Paths

The OpenSpec stage templates also enforce two filesystem guards:

  • Check root before any write: Before creating or updating files, the agent must run openspec list --json and inspect root. When root is null, the agent is forbidden from running openspec init as a side effect; in interactive mode it stops and asks, while in non-interactive mode it halts and reports the blocker.
  • CLI-resolved write targets: The agent must never guess openspec/changes/... paths from memory. Every output path comes from openspec status --change "<name>" --json (planningHome, changeRoot, and artifactPaths.<id>.resolvedOutputPath), and resolved symlink paths outside changeRoot are rejected before writing.

Defense 3: Eight Planning Directions and Mechanical Verification

Early OpenSpec adopters often ran into inconsistent artifacts: missing change tables, broken diagrams, or skipped specs files. HagiCode turns those output expectations into toggleable, auditable controls.

Eight Planning Directions and Conflict Resolution

ProposalPlanningDirections defines eight planning directions: explore, change-map, flowchart, prototype, architecture, sequence, repository-scope (all enabled by default), and enhanced-visualization (disabled by default).

Several design choices prevent conflicting rules and drift:

  • Render-time supersession: When enhanced-visualization is enabled, PlanningDirectionInstructionRenderer uses the built-in visualise skill to emit visualizer blocks and automatically omits the ASCII prototype fragment at render time, ensuring two contradictory UI-prototype instructions never reach the same prompt.
  • Per-CLI defaults and snapshots: IProposalPlanningDirectionDefaultsStore stores default directions per Agent CLI, and every run persists an optionsSnapshot capturing planningDirections, enableExploreMode, proposalContentLanguage, and heroId for traceability.
  • Paired design-guide checks: Before writing the first artifact in ff, the prompt checks the project root and scoped repository roots for both DESIGN.md and .impeccable/design.json. Only when both exist together are they loaded as read-only UI constraints.

No Guessing Skips or Eyeballing Checks

Across artifact generation and implementation, mechanical rules block common shortcuts:

# Maintenance changes with no spec-level impact must declare this explicitly instead of fabricating or silently skipping specs
skip_specs: true
  • No unilateral skipping of specs: During ff, the agent must re-run openspec status --change "<name>" --json after each artifact rather than relying on cached memory, and it is forbidden from skipping specs on its own judgment. Only maintenance changes with no spec-level behavior change may declare skip_specs: true in .openspec.yaml (or retire_capabilities: true when retiring a capability).
  • Item-by-item evidence and mechanical checks: During apply, tasks listing specific rules, colors, breakpoints, or test IDs must be checked item by item with recorded evidence. Whenever a mechanical check exists (such as searching classes or running tests), visual guessing is forbidden. If a task names a skill (such as /impeccable polish), the agent must locate and run that skill; if any item cannot be verified, the checkbox stays unchecked and the gap is named under ### Issues Encountered.
  • Code commits stay separate: Once apply finishes, source changes remain uncommitted in the working tree so developers can inspect diffs and commit through the Git tab or a dedicated Super Commit task.

Defense 4: Pausing at WaitingForReply Instead of Guessing

Often the single best way to eliminate hallucinations is not better prompting—it is making the AI stop the moment it feels tempted to guess.

HagiCode enforces this through InteractiveUserInputPolicy across interactive executors:

  • For question-capable CLIs (ClaudeCodeCli, PiCli, OmpCli, CodexCli, OpenCodeCli, and GitHubCopilotCli), the backend enables structured user-question tools across chat and proposal stages—except ProposalArchive, which always stays non-interactive.
  • Whenever the agent hits an ambiguous requirement, an out-of-spec gap, or mutually exclusive architectural options, it emits a structured question. SessionGrain immediately transitions from Openspecing or Executing into the stationary WaitingForReply state, records WaitingForReplyOrigin, and surfaces AwaitingInputCount so the user sees the session is blocked on input rather than spinning.
  • Once answered, the backend delivers the answer live to the active run or falls back to resuming the session via --resume from its recorded origin.

When running non-interactively (controlled by omitNonInteractiveHints), question tools are disabled, and the closing template contract (## Artifacts Ready, ## Implementation Complete / ## Implementation Paused, ## Archive Complete / ## Archive Failed) requires every assumption to be declared under ### Assumptions (if any) using the Assumption / Reason / Impact triad—either stop and ask, or put every inference on the record.

In Practice: A Low-Hallucination Daily Workflow

Putting all four defenses together, a typical cross-repository change in HagiCode follows a predictable rhythm:

# 1. Read real repository paths from the project instead of guessing
npx @hagicode/cli project repositories --id <project-id> --json

# 2. Create a proposal session with explicit write and read-only scope
npx @hagicode/cli proposal create \
  --project-id <project-id> \
  --chief-complaint "Repository scope
Writable repositories:
- repos/web
Read-only repositories:
- repos/hagicode-core

Tighten scope validation hints in the proposal drawer" \
  --default-title --json

# 3. Run planning (new -> explore -> ff) and wait until Reviewing settles
npx @hagicode/cli proposal generate --session-id <session-id> --enable-explore-mode --json
npx @hagicode/cli proposal get --session-id <session-id> --wait --json

# 4. Annotate if revisions are needed, or execute explicitly and answer WaitingForReply prompts
npx @hagicode/cli proposal execute --session-id <session-id> --json
npx @hagicode/cli proposal get --session-id <session-id> --wait --json

# 5. Review uncommitted code changes before archiving and running Super Commit
npx @hagicode/cli proposal archive --session-id <session-id> --json

Three habits make this workflow pay off quickly:

  1. Save proposals for real changes: Quick questions or one-line fixes belong in a default read-only chat session—do not force ceremony onto trivial edits.
  2. Spend review effort in Reviewing: Reviewing the repository scope table, diagrams, and acceptance checks in proposal.md, design.md, and tasks.md removes almost all ambiguity before apply touches a single source file.
  3. Keep archive and code commits separate: Let archive sync specs and move proposal artifacts in the main repository, while keeping code commits under human review and Super Commit grouping.

Conclusion

HagiCode's OpenSpec workflow curbs AI hallucinations and enforces behavioral discipline not through one clever prompt, but by distributing guardrails across four engineering layers:

  • State machine and exclusive boundaries: Planning, exploration, implementation, archiving, and committing never bleed into one another;
  • Structured scope contracts: targetRepositories and RepositoryScopeTable act as the single authority for read/write permissions;
  • Auditable planning directions and mechanical checks: Eight directions prevent conflicting instructions while CLI status recalculation and item-level evidence stop silent shortcuts;
  • WaitingForReply pause gates: Ambiguity triggers a pause for human clarification—or an explicit Assumption/Reason/Impact record—rather than silent guesswork.

When guardrails shift from polite reminders to system mechanics that prevent overreach, AI becomes far easier to trust in real multi-repository development.

📰 Read the original article on Dev.to AI

Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.