# Trajectory Grounding

## Purpose

Trajectory Grounding gives a running agent a compact, evidence-bound account of
where a project stands, what changed, what remains uncertain, and the safest
next action. Before the first main-agent request, Omnius asks the selected model
to form a specific, structured orientation from that evidence. This is a
control-plane checkpoint, not free-form self-talk and not a request to reveal
private reasoning.

The feature exists to prevent loops where changing a payload appears to be
progress even though the underlying prerequisite has not changed. The
myactuator repeated full-file write incident is the reference failure mode:
an existing target rejected unguarded `file_write` calls while generic recovery
guidance kept steering toward another full write.

## Invariants

- Every completed, failed, file-state, or verifier claim must point to a
  sanitized evidence reference: a tool result, file hash, verifier outcome, or
  child-agent result.
- Unknown or stale state is rendered as an open question, never as completed
  work.
- One current checkpoint is regenerated into the active context frame. It must
  not accumulate as independent system messages.
- The first active frame always attempts a tool-less model grounding pass. Its
  concise situation assessment must cite supplied evidence labels and be visible
  in the live trajectory box; if inference is unavailable, the UI labels the
  deterministic safety orientation rather than pretending it was generative.
- Focus-supervisor and explicit safety contracts override generic trajectory
  suggestions.
- The model must use the checkpoint to choose a next tool action, but must not
  echo it or generate a reasoning transcript for the user.
- Child agents receive only a scoped slice: parent goal, delegated scope,
  relevant constraint, and exit evidence requirement.

## Data contract

```ts
type TrajectoryAssessment =
  | "on_trajectory"
  | "recovery_required"
  | "verification_due"
  | "blocked";

interface TrajectoryCheckpoint {
  schemaVersion: 1;
  id: string;
  revision: number;
  turn: number;
  trigger: string;
  assessment: TrajectoryAssessment;
  goal: string;
  currentStep?: string;
  situationAssessment?: string;
  groundingSource?: "model" | "deterministic";
  groundingEvidenceRefs?: string[];
  completedWork: string[];
  groundedFacts: Array<{
    statement: string;
    evidence: string;
    freshness: "fresh" | "stale" | "unknown";
  }>;
  openQuestions: string[];
  nextAction: string;
  successEvidence: string;
  doNotRepeat: string[];
}
```

The model-facing rendering is capped and follows this form:

```text
[TRAJECTORY CHECKPOINT]
Goal: ...
Assessment: recovery_required
Reasoned situation: the full-file write was rejected and there is no fresh read
of the target, so a changed payload would not resolve the actual prerequisite.
Grounded facts:
- [turn 18/tool_result] file_write on pal.cpp was blocked: existing target
  lacks fresh overwrite/hash evidence.
Open question: current pal.cpp bytes have not been freshly read.
Required next action: file_read pal.cpp, then use file_edit/file_patch.
Success evidence: a targeted mutation or explicit blocker evidence.
Do not repeat: file_write pal.cpp with a changed full-file payload.
```

## Integration path

1. `packages/orchestrator/src/trajectory-checkpoint.ts` owns pure types,
   deterministic safety assessment, model-output validation/merging, rendering,
   fingerprints, and scoped child slices.
2. `AgenticRunner` records bounded sanitized observations for both executed
   tools and synthetic/preflight blocks. It runs the bounded tool-less
   grounding request before the first main frame, then rebuilds checkpoints in
   `_buildTurnContextFrame()`, which serves normal and brute-force loops.
3. `ContextFabric` receives a first-class `trajectory_checkpoint` signal with
   high priority, one-turn TTL, and a single semantic conflict group.
4. `context-compiler` recognizes the block for last-surface deduplication.
5. Tier prompts tell the model to reconcile its next tool call against the
   checkpoint without narrating it.
6. The runner emits a typed trajectory event. TUI, API events, debug artifacts,
   session handoffs, and child prompts consume bounded projections of it.
7. Large whole-file reads hand their isolated extraction branch an agentic
   request built from the current trajectory, active read action, and trigger
   evidence. The branch receives the specific unresolved question and return
   contract, never a raw copy of the original user prompt as its query.

## Trigger policy

The checkpoint is recomputed before each model request, but only emits a new
revision when content or direction changes. The model grounding pass runs at
task start and, in adaptive mode, after material failures, safety-direction
changes, compaction, or user steering; ordinary successful reads do not create
an extra planning call. Important triggers are task start, tool failure,
synthetic safety block, mutation, verifier result, child result, compaction,
user steering, focus-directive change, and adaptive cadence.

Use total tool-call count for cadence rather than a loop-local turn number so
brute-force re-engagement cannot reset the schedule.

## Exposure

- **Model context:** a first-class active-frame signal placed after goal/user
  steering and before generic guidance.
- **TUI:** a compact, collapsible main-view dynamic block and a direction detail
  in the live stage/footer; show updates only when the revision changes.
- **Sub-agents:** a scoped, non-authoritative parent slice in their prompt.
- **API/debug:** typed event plus debug artifact on direction change.
- **Handoff/session diary:** persist the latest meaningful checkpoint only at
  compaction, direction changes, handoff, or completion. Restored checkpoints
  are orientation, not fresh file evidence.

## Safety and rollout

`OMNIUS_TRAJECTORY_CHECKPOINT=off|shadow|adaptive|always` controls checkpoint
visibility and cadence. `OMNIUS_TRAJECTORY_GROUNDING=off|initial|adaptive`
controls model orientation: `initial` always grounds the first main-agent
request; `adaptive` also regrounds material direction changes. The main TUI
uses `adaptive`; child agents receive the parent slice rather than recursively
running a second grounding pass.
`shadow` computes and records checkpoints without model injection. `adaptive`
is the default target: inject on meaningful state changes and bounded cadence.

No mandatory `trajectory_update` tool is introduced. A tool would create
ceremony and failure loops for smaller models. Existing todo/workboard state is
updated only when the trajectory materially changes.

## Acceptance criteria

- Changed-payload full-write retries produce `recovery_required`, a fresh read
  prerequisite, and a no-repeat constraint.
- Cached/replayed reads do not satisfy a fresh-read prerequisite.
- Child completion yields verification work, not an unsupported completion
  claim.
- Context contains at most one current checkpoint and compaction retains its
  current evidence references.
- TUI/API/debug views all agree on checkpoint revision and assessment.
- The feature is bounded, sanitized, and disabled cleanly by configuration.
