Documentation
¶
Overview ¶
Package modes implements autonomous motion behaviors (Freestyle, continuous chat) as clients of the motion engine. Modes emit bounded, named segments that deterministic code applies through the engine's retarget API — never a parallel sampler, never transport commands, and never per-turn low-level stream replacement (docs/motion-retargeting.md, "Route Policy Learned On Hardware").
Index ¶
- Constants
- type Announcement
- type Arrangement
- type DecideFunc
- type Decision
- type DecisionInput
- type EarlierScore
- type EdgeDecision
- type EdgeInput
- type EdgeStatus
- type Engine
- type FreestyleStatus
- type Manager
- func (m *Manager) ActivateEdge(ctx context.Context) (Status, error)
- func (m *Manager) ApplyMotionReview(ctx context.Context, ticket ReviewTicket, target motion.MotionTarget, ...) error
- func (m *Manager) BeginUserPause() (func(keepPaused bool), bool)
- func (m *Manager) BeginUserResume() (func(resumed bool), bool)
- func (m *Manager) BeginUserStop() func()
- func (m *Manager) CancelChatTarget(generation uint64)
- func (m *Manager) EarlierScores() []EarlierScore
- func (m *Manager) MotionReviewTicket() (ReviewTicket, bool)
- func (m *Manager) NotifyAutopilotSettingsChanged()
- func (m *Manager) NotifyChatActivity() uint64
- func (m *Manager) NotifyChatActivityComplete(activityID uint64)
- func (m *Manager) NotifyChatStop()
- func (m *Manager) NotifyChatTarget(generation uint64, target motion.MotionTarget) bool
- func (m *Manager) NotifySpeechPlaybackComplete(requestID string) bool
- func (m *Manager) NotifyUserStop()
- func (m *Manager) PrepareChatTarget() uint64
- func (m *Manager) ReconsiderAfterChat()
- func (m *Manager) ResetSessionArc() bool
- func (m *Manager) ResumeEdge(ctx context.Context) (Status, error)
- func (m *Manager) SessionArcSnapshot() SessionArc
- func (m *Manager) SetSessionArcPercent(percent int) bool
- func (m *Manager) Shutdown()
- func (m *Manager) Start(ctx context.Context, mode string) (Status, error)
- func (m *Manager) Status() Status
- func (m *Manager) Stop(reason string)
- type Options
- type Planner
- type PositionBand
- type ReviewTicket
- type Segment
- type SessionArc
- type SpeechSource
- type SpeedStep
- type Status
- type TimingPreference
- type VariabilityPreference
Constants ¶
const ( SpeedTrendSteady = "steady" SpeedTrendRising = "rising" SpeedTrendEasing = "easing" )
SpeedTrend summarizes where speed has been going, so the model can answer "have I been sitting still?" without being told to guess.
const ( ShapePhaseSteady = "steady" ShapePhaseBuilding = "building" ShapePhaseHolding = "holding" ShapePhaseRising = "rising" ShapePhaseFalling = "falling" ShapePhasePeak = "peak" ShapePhaseBackingOff = "backing_off" ShapePhaseTeasing = "teasing" ShapePhaseEasing = "easing" ShapePhaseFinished = "finished" )
Shape phases reported in the Freestyle status.
const ( // ModeFreestyle is the autonomous arrangement planner. ModeFreestyle = "freestyle" // ModeAutopilot is Freestyle's loop with the segment choice delegated to // an injected LLM curation step; every failure falls back to the // deterministic planner (see autopilot.go). ModeAutopilot = "autopilot" // ModeChat keeps chat-driven motion alive between turns: it re-applies the // last chat target only after transport recovery, never after a user stop // or pause. ModeChat = "chat" )
Mode identifiers.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Announcement ¶
Announcement reports whether a line entered canonical chat and whether the scheduler must wait for browser playback before starting the next interval.
type Arrangement ¶
Arrangement is a bounded, inspectable sequence of segments. Planners and (later) LLM curation produce arrangements; deterministic code compiles them into engine retargets with explicit transition rules.
func NormalizeArrangement ¶
func NormalizeArrangement(arrangement Arrangement) (Arrangement, error)
NormalizeArrangement validates the bounded contract for a whole arrangement.
type DecideFunc ¶
type DecideFunc func(ctx context.Context, input DecisionInput) (Decision, error)
DecideFunc produces one bounded autonomous decision.
type Decision ¶
type Decision struct {
SpeechSource SpeechSource
Vibration *motion.VibrationSpec
// Tempo and AirSteps are the VacuGlide's own choices when tempo leads
// (ADR 0071). They ride a hold: the positions are left as they are.
Tempo *motion.TempoSpec
AirSteps int
Segment Segment
Pattern *motion.PatternDefinition
Say string
Hold bool
// Abstain holds without starting a replacement when no segment exists.
Abstain bool
// Requested marks a hold the human asked for in chat, so status can say why
// Autopilot is leaving the motion alone. It behaves exactly like Hold.
Requested bool
Next TimingPreference
// Variability is how much the target should wander before the next boundary.
Variability VariabilityPreference
// NextCheck is a hosted planner's own horizon under auto timing. Zero means
// the scheduler samples the Motion change rate window as before.
NextCheck time.Duration
}
Decision is one motion or speech curation outcome. Hold is scheduler-only: it must never produce an engine retarget.
type DecisionInput ¶
type DecisionInput struct {
Style string
SegmentIndex int
RecentPatternIDs []string
SpeedMinPercent int
SpeedMaxPercent int
LastSay string
CurrentPatternID motion.PatternID
CurrentSpeed int
CurrentAreaFocus *motion.AreaFocus
CurrentDynamic *motion.DynamicDefinition
CurrentFlow *motion.FlowSpec
MotionMinSeconds int
MotionMaxSeconds int
MotionChangeLevel int
// These session facts are backend-computed read-only input. Phrase age
// measures unchanged semantic shape/texture, excluding pace and the scheduler
// horizon; the decision counts let the model distinguish one sensible hold
// from accumulated sameness without requiring a change. None of these facts
// authorizes motion or feeds an automatic intensity score.
SessionSeconds int
SecondsAtCurrentSpeed int
SecondsAtCurrentPhrase int
DecisionsAtCurrentPhrase int
ConsecutiveHolds int
SpeedTrend string
// SessionTracking reports whether the session fields above are meaningful. When
// it is false the prompt omits them rather than sending zeros, because a model
// cannot act on a field it never saw.
SessionTracking bool
// ArcEnabled, ArcPercent and ArcMinutes describe the visible session buildup.
// Absent from the prompt entirely when disabled.
ArcEnabled bool
ArcPercent int
ArcMinutes int
// CurrentPerceptual is computed from the shared engine's compiled curve,
// after selected-device speed and safety fitting. It lets the model reason
// from felt commanded motion rather than treating any changed JSON field as
// proof of novelty.
CurrentPerceptual *motion.PerceptualSummary
// RecentPositionBands is bounded memory of hidden autonomous outcomes. Chat
// history cannot supply it because motion-only decisions are intentionally
// not published as dialogue.
RecentPositionBands []PositionBand
// RecentSpeeds is the same kind of memory for pace: the speed each recent
// stretch used and how long ago it began, oldest first. Without it every
// planning turn after "that's too much" looked like the moment it was said.
RecentSpeeds []SpeedStep
// MotionFeedback is populated only for one semantic quality retry after a
// model-elected update compiled as continuity.
MotionFeedback string
// RecentCheckSeconds lists the planner's recent auto-timing horizons, oldest
// first. They are observations, so a model can notice it keeps one length.
RecentCheckSeconds []int
// RecentScores are the distinct continuous scores played just before the
// current one, newest first, for motion planning only.
RecentScores []EarlierScore
// Lookahead is how long before its stretch ends a prepared decision is
// planned. The ages above are already projected to that boundary; callers
// that measure their own ages, such as chat history, add it to now.
Lookahead time.Duration
}
DecisionInput is bounded, semantic context for one autonomous decision.
type EarlierScore ¶
EarlierScore is a distinct continuous score that played earlier in the run.
type EdgeDecision ¶
type EdgeDecision struct {
HoldSeconds int `json:"hold_seconds"`
ResumeSpeed int `json:"resume_speed_percent"`
ResumeStyle string `json:"resume_style"`
}
EdgeDecision chooses a bounded duration and return, never raw device commands.
func (EdgeDecision) Validate ¶
func (d EdgeDecision) Validate(input EdgeInput) error
Validate rejects incomplete or unsafe model decisions.
type EdgeInput ¶
type EdgeInput struct {
TempoOnly bool `json:"tempo_only,omitempty"`
PreviousSpeed int `json:"previous_speed_percent"`
HoldingSpeed int `json:"holding_speed_percent"`
SpeedMin int `json:"speed_min_percent"`
SpeedMax int `json:"resume_speed_max_percent"`
RangeMin int `json:"holding_range_min_percent"`
RangeMax int `json:"holding_range_max_percent"`
}
EdgeInput describes the mechanical state after an immediate holding override. Only the normal mode loop may schedule its automatic return.
type EdgeStatus ¶
type EdgeStatus struct {
Active bool `json:"active"`
Phase string `json:"phase"`
Automatic bool `json:"automatic"`
ResumeAt string `json:"resume_at,omitempty"`
ResumeInSeconds int `json:"resume_in_seconds,omitempty"`
Message string `json:"message,omitempty"`
}
EdgeStatus is the backend-owned holding control snapshot.
type Engine ¶
type Engine interface {
Start(ctx context.Context, target motion.MotionTarget, settings config.MotionSettings) (motion.ActiveMotionState, error)
ApplyTarget(ctx context.Context, target motion.MotionTarget, reason string) (motion.ActiveMotionState, error)
Snapshot() motion.ActiveMotionState
}
Engine is the narrow motion-engine surface modes may use. Modes never see the transport; the engine owns every dispatch decision.
type FreestyleStatus ¶
type FreestyleStatus struct {
Feel string `json:"feel"`
Shape string `json:"shape"`
// ShapePhase names where the shape is: building, holding, rising,
// falling, peak, backing_off, teasing, easing or finished.
ShapePhase string `json:"shape_phase,omitempty"`
// ShapeProgressPercent runs through Slow build and Cooldown.
ShapeProgressPercent int `json:"shape_progress_percent,omitempty"`
// EnergyPercent is the shape's pace, 100 being the chosen pace.
EnergyPercent int `json:"energy_percent"`
Ending bool `json:"ending,omitempty"`
}
FreestyleStatus is the visible state of the running stream and its shape.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager owns at most one active mode loop.
func NewManager ¶
NewManager creates an idle mode manager.
func (*Manager) ActivateEdge ¶
ActivateEdge does no model work and never starts a stopped or paused device. The plan-ID guard and engine Stop generation protect the physical handoff.
func (*Manager) ApplyMotionReview ¶
func (m *Manager) ApplyMotionReview(ctx context.Context, ticket ReviewTicket, target motion.MotionTarget, apply func(context.Context) (motion.ActiveMotionState, error), ) error
ApplyMotionReview invalidates older mode work, then adopts the corrected semantic target for both keepalive and Autopilot. The caller still owns the atomic engine plan-ID check. There is no additional motion loop.
func (*Manager) BeginUserPause ¶
BeginUserPause blocks autonomous recovery before Engine.Pause performs its transport Stop. During that round-trip the engine is intentionally neither running nor fully marked paused; relying on Snapshot alone lets a mode start a replacement stream in that gap. The completion callback keeps the latch when the engine reached a paused state and rolls it back after an ordinary pause failure. The admission result is false when a newer Pause, Resume, or Stop superseded this request while it waited for another control operation.
func (*Manager) BeginUserResume ¶
BeginUserResume returns a completion callback that releases the mode-level latch only when the engine successfully resumes and no newer Pause intent is pending. The next scheduler tick then continues the preserved phrase and clocks instead of creating a replacement start. A false admission result means the engine call must be skipped because a newer control intent won.
func (*Manager) BeginUserStop ¶
func (m *Manager) BeginUserStop() func()
BeginUserStop marks autonomous work unable to restart and cancels its loop without waiting. The caller can stop the motion engine first, then invoke the returned function to drain and trace the mode goroutine.
func (*Manager) CancelChatTarget ¶
CancelChatTarget releases a failed interactive handoff so the active mode can resume planning on its next tick.
func (*Manager) EarlierScores ¶
func (m *Manager) EarlierScores() []EarlierScore
EarlierScores reports the run's earlier distinct continuous scores, newest first, for a live chat turn. Planning receives only the recent subset as observations, without recall IDs or old requests to repeat.
func (*Manager) MotionReviewTicket ¶
func (m *Manager) MotionReviewTicket() (ReviewTicket, bool)
MotionReviewTicket captures admission after a local choice has been applied.
func (*Manager) NotifyAutopilotSettingsChanged ¶
func (m *Manager) NotifyAutopilotSettingsChanged()
NotifyAutopilotSettingsChanged applies saved cadence preferences to the live session without retargeting current motion.
func (*Manager) NotifyChatActivity ¶
NotifyChatActivity invalidates stale autonomous planning and postpones the independent speech clock even when the interactive turn does not change motion.
func (*Manager) NotifyChatActivityComplete ¶
NotifyChatActivityComplete releases autonomous planning after the canonical owning interactive turn has finished. An invalidated turn may unwind after its replacement has started, so completion must carry its activity ID.
func (*Manager) NotifyChatStop ¶
func (m *Manager) NotifyChatStop()
NotifyChatStop clears the keepalive target after a chat-driven stop.
func (*Manager) NotifyChatTarget ¶
func (m *Manager) NotifyChatTarget(generation uint64, target motion.MotionTarget) bool
NotifyChatTarget adopts a successfully applied chat target for keepalive and as Autopilot's authoritative current segment.
func (*Manager) NotifySpeechPlaybackComplete ¶
NotifySpeechPlaybackComplete starts the next speech interval after audible playback, not after inference or enqueue completion.
func (*Manager) NotifyUserStop ¶
func (m *Manager) NotifyUserStop()
NotifyUserStop records an explicit user stop: the active mode ends and no keepalive may restart motion afterwards.
func (*Manager) PrepareChatTarget ¶
PrepareChatTarget blocks new mode work and invalidates any in-flight decision before an interactive target enters the shared engine.
func (*Manager) ReconsiderAfterChat ¶
func (m *Manager) ReconsiderAfterChat()
ReconsiderAfterChat brings Autopilot's next planning boundary forward to now after a live chat turn that left the motion unchanged. The planner reads the human's latest words, and without this a remark such as "that's too much" waited for the rest of the current segment, up to the cadence maximum. Chat that changes the motion re-arms its own segment instead. The planner still runs only after the chat activity completes.
func (*Manager) ResetSessionArc ¶
ResetSessionArc returns buildup to empty. A visible progression the user cannot restart is not really under user control.
It reports false when there is no Autopilot session to place buildup in. Start clears buildup for a fresh run, so accepting a placement beforehand would store a value that is silently discarded a moment later — a call that appears to work and does nothing is worse than one that says no.
func (*Manager) ResumeEdge ¶
ResumeEdge returns to the saved motion without starting a stopped device.
func (*Manager) SessionArcSnapshot ¶
func (m *Manager) SessionArcSnapshot() SessionArc
SessionArcSnapshot reports buildup for the UI.
func (*Manager) SetSessionArcPercent ¶
SetSessionArcPercent lets the user place the bar directly.
type Options ¶
type Options struct {
// Ensure returns a startable engine for the selected dispatch owner.
Ensure func(ctx context.Context) (Engine, error)
// Current returns the live engine or nil when none exists yet.
Current func() Engine
// Settings returns the current motion settings snapshot.
Settings func() config.MotionSettings
// FreestyleSettings returns Freestyle's durable preferences; nil uses
// the defaults.
FreestyleSettings func() config.FreestyleSettings
// AutopilotSettings returns durable cadence and speech-authority settings.
AutopilotSettings func() config.AutopilotSettings
// MotionGenerationMode keeps Autopilot fallback inside the selected model
// vocabulary. Dynamic mode never falls through to the pattern planner.
MotionGenerationMode func() string
// TempoLeads keeps native tempo failures out of the positional fallback.
TempoLeads func() bool
Traces *diagnostics.TraceRing
Now func() time.Time
Tick time.Duration
Seed int64
// PrepareNextDecision reports whether Autopilot plans each motion decision
// as its stretch begins rather than just before the boundary. The server
// enables it only for external planners.
PrepareNextDecision func() bool
// MaxSegmentDuration caps armed segment deadlines. It exists for tests
// that need many segment boundaries quickly; production leaves it zero.
MaxSegmentDuration time.Duration
// Decide is Autopilot's injected LLM curation step. Autopilot cannot
// start without it; Freestyle and chat keepalive never use it.
Decide DecideFunc
// DecideEdge plans only the duration and return after an immediate hold.
DecideEdge func(context.Context, EdgeInput) (EdgeDecision, error)
// DecideSpeech runs the independent autonomous speech contract.
DecideSpeech DecideFunc
// CanAnnounce is false while autonomous speech would deepen a TTS backlog.
CanAnnounce func() bool
// Announce publishes an Autopilot line and optionally queues browser audio.
Announce func(ctx context.Context, say string, source SpeechSource) Announcement
// ObserveChoice is a nonblocking observer of accepted local model choices.
// It must not do network work on the mode loop.
ObserveChoice func(DecisionInput, motion.ActiveMotionState)
ReviewEnabled func() bool
}
Options wires the manager to the app runtime.
type Planner ¶
type Planner struct {
// contains filtered or unexported fields
}
Planner deterministically builds pattern segments for Autopilot's fallback when a model decision fails. Freestyle no longer uses it; it plays the generated stroke stream in freestyle_stream.go. Given the same seed, style, and settings, the segment sequence is reproducible; the seed and all candidate scores are recorded in planner trace rows.
func NewPlanner ¶
NewPlanner seeds the segment planner; a zero seed uses the clock and the effective seed stays visible in every decision row.
func (*Planner) NextSegment ¶
func (p *Planner) NextSegment(settings config.MotionSettings) (Segment, []diagnostics.PlannerScore)
NextSegment scores every pattern for the saved style and returns the next bounded segment plus the full score table for the trace row.
func (*Planner) SegmentIndex ¶
SegmentIndex reports how many segments the planner has produced.
type PositionBand ¶
PositionBand describes the compiled position envelope of one recent target. It is an observation for the model, never a target or transport payload.
type ReviewTicket ¶
type ReviewTicket struct {
// contains filtered or unexported fields
}
ReviewTicket identifies the mode intent that accepted a local choice. It does not reserve the mode: ordinary planning continues during the review.
type Segment ¶
type Segment struct {
// Tempo is a native tempo-only segment, never a position fallback.
Tempo *motion.TempoSpec `json:"tempo,omitempty"`
PatternID motion.PatternID `json:"pattern_id"`
Dynamic *motion.DynamicDefinition `json:"dynamic,omitempty"`
Flow *motion.FlowSpec `json:"flow,omitempty"`
SpeedPercent int `json:"speed_percent"`
DriftToSpeedPercent int `json:"drift_to_speed_percent,omitempty"`
AreaFocus *motion.AreaFocus `json:"area_focus,omitempty"`
DurationMillis int64 `json:"duration_ms"`
}
Segment is one bounded step of a motion arrangement: a named pattern at a semantic speed, optionally focused and optionally drifting to a second speed mid-segment. A segment always runs long enough to establish a feel.
func NormalizeSegment ¶
NormalizeSegment clamps one segment into the bounded contract.
func (Segment) DriftTarget ¶
DriftTarget is the optional mid-segment same-pattern speed nudge; phase is preserved because the pattern does not change.
type SessionArc ¶
type SessionArc struct {
Enabled bool `json:"enabled"`
Percent int `json:"percent"`
Minutes int `json:"minutes"`
}
SessionArc is the UI-facing buildup snapshot. Its name preserves the API schema.
type SpeechSource ¶
SpeechSource is captured when a check-in is generated. Changing role routing before publication must not relabel an already generated line.
type SpeedStep ¶
SpeedStep is one recent stretch's speed and how long ago it began. Interactive marks a speed the person set through chat; it carries no words.
type Status ¶
type Status struct {
EdgeHold *EdgeStatus `json:"edge_hold,omitempty"`
Active bool `json:"active"`
Mode string `json:"mode,omitempty"`
Style string `json:"style,omitempty"`
// StatusAt and the absolute deadlines let a client render a smooth clock
// between backend snapshots without inventing its own schedule. The legacy
// remaining fields stay as a compatibility and clock-skew fallback.
StatusAt string `json:"status_at,omitempty"`
SegmentIndex int `json:"segment_index,omitempty"`
SegmentEndsMs int64 `json:"segment_ends_in_ms,omitempty"`
SegmentDueAt string `json:"segment_due_at,omitempty"`
LastEvent string `json:"last_event,omitempty"`
LastEventAt string `json:"last_event_at,omitempty"`
WaitingForChat bool `json:"waiting_for_chat,omitempty"`
// DecisionSource reports where Autopilot's current segment came from:
// "model", "fallback" (planner after a failed decision), "hold",
// "requested_hold" while the human asked chat to keep the motion as it is,
// or "interactive" when chat supplied the live target.
DecisionSource string `json:"decision_source,omitempty"`
// PlanningFailures counts consecutive failed motion decisions in this run.
// Deliberate holds and successful plans reset it; speech does not affect it.
PlanningFailures int `json:"planning_failures,omitempty"`
// LastSay is the most recent Autopilot line. The planner uses it to avoid
// repetition; the API retains it as diagnostic state while Chat owns display.
LastSay string `json:"last_say,omitempty"`
// MotionChangeMs and SpeechMs are independent backend-owned clocks.
MotionChangeMs int64 `json:"motion_change_in_ms,omitempty"`
MotionChangeDueAt string `json:"motion_change_due_at,omitempty"`
SpeechMs int64 `json:"speech_in_ms,omitempty"`
SpeechDueAt string `json:"speech_due_at,omitempty"`
MotionPlanned bool `json:"motion_planned,omitempty"`
SpeechWaitingPlayback bool `json:"speech_waiting_playback,omitempty"`
// Arc is the visible session progression bar. Absent when the user has the
// switch off, so the UI shows nothing rather than an empty bar.
Arc *SessionArc `json:"session_arc,omitempty"`
// Freestyle is the running stream's feel and visible session shape.
Freestyle *FreestyleStatus `json:"freestyle,omitempty"`
}
Status is the UI-facing mode state.
type TimingPreference ¶
type TimingPreference string
TimingPreference is a model-selected semantic timing category. The manager samples the concrete delay inside the user's saved bounds.
const ( // TimingSoon samples the early part of the configured cadence window. TimingSoon TimingPreference = "soon" // TimingNormal samples the middle of the configured cadence window. TimingNormal TimingPreference = "normal" // TimingLater samples the late part of the configured cadence window. TimingLater TimingPreference = "later" )
type VariabilityPreference ¶
type VariabilityPreference string
VariabilityPreference is a model-selected category for how much the motion should wander *inside* the current target, as distinct from how often the target is reconsidered. The two are independent: a persona can hold one pattern for a long stretch while still breathing within it, or change target often while each stretch stays flat.
Like TimingPreference it is a category rather than a number, because a local model emits a category reliably and the backend samples the concrete values — so a model that always answers "normal" still produces varied motion.
const ( // VariabilitySettled holds the target flat until the next boundary. VariabilitySettled VariabilityPreference = "settled" // VariabilityNormal takes about half the earned waypoint allowance. VariabilityNormal VariabilityPreference = "normal" // VariabilityRestless takes the full allowance at a wider amplitude. VariabilityRestless VariabilityPreference = "restless" )
Source Files
¶
- arrangement.go
- autopilot.go
- autopilot_arc.go
- autopilot_health.go
- autopilot_scheduler.go
- autopilot_sway.go
- edge.go
- freestyle_shapes.go
- freestyle_stream.go
- layered.go
- manager.go
- manager_chat.go
- manager_controls.go
- manager_start.go
- manager_state.go
- manager_status.go
- motion_review.go
- schedule_state.go
- segment_planner.go
- vibration.go