{"modulePath":"github.com/memcode-ai/memcode","version":"v0.56.16","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package plan\n\nPackage plan holds the plan-mode lifecycle as a real state machine. The lifecycle itself is unchanged — idle → research → present → approve → apply, driven by /plan, the enter\\_plan/execute\\_plan/cancel\\_plan tools, and the approval selector — but it used to live as four exported booleans whose transitions were field assignments scattered across runtime (loop.go set Presented, chat.go cleared Applying, invariants lived as comments). Every wrong-plan/clobber/stale-flag incident traced back to a write the package could not guard.\n\nNow the Controller's fields are unexported and its named transitions are the only way to move it: the compiler rejects outside writes, illegal states like \"Active and Applying at once\" are unrepresentable, and each transition's guard is a table-tested rule instead of a convention.\n\nTransitions return Effects (data) instead of performing side effects: the machine never touches the session, the observer, the event log, or the disk. The runtime applies Effects AFTER the machine's lock is released, so the lock can never wrap a printf/observer callback — the old \"don't hold s.mu across EnterPlan\" deadlock trap is gone structurally, and so is the unlocked Task/LastPlan reset race (every read and write now goes through c.mu).\n\n## Functions\n\n```go\nfunc PlanShaped(text string) bool\n```\nPlanShaped reports whether text carries a plan's mandated skeleton: at least two numbered step lines. A \"simplify the plan\" revision keeps its numbered steps no matter how short it gets; a prose answer to a follow-up has none.\n\n## Types\n\n```go\ntype ApproveOutcome struct {\n\tContract string\n\tArmed    bool\n}\n```\nApproveOutcome carries the selected apply contract. Armed=false means no contract existed (nothing pinned and no fallback) — the lifecycle returns to Idle and nothing must execute.\n\n```go\ntype Controller struct {\n\t// contains filtered or unexported fields\n}\n```\nController owns the plan-mode lifecycle. Held as a pointer on Session (s.planCtl); the zero value is a ready Idle machine. All fields are unexported ON PURPOSE — state moves only through the transition methods below, and reads go through the locked accessors. Nil-receiver-safe reads let callers skip the \\`planCtl != nil\\` dance.\n\n```go\nfunc (c *Controller) Analytical() bool\n```\nAnalytical reports whether any analytical mode (\"plan\" or \"research\") is active.\n\n```go\nfunc (c *Controller) ApplyAborted()\n```\nApplyAborted clears an armed-but-never-run contract (commit-gate abort, Esc in the approval window): Applying → Idle.\n\n```go\nfunc (c *Controller) ApplyContract() string\n```\nApplyContract returns the armed contract text (\"\" outside Applying).\n\n```go\nfunc (c *Controller) ApplyDone()\n```\nApplyDone ends the apply turn: Applying → Idle, contract cleared. It is one of exactly two clears of the apply state (with ApplyAborted) — the raw tuple-assignment clears that used to live in runtime are gone.\n\n```go\nfunc (c *Controller) Approve(lastTextFallback string) (Effects, ApproveOutcome)\n```\nApprove is the /execute transition: Researching|Presented → Applying, arming the apply contract. Contract selection lives here — the PINNED plan wins; lastTextFallback (the session's last rendered text) is used only when nothing was ever pinned. No contract at all → Idle with Armed=false (nothing may execute). From Idle/Applying → no-op (executePlanTool turns that into a model-facing error; re-arming mid-apply is structurally impossible).\n\n```go\nfunc (c *Controller) BeginTurn()\n```\nBeginTurn is the per-turn reset: a presented plan goes back to Researching at the top of the next plan-mode turn, so an interrupted turn (Ctrl-C on a clarifying question) never leaves a stale \"Plan ready\" selector armed with nothing rendered behind it. No-op in every other phase.\n\n```go\nfunc (c *Controller) Cancel() Effects\n```\nCancel abandons the plan session: Researching|Presented → Idle. lastPlan and slug survive (recall\\_plan still works; only Enter wipes them). No-op outside plan mode — Cancel is called defensively from several TUI paths.\n\n```go\nfunc (c *Controller) ConsumeCommitGate() bool\n```\nConsumeCommitGate consumes the one-shot: true exactly once per arm.\n\n```go\nfunc (c *Controller) Enter(currentModel string, opts ...Opt) Effects\n```\nEnter starts a plan session: Idle → Researching. Already planning or applying → silent no-op (zero Effects): double /plan and enter\\_plan-while-planning are normal user races, and entering during an apply would corrupt the lifecycle. currentModel is saved for restore at exit.\n\n```go\nfunc (c *Controller) Epoch() int\n```\nEpoch identifies the current plan session for async-verdict staleness checks.\n\n```go\nfunc (c *Controller) InFlow() bool\n```\nInFlow reports any non-Idle phase (planning or applying).\n\n```go\nfunc (c *Controller) IsApplying() bool\n```\nIsApplying reports the apply phase — the old Applying boolean.\n\n```go\nfunc (c *Controller) Mode() string\n```\nMode returns the active analytical mode (\"plan\" or \"research\") when in Researching or Presented phase, or \"\" when Idle/Applying.\n\n```go\nfunc (c *Controller) NotePlanTurn(hasOutput bool) Effects\n```\nNotePlanTurn records a proposed/revised plan after a planning turn that produced output, advancing the revision counter for the memory trail.\n\n```go\nfunc (c *Controller) NoteReflect() int\n```\nNoteReflect counts a reflection-gate research round; returns the new count for the status line. No-op (returning the current count) outside plan mode.\n\n```go\nfunc (c *Controller) Phase() Phase\n```\nPhase returns the current lifecycle phase.\n\n```go\nfunc (c *Controller) PhaseEpoch() (Phase, int)\n```\nPhaseEpoch returns phase and epoch atomically — the pair the intake gate stamps on a submission so an async verdict can be staleness-checked later.\n\n```go\nfunc (c *Controller) Planning() bool\n```\nPlanning reports plan mode proper (Researching or Presented in \"plan\" mode).\n\n```go\nfunc (c *Controller) PolicyOverride(target string) map[string]any\n```\nPolicyOverride reports the per-operation policy for a target, nil when none.\n\n```go\nfunc (c *Controller) Present(text string) (Effects, PresentOutcome)\n```\nPresent lands a synthesis: Researching|Presented → Presented. The pin guard lives HERE: the contract is replaced only when nothing is pinned yet or the synthesis is plan-shaped — a conversational answer to a related follow-up must never overwrite the contract /execute will run (the clobber bug). When the pin is replaced, Effects.SavePlan carries the text for the durable copy.\n\n```go\nfunc (c *Controller) Presentable() bool\n```\nPresentable reports that the most recent plan turn landed an approvable plan — the TUI raises the selector on it. Never true in research mode.\n\n```go\nfunc (c *Controller) RecordSaveSlug(slug string)\n```\nRecordSaveSlug records the saved-plan filename slug minted when the plan was first written to the plans store — reused across revisions so one plan session is one file.\n\n```go\nfunc (c *Controller) ReflectRounds() int\n```\nReflectRounds returns the reflection-gate round count for this session.\n\n```go\nfunc (c *Controller) Researching() bool\n```\nResearching reports whether \"research\" mode is active.\n\n```go\nfunc (c *Controller) ResolveCommitGate()\n```\nResolveCommitGate arms the commit-before-work one-shot: the plan selector's commit choice was answered, so the apply turn's gate must not re-ask. Armed only while a plan is on the table (or already approved — the selector's Execute row fires ExitPlan first in some flows).\n\n```go\nfunc (c *Controller) Revision() int\n```\nRevision returns how many times the current plan has been revised.\n\n```go\nfunc (c *Controller) SetPolicyOverride(target string, fields map[string]any)\n```\nSetPolicyOverride attaches policy to the plan currently in flight. Scoped to this operation only; Enter and the terminal transitions clear it.\n\n```go\nfunc (c *Controller) Slug() string\n```\nSlug returns this plan session's saved-plan filename slug (\"\" until first saved).\n\n```go\nfunc (c *Controller) Snapshot() (task, draft string)\n```\nSnapshot returns the plan anchor task + pinned draft atomically — what the intake classifier judges relevance against.\n\n```go\nfunc (c *Controller) UpdateSavedModel(model string)\n```\nUpdateSavedModel updates the model to restore when exiting analytical mode, so an explicit mid-plan or mid-research /model change persists across exit.\n\n```go\nfunc (c *Controller) Yolo() bool\n```\nYolo reports the auto-resolve/auto-execute flag for this plan session.\n\n```go\ntype Effects struct {\n\tSetModel    string      // non-empty → sess.SetModel (planner on Enter, saved on Approve/Cancel)\n\tEmit        events.Kind // non-empty → emit with EmitPayload\n\tEmitPayload map[string]any\n\tClearTodos  bool   // Enter: a new plan is a new unit of work — drop the prior checklist\n\tSavePlan    string // Present, only when the pin was actually replaced (durable ~/.memcode/plans copy)\n}\n```\nEffects is what a transition asks the caller to do. The machine returns it under no lock obligation on the caller's side; runtime applies it via Session.applyPlanEffects after the transition returns.\n\n```go\nfunc (e Effects) Zero() bool\n```\nZero reports a no-effect result — the signature of a refused (no-op) transition.\n\n```go\ntype Opt func(*Controller)\n```\nOpt is a functional option for Enter — the hook for plan-scoped transient state. Enter resets everything first, then applies opts, so a stale flag can never leak into the next plan session; after unexporting, opts are the ONLY write path to task/yolo, which makes reset-before-opts structural.\n\n```go\nfunc WithMode(mode string) Opt\n```\nWithMode sets the analytical mode (\"plan\" default, or \"research\").\n\n```go\nfunc WithTask(task string) Opt\n```\nWithTask anchors this plan session to the task text that started it — the intake gate classifies later submissions against this anchor.\n\n```go\nfunc WithYolo() Opt\n```\nWithYolo suppresses human-in-the-loop questions during planning (auto-resolving them with the model's recommended choice); the TUI also auto-executes the plan without showing the approval selector.\n\n```go\ntype Phase int\n```\nPhase is the plan lifecycle's single word of truth. Exactly one holds at any moment; the zero value is Idle so a zero Controller is out of plan mode.\n\n```go\nconst (\n\tIdle        Phase = iota // no plan lifecycle in flight\n\tResearching              // plan mode: drafting/revising, no approvable plan THIS turn\n\tPresented                // plan mode: a synthesis landed this turn — the selector may raise\n\tApplying                 // an approved contract is armed or executing\n)\n```\n\n```go\nfunc (p Phase) Planning() bool\n```\nPlanning reports whether the phase is inside plan mode proper (research or presented) — the old \\`Active\\` boolean.\n\n```go\nfunc (p Phase) String() string\n```\n\n```go\ntype PresentOutcome struct{ Pinned bool }\n```\nPresentOutcome reports whether Present replaced the pinned contract. A non-plan-shaped synthesis still presents (the selector raises over the OLD pin, which is still valid) but does not replace it.\n\n","path":"github.com/memcode-ai/memcode/internal/agent/plan","name":"plan","synopsis":"Package plan holds the plan-mode lifecycle as a real state machine.","isRedistributable":true}
