Skip to content

feat(plan): operator-driven plan-approval gate (issue #206) - #293

Merged
JAORMX merged 10 commits into
mainfrom
feat/plan-approval-gate
Jul 22, 2026
Merged

JAORMX merged 10 commits into
mainfrom
feat/plan-approval-gate

Conversation

@JAORMX

@JAORMX JAORMX commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements the operator-driven plan-approval gate from #206: a present plan → iterate → approve → execute loop for plan mode, reusing the ADR-0062 guardrail approve-once spine. Closes the gap where plan mode had no structured "plan ready" signal and no plan-specific approval affordance.

How it works

  1. PresentPlan tool (read-only, PlanOnly-gated to the plan-mode catalog projection) — the model signals "plan ready". It is not ExitPlanMode: it doesn't flip the mode. The run parks on a PlanOriginated permission ask.
  2. surfacePlanAsk (sibling of askHookApproval) reuses the shared surfaceAsk spine unchanged. Verdict → mode: allow-once → default, allow-always → accept-edits, deny → iterate (stay in plan mode).
  3. Mode flip at the run terminal boundary (never mid-turn): the verdict sets run-scoped planApprovedTarget; the run terminates StopPlanApproved (clean, reopen-recoverable, string passthrough); terminateComplete calls SetMode from StateCompleted (the SetMode-rejects-Running/Awaiting invariant is preserved). Next run: engineAndWorkspaceFor CASE 1 rebuild swaps plan-slot → execute model (existing mechanism).
  4. AskOrigin enum + serialized PlanOriginated marker — cross-process resume skips preHook, mirroring HookOriginated. Retires the session.go:230-231 "second serialized bit → enum" contract.
  5. Atomic ApprovePlan RPC (proto + gRPC streaming + HTTP POST /v1/sessions/{id}/plan:approve) — composes ResumeApproval → flip → continuation run carrying PlanApprovedProceedText, preventing the half-executed two-step. FAILED_PRECONDITION mid-run; ErrNotAwaitingPlan when not parked on a plan ask. ACP gets no new method (composes set_mode + prompt).
  6. plan_mode_auto_approve — opt-in, operator-tier-only, default-off, composition-side observer (Service.MaybeAutoApprovePlan, never in the loop). Headless auto-approve drives execution on both the live and cross-process paths. Loud "NO HUMAN REVIEW" narration.
  7. mecatui plan-approval modal — distinct "Plan ready for review" surface naming both models, [A]pprove & run / [W] auto-accept edits / [D] iterate, plan_approved footer label. Detects the plan ask by Tool == "PresentPlan" (proto PermissionAsk unchanged — no wire/provenance field added).

Layers touched

engine/session, engine/tool, engine/agent, internal/app, internal/adapter/server, internal/adapter/permconfig, internal/configgen, cmd/mecated, cmd/mecatui, contracts/proto. engine/governance and engine/port untouched (ask machinery reused). engine/CHANGELOG.md entries all classified Added (minor).

Prior art

Mirrors Claude Code's explore-plan-act flow but keeps the transition operator-driven (no model-called ExitPlanMode), reusing the harness's own guardrail approve-once primitive rather than a parallel channel.

Review

Independent 6-agent panel (Spec / Standards / Security / Architecture / Library-reuse / Duplication) + QA test-adequacy review. Spec/Standards/Security: zero findings. Fixed the cross-confirmed set: auto-approve live-path continuation, verdict→mode helper extraction, shared relay-event extraction, two-Build cross-process restart e2e, HTTP 409/404 coverage, merged-stream ordering, deny-terminal + parked-ask flake.

Test plan

  • go build ./..., go test ./..., cd engine && go test ./... — green
  • task lint (0 issues), task api:check, task docs:check (matlatl strict: 0 broken)
  • go run ./cmd/mecademo prints a full offline session
  • New tests: engine plan-ask suite, two-Build restart e2e, ApprovePlan gRPC/HTTP/SSE + error codes + ordering, auto-approve suite, catalog PlanOnly gate, mecatui plan modal suite

Docs: ADR 0069 + architecture / IMPLEMENTATION-NOTES / usage / PRODUCTION-READINESS updated to shipped; llms.txt regenerated.

JAORMX and others added 2 commits July 22, 2026 02:52
Add the present-plan -> iterate -> approve -> execute loop to plan mode,
reusing the ADR-0062 guardrail approve-once spine.

- PresentPlan tool (read-only, PlanOnly-gated to plan-mode catalog): the
  model signals plan-ready; the run parks on a PlanOriginated permission ask.
- surfacePlanAsk (sibling of askHookApproval) over the shared surfaceAsk
  spine; verdict->mode (allow-once->default, allow-always->accept-edits,
  deny->iterate). Mode flip lands at the run terminal boundary via
  Run.planApprovedTarget + terminateComplete SetMode (SetMode mid-turn
  invariant preserved). StopPlanApproved clean terminal.
- AskOrigin enum + PlanOriginated serialized marker (cross-process resume
  skips preHook, mirrors HookOriginated).
- Atomic ApprovePlan RPC (proto + gRPC + HTTP plan:approve): ResumeApproval
  -> flip -> continuation run with PlanApprovedProceedText, preventing the
  half-executed two-step.
- plan_mode_auto_approve flag (operator-tier, default off, composition-side
  observer) for headless; live + cross-process paths both drive execution.
- mecatui plan-approval modal (A/W/D -> allow-once/allow-always/deny),
  both-model names, plan_approved footer label.

Co-Authored-By: mecatl <[email protected]>
ADR 0069 (plan-approval gate) records the decision; architecture,
IMPLEMENTATION-NOTES, usage (+ gRPC/HTTP/mecated subdocs), and
PRODUCTION-READINESS updated to shipped. llms.txt regenerated.

Co-Authored-By: mecatl <[email protected]>
JAORMX and others added 8 commits July 22, 2026 07:11
- govulncheck: GO-2026-5970 (infinite loop on invalid input in
  golang.org/x/text/unicode/norm) fixed in v0.39.0; bump from v0.38.0.
- docs: regenerate llms.txt (heading count drifted 1601 -> 1602 after a
  late docs edit); the matlatl llms freshness gate now matches.

Co-Authored-By: mecatl <[email protected]>
The gate only fired when the model CHOSE to call PresentPlan, and nothing
told it to — a model read an inline 'acceptable' as approval and kept
executing without ever surfacing the gate. Make the workflow explicit at
three reinforcing layers:

- Spec().Description: call EXACTLY ONCE when the plan is complete, then
  STOP; an inline 'acceptable'/'looks good'/'approved' in chat is NOT
  approval.
- applyPlanModePosture / planModePostureNote on the plan-mode session
  engine's Role (create-in-plan AND the CASE-1 flip-into-plan rebuild).
- the plan-mode volatile prompt suffix (engine/prompt/builder.go) carries
  the same contract per-turn, covering plan sessions on the shared engine.

Mirrors the 'plan mode is a reinforced system-reminder, not a one-shot
instruction' posture (ADR 0024; gauntlet #7 'we told the model not to
doesn't work').

Co-Authored-By: mecatl <[email protected]>
The plan-approval modal showed only 'plan ready for operator approval' —
the operator couldn't read what they were approving. The plan lived only in
the model's preceding assistant text; the PresentPlan args carried just a
one-line note, so the plan never reached the wire or the modal.

- PresentPlan schema gains a 'plan' string arg; the model passes the full
  plan there (and still presents it in message text for the transcript).
  Args flow through the existing PendingAsk.Args -> PermissionAsk.args
  channel, so no proto/port change. Gauntlet #7 holds: EvApproval stays
  metadata-only (no args).
- The plan-mode prompt notes + volatile suffix now instruct the model to
  pass the full plan in the 'plan' argument.
- renderPlanApprovalModal renders the plan from ask.Args via
  planBodyFromArgs, sanitized; a plan longer than maxPlanLines (12) shows a
  line cap + 'ctrl+t expand' affordance (the established reveal pattern).
  Graceful fallback to note, then to the reason line, when args carry no
  plan (older models, malformed JSON).

Co-Authored-By: mecatl <[email protected]>
…ng (#206)

Clicking 'iterate' ([D], a deny verdict) made the agent KEEP WORKING
immediately — the engine recorded 'revise and re-present' and the run
CONTINUED in the same turn, so the model reworked the plan with no
operator input. Iterate should pause and hand the operator the input box.

A deny of a plan ask now terminates the plan run cleanly via the new
StopPlanIterate (a clean, completed, Reopen-recoverable terminal, string
passthrough): surfacePlanAsk sets the run-scoped planIterateRequested flag,
runLoop terminates StopPlanIterate, and the session stays ModePlan so the
operator's next typed prompt drives the revision. Wired on the live path,
the cross-process ResumeApproval resume path, and the ApprovePlan RPC deny
path (no continuation run — the same pause). mecatui renders a
'plan iterate · awaiting your feedback' footer label and returns to idle
with the input focused. mecatequi treats it as a clean exit. plan_iterate
is not in the subagent salvage allow-set (an intentional pause, not an
empty terminal).

Co-Authored-By: mecatl <[email protected]>
The plan rendered as raw markdown lines split on newlines with no width
wrapping, so long bullets/paragraphs ran off the right edge of the card and
were unreadable.

Render the plan through the established glamour wrap path at the modal's
card content width: extract markdownWidth(src, w) (the width-parameterized
core of markdown — normalizeEmojiWidth + width-keyed glamour cache) so the
conversation markdown path is byte-identical, and wrap the plan via
cardTextWidth(width). The maxPlanLines cap now counts WRAPPED display lines
(post-wrap), so a 3-source-line plan that wraps to 30 rows caps correctly;
ctrl+t expand still reveals all.

Co-Authored-By: mecatl <[email protected]>
Issue #206 shipped a plan-approval gate that depended on the model CALLING
PresentPlan, but nothing told the model the gate existed or that it must use
it — the model improvised and the gate never fired. Generalize the lesson
into a named rule so it is not repeated:

A model-facing gate/affordance whose correct operation depends on the
model's behavior MUST ship BOTH (a) a model-visible prompt-layer
instruction (the *PostureNote + applyXPosture idiom) AND (b) an executable
test proving the instruction lands in the built engine's system prompt via
the REAL factory path.

- AGENTS.md: new 'Things That Will Bite You' entry naming the rule.
- docs/adr/0070: records the convention (instruction + system-prompt
  discoverability gate, one concrete test per affordance — no framework).
- Strengthen TestPlanModeEngineSystemPromptContainsPlanApprovalContract to
  assert the full contract clause-set against req.System.StablePrefix (the
  Role layer applyPlanModePosture owns), not the combined Render() — the
  volatile suffix duplicates the prose, so Render() would make the oracle
  vacuous. Mutation-proven: removing the factory wiring turns it red.

Co-Authored-By: mecatl <[email protected]>
The collapsed centered card was unusable: it hid the plan behind a 12-line
cap, ctrl+t expanded it but STILL gave no scrolling, so a long plan could
never be read. Replace it with a proper reading view.

A plan ask now opens a dedicated full-screen scrollable viewport (planVP)
that fills the conversation region: the WHOLE plan, glamour-wrapped to the
view width, no collapse, no ctrl+t gate. Mouse wheel, pgup/pgdn, up/down,
and home/end scroll through all of it. The action buttons ([A]pprove & run /
[W] auto-accept edits / [D] iterate) pin to a persistent bar at the bottom
with a scroll hint, so the operator reads then acts without losing their
place. Resize preserves the scroll offset; resolve/retract/session-reset
clears planVP. The generic (non-plan) permission modal is unchanged.

Co-Authored-By: mecatl <[email protected]>
Clicking 'Approve & run' flipped the mode and showed 'plan approved ·
executing' but then sat idle — no execution run started, and the header
still read 'mode plan'. The atomic approve->flip->continue existed only on
the ApprovePlan RPC + headless auto-approve paths; the interactive TUI path
(ResumeApproval frame) never sent the proceed message.

Two halves:

- Fire the proceed prompt on ResultMsg{plan_approved} (submitProceedPrompt)
  — NOT immediately after SendApproval, because the Converse handler ignores
  a second Prompt on the same stream and the run-entry funnel needs the
  approval run terminated. The proceed opens a fresh stream carrying
  planApprovedProceedText (a ui-layer literal byte-identical to
  agent.PlanApprovedProceedText; ui cannot import engine), so the execution
  run starts on the execute model. Deny (plan_iterate) and non-plan results
  do not fire it.
- Refresh the mode + model echo so the header shows the flipped mode and
  execute model: ResolvedModelMsg gains Mode (RefreshResolvedModelCmd now
  captures SessionSnapshot.Mode), fired alongside the proceed on
  plan_approved; onResolvedModelMsg applies the new mode + effectiveModel.

Co-Authored-By: mecatl <[email protected]>
@JAORMX
JAORMX merged commit de6dbb6 into main Jul 22, 2026
14 checks passed
@JAORMX
JAORMX deleted the feat/plan-approval-gate branch July 22, 2026 14:56
JAORMX pushed a commit that referenced this pull request Jul 24, 2026
)

Addresses only the MECHANICAL findings from the post-merge review of the
plan-approval gate (issue #206 / PR #293). The design-loaded findings
(approve-then-cancel mode-flip loss, disconnect durable-log-tail drop,
continuation-logic dedup) are deliberately left for separate decisions.

- server/http.go: planModeFromString lowercases BEFORE trimming the
  PERMISSION_MODE_ prefix, so the documented case-insensitive spelling
  ("permission_mode_default") is honoured instead of silently falling
  through to deny/iterate.
- server/service.go: autoApproveWaitTimeout var -> const (never overridden;
  matches its sibling const autoApprovePollInterval).
- app/build.go: --plan-mode-auto-approve on an INTERACTIVE deployment now
  WARNs it is INERT (the flag only fires headless), mirroring
  normalizeAskReviewerModel's inert-when-interactive posture, instead of
  narrating a "NO HUMAN REVIEW" fact that does nothing.
- mecatui/ui/view.go: the footer "W auto-accept" hint is gated on
  ask.offerAlways, matching the action bar; a surfaced child plan ask
  (offerAlways=false) no longer advertises a key that no-ops.
- permconfig: new plan_mode_auto_approve_test.go pins the operator-tier-only
  boundary (a project-tier plan-mode-auto-approve: is ignored with a WARN) —
  the one operator-tier scalar whose boundary was previously untested.
- adr/0069: amendment note recording the deny path terminates via
  StopPlanIterate (superseded the ADR's "loop continues" design; frozen ADR
  corrected by note, not rewritten in place).

NOTE: llms.txt must be regenerated (task docs:llms) after the ADR edit; the
sandbox could not fetch the matlatl module to do so here.

Co-authored-by: Claude Opus 4.8 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant