feat(impact): engine-first architecture - #136
Conversation
andev0x
commented
Aug 15, 2026
- add complexity assessment
- define operation kinds and their base scores
- add complexity assessment - define operation kinds and their base scores
andev0x
left a comment
There was a problem hiding this comment.
Phase 10 — ENGINE-FIRST Final Report
Executive Summary
The execution engine has been refactored to make strategy selection, context boundaries, model necessity, and token budgets deterministic before any model invocation. The model is now treated as a bounded reasoning component rather than an unguided classifier or filesystem resolver.
Key Performance & Behavior Metrics
| Metric / Scenario | Legacy Path (Before) | Engine-First Path (After) |
|---|---|---|
Simple Mutation ($prompt fix extra contents in @index.html) |
2–3 LLM calls, 3 mode transitions, manual chip press | 1 LLM call, 0 mode transitions, zero manual interaction |
| Initial Call Context | Raw text only (0 file context) | Bounded, exact target context pre-loaded |
| Deterministic Tasks (e.g., Template creation) | 1 LLM call | 0 LLM calls (Directly staged) |
| Ambiguous Targets | 1 LLM call (Model used as resolver) |
0 LLM calls (Early human_clarification route) |
| Complexity Scoring | Keyword frequency ("implement" |
Auditable execution factor matrix |
1. Architectural Findings & Diagnostics
Legacy Execution Trace
Analyzing $prompt fix extra contents in @index.html under the old architecture:
routePromptDirective (intent_dispatch.go:236)
└─► Fast-track misses (keyword heuristics, router.go:360)
└─► ClassifyDirectMutation misses (IsFrontendUI matches "index.html", router.go:197,241)
└─► Transition to /ask (commands.go:7027)
├─► LLM Call #1: Raw input ONLY (Zero target file context)
└─► Manual User Action: User must click "Forward to /investigate" chip
└─► /investigate (investigate.ClassifyIntent)
└─► IntentFrontendUI matched ──► Immediate bounce to /plan
└─► /plan ──► LLM Call #2: Plan synthesis (engine.go:818)
└─► User approves
└─► /build ──► LLM Call #3: Propose build patch (full file context)
Identified Engine-First Violations
-
No Pre-Invocation Strategy Selection:
routePromptDirectiveonly performed fast-tracking or handoffs without declaring an execution contract. -
Context-Deprived Initial Invocations: Ask-handoff LLM received raw text without target file buffers (
commands.go:7047-7054). -
Keyword-Based Complexity: Evaluated using naive keyword matches (e.g.,
"implement"$\rightarrow$ High,"remove"$\rightarrow$ Medium). -
Forced Mode Bouncing: Simple single-file prompt forced through
/ask$\rightarrow$ /investigate$\rightarrow$ /plan$\rightarrow$ /build. - Static Token Budgets: Hardcoded per-mode budgets (e.g., Hotfix: 2048, Plan: 1536).
-
Model as Filesystem Resolver: Target file resolution delegated down the chain to LLM/
expandFileRefs.
2. Technical Architecture Changes
Core Execution Strategy Contract
Introduced the internal/execution/strategy package with 6 bounded, composable execution strategies:
direct_deterministic(0 LLM calls)targeted_mutationtargeted_reasoningrepository_investigationmulti_file_planninghuman_clarification(0 LLM calls)
ExecutionStrategyProfile Record
Deterministically calculated by selector.go:Select prior to any LLM invocation. Tracks:
Intent • Strategy + Reason • ModelRequired • ModelDecision • Per-Target Resolution • Complexity • ContextKinds • ArtifactContract • ReasoningBudget • MaxOutputTokens • Deterministic • Escalation
Context Ownership & Envelopes
Implemented ContextEnvelope / ContextItem (context.go) with 10 explicit channels:
- Ownership & Auditing: Every item specifies
Owner(engine/model),Source,Relevance,Authority, andReasonForInclusion. - Budget-Aware Headers: Large files supply metadata/size bounds instead of full bytes on initial compile.
- Evidence-Driven Escalation:
Escalatorexpands envelopes only when concrete failure or structural evidence demands it.
Deterministic Target Resolution (selector.go)
Target files are fully resolved prior to prompt dispatch via collectTargets and resolveTarget:
- Resolution Classifications:
Explicit,Resolved,Inferred,Unresolved,Ambiguous. - Syntax Hardening: Unresolved syntax directly triggers
human_clarification(0 model calls). - Keyword Disambiguation: Path references (e.g.,
@architecture.md) are stripped prior to intent parsing to prevent false-positive architectural classification.
Factor-Based Complexity Scoring (complexity.go)
Replaced string/keyword heuristics with an auditable multi-factor matrix evaluated in complexity.go:Assess:
Complexity Factors:
├── Operation Family
├── Target & File Count
├── Dependency Depth
├── Ambiguity Index
├── Repository Scope
├── Cross-File Coupling
├── Verification Depth
└── Artifact Size
-
Calibration Samples:
- Single-file content edit
$\rightarrow$ Low - Component + CSS update
$\rightarrow$ Medium - 20-file refactor / structural redesign
$\rightarrow$ High
- Single-file content edit
Strict Model Invocation Contract (invocation.go)
Every provider call is instantiated via invocation.go:For(profile, n) and produces an auditable contract covering:
- Reason & Model Decision
- Included vs. Intentionally Excluded Context
- Artifact & Output Specifications (
MaxOutputTokens,ReasoningBudget) - Success Criteria & Fallback Directives
All metadata is fully inspectable via $inspect.
3. Workflow Comparison ($prompt)
BEFORE:
$prompt ──► Parse ──► Fast-Track Miss ──► /ask LLM (0 Ctx) ──► User Chip ──► /investigate ──► /plan LLM ──► Approve ──► /build LLM
AFTER:
$prompt ──► Parse ──► Strategy Selection ──► targeted_mutation ──► /build Bounded Executor ──► 1 Bounded LLM Call ──► Approve ──► Apply ──► Verify
Seams & Integration Points
- $hot Continuity: Preserves exact legacy contract. Reuses the new bounded executor while consuming strategy-selected adaptive output budgets (
hotfixOutputBudget(), defaulting to 2048). - Fall-Through Safety: Complex queries (
repository_investigation,multi_file_planning) naturally fall through to existing ask/investigate/plan pathways only when verified by structural evidence.
4. Verification & Testing
Test Suite Summary
Added 28 new test cases:
- 19 Package-Level Tests (
internal/execution/strategy)- Strategy selection correctness
- Complexity factor calibration
- Context envelope compilation & escalation
- Invocation contract accuracy & negative boundary paths
- 9 UI Integration Tests (
internal/ui)- Simple targeted mutation routing
- Deterministic task generation
- Clarification & ambiguity handling
- Escalation & adaptive token budgeting
$inspecttelemetry verification
- Regression Protection: Verified
TestHandleInputPromptRoutesToAskto ensure architectural fall-through remains operational.
Verification Matrix
[✓] go build ./...
[✓] go build ./cmd/izen
[✓] go vet ./...
[✓] go test ./... (125 packages)
[✓] go test -race ./...
[✓] golangci-lint run ./... (0 issues)
5. Scope & Boundary Limits
Explicitly Excluded / Unchanged Systems
-
Preserved Workflows:
$hotpipeline,$fix/$testcontinuity,/clear,/drop,/new. -
Preserved Core Types:
MutationSet,ExecutionProof,PromptEnvelope, provider token accounting. -
Preserved Engine Layers: Compressor fast-track (retained as fall-through),
pkg/appCLI surface,pkg/engine/pipelineFacade. - Preserved Safety Boundaries: Terminal states, transaction rollbacks, approval gates, race safety guarantees.
Known Follow-Ups
TargetedReasoningcurrently routes through/askhistory; a fully history-free ask variant will be handled in a subsequent iteration.- Direct deterministic tasks for fresh
$prompthandle initial template creation; plan-engine fast-tracks (undefined symbols, canonical mismatch) remain managed inside/plan.
- add strategy compilation logic - implement logic for different strategy types (targeted mutation, deterministic, clarification, reasoning, investigation, multi-file planning) - ensure deterministic behavior across identical profiles
andev0x
left a comment
There was a problem hiding this comment.
Phase 11 — EXECUTION GRAPH & RUNTIME CONVERGENCE — FINAL REPORT
Executive Summary
The execution engine has been converged around a typed, bounded Execution Graph (strategy.ExecutionGraph) that governs execution topology, model invocations, escalation ledgers, and transaction boundaries before execution begins. Mode switches (/build, /plan) are now decoupled UI presentation state rather than structural engine dependencies, and human approval/clarification nodes strictly enforce authority boundaries.
Key Performance & Behavior Metrics
| Metric / Scenario | Legacy Architecture | Engine-First Graph Path (Phase 11) |
|---|---|---|
| Simple Targeted Mutation | Bounces through /ask /investigate /plan /build
|
Single Graph (FLOW 1): resolve read reason propose approve mutate verify
|
| Model Invocations (Simple) | 2–3 unconstrained calls | Graph-Enforced Max 1 (Asserted via contract) |
| Deterministic Tasks | 1 LLM call |
FLOW 2: resolve read mutate verify (0 LLM calls) |
| Ambiguous / Unresolved | 1 LLM call (Model resolves filesystem) |
FLOW 3: resolve clarify (0 LLM calls, immediate halt) |
| Execution Observability | Telemetry-only token counts | Full Graph Topology + Escalation Ledger rendered in $inspect
|
1. Forensic Path Findings & Call Matrix
Repository-Wide Call Path Analysis
| Path | Entry Point | Strategy Selection | Model Invocations | MutationSet Boundary | Terminal Event |
|---|---|---|---|---|---|
$prompt targeted |
dispatchASTIntent routePromptDirective
|
strategy.Select (TargetedMutation) |
1 Bounded (hotfix executor) | Yes (PatchManager apply) |
buildResultMsg |
$prompt deterministic |
Same | DirectDeterministic |
0 | Yes (staged |
planResultMsg fast-track |
$prompt ambiguous |
Same | HumanClarification |
0 | No |
clarification stop |
$prompt repo/plan |
Same |
RepositoryInvestigation / MultiFilePlanning
|
1 (ask-handoff) + sub-engines |
Downstream |
promptHandoffMsg |
$hot |
handleHotfixCmd (commands.go:3097) |
Direct Executor (Stale graph cleared) | 1 | Yes |
buildResultMsg commit |
$fix |
runFixCmd (commands.go:5984) |
Legacy streaming path | 1 streaming | Yes | Build verify/recovery |
$test |
runTestCmd (commands.go:5735) |
N/A | 0 | No | testResultMsg |
/ask |
handleMessageContent |
N/A | 1 streaming | No | streamDoneMsg |
/investigate |
runInvestigateCmd (agents.go:25) |
Dispatcher (Heuristic/LLM) | 1–2 | No |
investigateResultMsg /plan or /build
|
/plan |
runPlanEngineCmd (commands.go:997) |
Microkernel / LX fast-tracks | 0–3 | Begins on /build entry |
planResultMsg |
/build |
runBuildCmd (commands.go:2369) |
Per-task fast-track | 0–1 per task | Yes (begin/commit/rollback) | buildResultMsg |
/review |
runReviewCmd (agents.go:463) |
N/A | 0 | No | reviewResultMsg |
2. Core Architectural Violations Resolved
- Missing Typed Execution Graph: Implied execution paths were previously unrepresented in code;
execution.ExecutionGraphwas restricted strictly to file mutations. - Absent Escalation Ledger:
Escalatorexpanded context dynamically, but previous-state, new-state, and evidence records were never persisted. - Decoupled Telemetry: Model invocation counts existed only in telemetry, unlinked to a pre-declared graph
InvocationContract. - Opaque Visual Telemetry:
$inspectrendered raw token counts but provided no vision into strategy topology or context escalations.
3. Execution Graph & Topology Design
Graph Specification (internal/execution/strategy/graph.go)
Introduced strategy.ExecutionGraph containing bounded, typed nodes:
resolve_target • read_target • gather_evidence • reason • propose • approve • mutate • verify • clarify
Graph Properties:
├── Explicit & Deterministically Ordered
├── Terminal-Aware & Cancellation-Safe
├── Evidence-Producing
├── MutationSet-Compatible (Deduplicated target set)
└── Inspectable via String() and Metrics()
Strategy $\rightarrow$ Graph Compilation Matrix (compile.go)
-
FLOW 1 (Simple Mutation):
resolve$\rightarrow$ read$\rightarrow$ reason(Model #1)$\rightarrow$ propose$\rightarrow$ approve$\rightarrow$ mutate$\rightarrow$ verify(Expected Invocations: 1) -
FLOW 2 (Deterministic Task):
resolve$\rightarrow$ read$\rightarrow$ mutate$\rightarrow$ verify(Expected Invocations: 0) -
FLOW 3 (Ambiguous / Unresolved):
resolve$\rightarrow$ clarify(Expected Invocations: 0) -
FLOW 4 (Multi-File / Investigation):
resolve$\rightarrow$ gather_evidence$\rightarrow$ reason$\rightarrow$ propose$\rightarrow$ approve$\rightarrow$ mutate$\times N$ $\rightarrow$ verify
4. Evidence-Driven Escalation & Human Boundaries
Audit-Ready Escalation Ledger
State transitions and context expansions are logged via EscalationRecord:
EscalationRecord:
├── FromState / ToState
├── TriggeringEvidence
├── AdditionalContext
├── EscalationReason
└── Timestamp (At)
- Zero Silent Escalations: Strategy shifts (e.g., expanding from single targeted edit to repo investigation) require explicit evidence records.
- Context Preservation:
Escalator.Expandappends incremental context toContextEnvelopewithout resetting execution state.
Strict Human Authority Enclaves
- Human Nodes (
approve,clarify): Force the execution graph intoawaiting_human. - State Resolution: Resumed strictly via
Complete(User Approved) orFail(User Rejected). - Rejection Guarantee: Rejecting an approval node guarantees 0 mutation applications (verified via unit tests). The model cannot override ambiguity into execution authority.
5. Workflow Comparison ($prompt)
BEFORE:
$prompt ──► Router ──► /ask ──► LLM #1 ──► Chip Action ──► /investigate ──► /plan ──► /build ──► LLM #2 ──► Patch
AFTER:
$prompt ──► Intent AST ──► Evidence Engine ──► Strategy Select ──► Compile Graph ──► Bounded Reason ──► Human Approve ──► Mutate ──► Verify
Seams & Regression Safety
- $hot Regression Guard: Added
engine_graphclearing guard inhandleHotfixCmdto prevent hotfix execution from polluting active strategy graphs. - Multi-File Mutation Ordering: Multi-target mutations compile one
mutatenode per target in resolution order under a singleMutationSetboundary. - Mode Decoupling: Routing to
/buildis handled as UI presentation state (modeChangeAuthorized), removing mode transitions as a dependency for internal engine execution.
6. Telemetry & $inspect Integration
$inspect now exposes full engine graph telemetry alongside execution proofs:
# ================================================================================
EXECUTION STRATEGY GRAPH
Strategy: targeted_mutation | State: completed | Expected Invocations: 1
NODES:
[1] resolve_target [COMPLETED] Target: @index.html (Explicit)
[2] read_target [COMPLETED] Bytes Read: 1,420
[3] reason [COMPLETED] Model Call #1 (Contract: Bounded Patch)
[4] propose [COMPLETED] Artifact: Unified Diff
[5] approve [COMPLETED] Human Decision: APPROVED
[6] mutate [COMPLETED] Applied to index.html (MutationSet #8412)
[7] verify [COMPLETED] Syntax Check: PASSED
# METRICS:
Total Nodes: 7 | Max Depth: 7 | Invocations: 1 | Escalations: 0 | Human Gates: 1
7. Verification & Test Suite
Testing Summary
- Strategy Package: Complete lifecycle tests (golden flows FLOW 1–5, terminals, cancellations, metrics, matrix items E/F/I/L/Q/R).
- UI Layer: Graph compilation on dispatch, clarification stops, model failure recovery, rollback integrity, stale-graph clearing, and
$inspectrendering.
Verification Results
[✓] go build ./...
[✓] go build ./cmd/izen
[✓] go vet ./...
[✓] go test ./... (125 packages)
[✓] go test -race ./... (125 packages)
[✓] golangci-lint run ./... (0 issues)
[✓] Execution Graph Regression Suite (All Passed)
8. Remaining Architectural Debt & Boundaries
Remaining Debt
-
$fixStreaming Path:$fixcontinues to use a legacy streaming path outside the strategy layer; calls do not currently write anInvocationContract. -
Sub-Engine Boundary Recording: Node recording for intermediate steps in
/investigateand/planis managed inside modes rather than at raw engine entry boundaries.
Explicitly NOT Changed
- Command Contracts:
/clear,/drop,/new,$hotdirect path contracts preserved. - Core Semantics:
MutationSetsingle-transaction boundaries,ExecutionProofauthority, token accounting rules, and terminal safety states remain untouched.
- add before and after architecture diagrams - detail ownership changes in UI to runtime executor - describe new runtime contracts and command handlers - outline remaining risks for future migrations
- add model resolution - apply semantic repository updates
- document execution lifecycle changes - detail event ownership rules - explain new context policy design - describe casual chat routing updates
andev0x
left a comment
There was a problem hiding this comment.
PART 1 — Event semantics (internal/execution/executor.go, internal/events/events.go)
- New execution.provider.response event emitted only on successful responses.
- model.invoked now fires at invocation start; usage travels on provider.response.
- Failed invocations emit no artifact/response/approval and record zero proof invocations; execution.finished is terminal and always last.
PART 2 — Strategy-owned ContextPolicy (strategy/strategy.go, selector.go, context.go)
- New ContextPolicy (none / target_file_only / repository); each strategy branch sets its own; Compiler.Compile returns an empty envelope for none; executor compileContext derives channels from the policy.
PART 3 — Casual chat routing
- New direct_response strategy: "hi" → Intent=casual_chat, Strategy=direct_response, zero context (0 channels, no file read, no workspace scan).
PART 4+5 — Presentation reducer (internal/presentation/execution_projection.go)
- Single ExecutionViewState (Idle/Running(step)/WaitingApproval/Completed/Failed) + Debug and Human timelines, reduced purely from runtime events; terminal events always transition. Wired into the gated UI path (model.execView, dock text derives only from the projection).
Tests — new runtime/strategy/presentation/UI suites cover all five required regression areas (artifact ordering, casual-chat zero-context, DirectResponse selection, clean terminal on provider failure, no impossible UI states).