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:
- 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.
- 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.
-
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. -
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:
-
Multi-step queueing without premature transitions: When
proposal generateruns, the backend enqueuesopenspec-v1-new, optionalopenspec-v1-explore, andopenspec-v1-ffin order based on Explore mode. Step 1 usesMessageAssociationType.ProposalGenerationStart, which intentionally keeps the session inOpenspecingso it cannot jump toReviewingearly. Only afterProposalGenerationfinishes andOpenSpecValidationService.ValidateProposalFilesconfirms thatopenspec/changes/<proposalName>/proposal.mdexists on disk does the session transition toReviewing. -
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 intasks.md, runningopenspec archive, or runninggit add/commit/push. It also forbids writing non-implementation work—such as archiving, syncing main specs, committing, opening PRs, or deploying—intotasks.md. Bothnewandarchiveadditionally 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 ofproposal.md,design.md, orspecs. 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 intoopenspec/specs/, directory archiving, and optional archive commits, while strictly forbidding implementing unfinished code tasks. Even whencommit_when_archiveis enabled, Git commits are restricted exclusively to the MonoSpecs root repository and never touch code repositories underrepos/.
-
Planning (
-
No hidden chaining: Returning from a command only means the request was queued. Each stage settles at
ReviewingorExecutionCompletedand waits for a human decision—sending revision notes viaproposal annotate, or explicitly invokingexecuteorarchive.
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
rootbefore any write: Before creating or updating files, the agent must runopenspec list --jsonand inspectroot. Whenrootisnull, the agent is forbidden from runningopenspec initas 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 fromopenspec status --change "<name>" --json(planningHome,changeRoot, andartifactPaths.<id>.resolvedOutputPath), and resolved symlink paths outsidechangeRootare 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-visualizationis enabled,PlanningDirectionInstructionRendereruses the built-invisualiseskill to emitvisualizerblocks and automatically omits the ASCIIprototypefragment at render time, ensuring two contradictory UI-prototype instructions never reach the same prompt. -
Per-CLI defaults and snapshots:
IProposalPlanningDirectionDefaultsStorestores default directions per Agent CLI, and every run persists anoptionsSnapshotcapturingplanningDirections,enableExploreMode,proposalContentLanguage, andheroIdfor traceability. -
Paired design-guide checks: Before writing the first artifact in
ff, the prompt checks the project root and scoped repository roots for bothDESIGN.mdand.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: Duringff, the agent must re-runopenspec status --change "<name>" --jsonafter each artifact rather than relying on cached memory, and it is forbidden from skippingspecson its own judgment. Only maintenance changes with no spec-level behavior change may declareskip_specs: truein.openspec.yaml(orretire_capabilities: truewhen 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
applyfinishes, 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, andGitHubCopilotCli), the backend enables structured user-question tools across chat and proposal stages—exceptProposalArchive, 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.
SessionGrainimmediately transitions fromOpenspecingorExecutinginto the stationaryWaitingForReplystate, recordsWaitingForReplyOrigin, and surfacesAwaitingInputCountso 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
--resumefrom 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:
- 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.
-
Spend review effort in
Reviewing: Reviewing the repository scope table, diagrams, and acceptance checks inproposal.md,design.md, andtasks.mdremoves almost all ambiguity beforeapplytouches a single source file. -
Keep
archiveand code commits separate: Letarchivesync 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:
targetRepositoriesandRepositoryScopeTableact 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;
-
WaitingForReplypause 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.
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.