rulvar API reference / @rulvar/plan
@rulvar/plan
Classes
| Class | Description |
|---|---|
| PinLedger | The worktree pin ledger: a pure fold counting live pins from abandon entries carrying retainWorktree: true (park pinning and DEF-5 retention share the cap by construction). |
| PlanWriteLock | PlanWriteLock (M7-T01): the in-process FIFO mutex serializing live appends to the sequential scope "plan". |
| RevisionGuards | The guard state machine. All counting inputs arrive from pure folds (the caller feeds landed revisions, severs, and re-adds in journal order), so live and replay converge on identical verdicts; the caller journals each verdict BEFORE applying its effects. |
Interfaces
| Interface | Description |
|---|---|
| CassetteTurn | A minimal scripted adapter over the PUBLIC provider SPI. |
| EscalationDebitRow | One per-lineage debit row of a class-level decision. |
| EscalationDecisionValue | The authoritative escalation-decision entry value (the producer contract of LineageIndex and foldTermination). Exactly one such entry per report; the debit is atomic with the append and the balance-after is embedded (DEF-2). A decision whose counting debit was DENIED carries countsAgainstLimit: false plus capExceeded: true: the termination.denied entry written strictly before is the counting record, and the folds stay replay-strict. |
| GateVerdictValue | One journaled acceptance-gate evaluation. |
| GuardsState | - |
| GuardVerdictValue | The journaled guard verdict payload (kind 'decision'). |
| KbProposeInput | The model-facing kb_propose payload (tier-relative subject). |
| LadderVerdictValue | The ladder verdict decision entry: the producer contract both folds already consume. A RAISING verdict debits one rung unit (rungIndexAfter/rungsRemainingAfter embedded, checked by foldTermination) and carries the rung RESPAWN's embedded admission (spawn debit) plus nextAttempt (the lineage registration: relation 'rung-retry'). A non-raising verdict records the ladder's end (exhausted rungs, top rung, or a denied respawn) and authorizes nothing. |
| LedgerExport | The draft-versioned outward seam; the final shape stays an open question. |
| LedgerFact | - |
| LedgerLesson | - |
| LedgerObservation | - |
| LedgerRevisionRow | One auto-derived revision history row (fold join, never authored). |
| LedgerView | The pure ledger fold. |
| M7CassetteFixture | One normalized-cassette fixture file (cassettes/<id>.json). |
| ParkDisposition | The park disposition computed at landing time. |
| PlanDecisionValue | The value payload of a plan.decision entry. |
| PlanFoldState | The plan fold state: the working state plus fold-side records that deliberately stay OUT of planHash. badBaseStreak reconciles two normative clauses: a bad_base revision leaves the hashed state byte-identical (planHashAfter == planHashBefore) yet still lengthens the guard streak: the guards therefore consume effectiveDroppedStreak, the hashed counter plus the trailing bad_base entries. doneRefs remembers which entry resolved each done node so waive_dep drops can point blockingRef at it. |
| PlanNode | Canonical per-node fields entering planHash, exactly this record. deps are sorted in the hash (not necessarily in state); checkpointRef/escalationRef participate as absent when absent. |
| PlanReviseRequest | - |
| PlanReviseResult | The canonical result form (XF-11): DEF-8 shape plus the DEF-2 balance. |
| PlanRevisionAdmission | One embedded admission beside its op (DEF-2/DEF-3 folds read it). |
| PlanRevisionValue | The value payload of a plan.revision entry (XF-11). |
| PlanRunnerOptions | Configuration knobs of the PlanRunner extension. |
| PlanSnapshotRef | - |
| PlanToolRuntime | The engine seam the plan tools close over. |
| PlanViewNode | One rendered node of the pinned plan_view fold. |
| PlanViewRender | The plan_view render: plan state, lineage, termination, reuse. |
| PlanWorking | The working state the applier threads: the hashed TaskPlan plus the resolved spec table. Specs stay OUT of planHash by construction (the hashed projection is promptSpecHash per node) but are themselves a pure fold of add_task specs, amend patches, and decomposition specs, so live and replay converge byte-identically. |
| QueueFailoverDeps | queue-failover-during-forced-finish (the DEF-7 final cassette; M8-T03): worker A loses its lease strictly between the cap decision and the final wake; worker B reclaims with a bumped fencing epoch and rolls the forced finish forward. The stale writer's appends are rejected and invisible, exactly one cap decision exists, and finalization is paid once. |
| RebaseContext | - |
| RebaseEvaluation | - |
| ReuseTransform | The reuse-by-reference transform hook (DEF-5; M7-T07). |
| RevisionGuardsOptions | RevisionGuards configuration. |
| TaskPlan | TaskPlan: typed data owned by the engine, never prose in a transcript. The guard fold counters ride the same record because they enter planHash: revisionCount counts journaled plan.revision entries; droppedRevisionStreak counts consecutive fully-dropped revisions (RevisionGuards). |
| TaskSpec | - |
| UnparkPlacement | The unpark placement: continuation or restart. |
Type Aliases
| Type Alias | Description |
|---|---|
| AppliedPlanOp | Applied forms the fold consumes. cancel_task gains the engine-computed cascade (computed at apply time, never a parameter); park/cancel against running nodes apply as flag requests landing later via plan.decision (park-landed, cancel-landed). |
| EnginePlanOp | The closed EnginePlanOp set. |
| GuardFallback | - |
| LedgerOp | The CLOSED authored op vocabulary. |
| PlanDecisionOrigin | Engine authorship origins of plan.decision entries. |
| PlanNodeStatus | The closed status machine; skipped is fold-derived for entries but first-class for plan nodes. |
| PlanOp | The orchestrator-facing PlanOp union. |
| PlanReviseErrorCode | - |
| RebaseOutcome | - |
| RebaseReasonCode | The complete machine reason vocabulary, normative and closed. |
| TaskSpecPatch | The amend_task patch form: every field optional. |
Variables
| Variable | Description |
|---|---|
| BUDGET | - |
| DEFAULT_DROPPED_REVISION_LIMIT | - |
| DEFAULT_MAX_OSCILLATIONS_PER_KEY | Appendix A: osc_guard reject threshold per key (shared default). |
| DEFAULT_MAX_PINNED_WORKTREES | Appendix A: the single pin cap shared by park/unpark and retainWorktree. |
| DEFAULT_STALL_REPLAN_CAP | The hard per-run stall replan bound. |
| EMPTY_PLAN_HASH | - |
| JUDGE_VERDICT_SCHEMA | The forced verdict schema of the judge gate. |
| KB_PROPOSE_SCHEMA | The normative kb_propose schema (phase 3). The subject is tier-relative: the orchestrator never sees model names, so the handler resolves the rung index against the declared ladder of the referenced lineage into the concrete KbProposal subject. |
| KB_PROPOSE_TOOL_NAME | - |
| LEDGER_APPEND_SCHEMA | The closed authored op vocabulary as JSON Schema. |
| LEDGER_APPEND_TOOL_NAME | - |
| LEDGER_READ_SCHEMA | ledger_read takes no parameters and pins to the turn snapshot. |
| LEDGER_READ_TOOL_NAME | - |
| LEDGER_RENDER_BUDGET_CHARS | The committed ledger_read render budget (Appendix A: 65536 chars over the serialized view, the character measure; OQ-04 closed at M10 entry). The section caps stay the primary bound; under the default termination limits this belt never engages. |
| LEDGER_SECTION_CAPS | Appendix A per-section caps. |
| PLAN_HASH_VERSION | The hashVersion whose profile computes planHash today. |
| PLAN_REVISE_SCHEMA | The plan_revise parameter schema (normative). |
| PLAN_REVISE_TOOL_NAME | - |
| PLAN_SCOPE | The single sequential scope holding every plan-mutating entry, inside the orchestrator's run scope: total order = ordinal order = durable append order. Child node scopes are plan/NodeId (core planNodeScope). |
| PLAN_VIEW_SCHEMA | plan_view takes no parameters. |
| PLAN_VIEW_TOOL_NAME | - |
Functions
| Function | Description |
|---|---|
| agentTypeOfRequest | - |
| applyAppliedOp | Applies ONE applied op to the working state. The applier consumes recorded outcomes; op-level legality was decided at rebase time and is never re-evaluated here. Exported for the rebase engine, which applies each op of a revision against the state already changed by the earlier applied ops of the same revision. |
| applyDecisionOps | The shared plan.decision applier core: engine authorship happens at the fold head under PlanWriteLock, so the producer can PREVIEW the resulting state (and its planHashAfter) before appending, and the fold re-applies the recorded ops identically on replay. |
| applyPlanEntry | THE single applier: folds one plan-scope entry into the state. Replay consumes recorded outcomes (the APPLIED diff), never re-runs rebase, and timers do not run; hash verification runs under the entry's own hashVersion profile. |
| applyTaskSpecPatch | Applies an amend_task patch onto a spec (undefined fields untouched). |
| assertPlanHead | The append-time head assertion: planHashBefore of the entry being appended MUST equal the current fold head. A failure is an engine bug and raises the typed PlanInvariantError; the run finishes with outcome error, never a silent brick. |
| assertPlanTransition | Asserts one status transition against the closed machine. Op-level legality (which ops may request which transitions in which state) is the rebase conflict table's job (M7-T04); the machine itself enforces exactly the structural rules: |
| boundLedgerRender | Deterministic render bound: over budget, rows drop oldest-first, auto-derived joins before authored sections, and the mission brief slices last; every drop is a FLAGGED discrepancy line. A pure function of (view, budget): a re-executed wake turn renders byte-identical bounded bytes from the same pinned fold. |
| buildPlanTools | Builds the PlanRunner tools (appended to the mode (c) toolset). |
| canonicalLadderOf | Canonicalizes the profile's declared ladder once per dispatch site. |
| canonicalPlanState | The canonical JSON projection of PlanState: nodes sorted by NodeId plus the guard fold counters, nothing else. |
| cassetteAdapter | - |
| chainEffortOf | The profile's chain effort feeding canonicalization, when declared. |
| clampStartTier | Clamps the orchestrator's model_hint.startTier to the declared ladder: the hint is the ONLY model influence the orchestrator has, and it never names a model. |
| decisionOriginOf | The plan.decision origin of one resolvedBy value. |
| depsSatisfied | Dependency satisfaction, derived purely in the fold and NEVER a record: a dep is satisfied when waived or when its upstream node is done. Terminally unsuccessful upstreams (cancelled, failed) keep blocking: such edges "remain blocking" per the rewire_deps row of the conflict table, and waive_dep exists exactly to unblock them. |
| effectiveDroppedStreak | The streak RevisionGuards consume. |
| emptyPlan | The empty plan every fold starts from. |
| emptyPlanFold | - |
| engineWith | - |
| escalationDecisionKey | Content key: one authoritative decision per report (decide-once). |
| executingRungOf | The rung an attempt executes on: the clamped start tier plus the journaled raise count, hard-clamped at the top rung. rungIndex per lineage is strictly monotone; there are no demotions. |
| exportLedger | - |
| foldLedger | Fold every ledger.op plus the auto-derived joins up to uptoSeq. |
| gateVerdictKey | Content key of one gate verdict: attempt plus gate position. |
| isTerminalPlanStatus | - |
| judgePrompt | The judge prompt: artifact-grounded, assembled from journaled values only (the attempt's output summary and artifact index), so a replayed judge dispatch hashes identically. |
| ladderOfProfile | Extracts the declared ladder from an agent profile: the ModelSpec union carries it (model: { ladder }), or the loop-role routing entry. The same declaration points feed ladderLengthOf and the frozen kMax, so admission and execution can never disagree on the ladder length. |
| ladderTriggerOf | Classifies a settled attempt into the typed transition trigger: schema-mismatch errors are 'schema-exhausted'; the engine's no-progress abort is first-class 'no-progress' (it rides status 'limit' with the dedicated abort class, distinct from user cancellation by construction); cancelled, escalated, and skipped never trigger. 'verify-failed' comes from the acceptance gates, never from the terminal status. |
| ladderVerdictKey | Content key of one ladder verdict: the judged attempt is unique. |
| ledgerCapViolation | Section-cap check for one authored op (Appendix A). |
| ledgerOpKey | The content key of one authored op (ordinal distinguishes repeats). |
| ledgerSufficiency | Compaction sufficiency: the orchestrate role may compact aggressively only when the ledger measurably suffices (at least one authored revision recorded and a minimum fact count); otherwise the engine falls back to conservative summarize. |
| normalizeAdaptiveJournal | Normalizes one journal for cassette comparison: ULIDs and sha256 strings map to first-appearance placeholders; wall clock, spans, and transcript refs collapse to fixtures. Deterministic given a deterministic entry stream. |
| orchestratePlanned | The PlanRunner entry surface: mode (c) plus the extension in one call. |
| parkDispositionOf | - |
| planDecisionKey | - |
| planHash | planHash under one deriver profile (default: the current hashVersion 2 profile). Replay recomputes each entry's planHashAfter with the predicate of that entry's OWN hashVersion, so the deriver is a parameter, not an ambient. |
| planRevisionKey | Content keys: plan.revision keys over {kind, base, requestedOps}; plan.decision over {kind, origin, ops, causeRef}. Cosmetics (rationale) never enter a key; ordinal within scope "plan" distinguishes repeats, so forward-matching works without kernel changes. |
| planRunner | Builds the PlanRunner orchestrator extension. Attach via orchestrate(engine, goal, { extension: planRunner(o) }) or the orchestratePlanned convenience surface. |
| promptSpecHashOf | The deterministic spec digest entering PlanNode.promptSpecHash: the canonical JSON of the full TaskSpec through the frozen hashVersion 2 canonicalization. A plan-internal digest, not a kernel content key: the paid-call identity stays with the child's own spawn entry. |
| readPlanDecision | Reads a plan.decision entry's payload. |
| readPlanRevision | Reads a plan.revision entry's payload (tolerant of foreign journals). |
| rebasePlanRevision | Steps 2-4 of the committed algorithm: base validation, sequential per-op conflict resolution against the mutating head, and the post-revision counter update. Pure: the caller owns the lock, the append, and every effect. |
| recomputePlanReadiness | Recomputes the derived pending/ready boundary after a fold step: every schedulable node (currently pending or ready) becomes ready when its deps are satisfied and pending otherwise. rewire_deps may regress a ready node to pending; upstream done transitions and waives promote pending to ready. All other statuses are untouched. Returns the same plan object when nothing changed, so fold steps stay cheap. |
| resolvedByOf | Maps a resolution by value onto the decision's resolvedBy field. |
| runAmendVsRunningThenCancelAdd | amend-vs-running-then-cancel-add (DEF-8): amend_task on a running node drops node_running; the next revision cancels it and adds the amended prompt as a NEW node continuing the SAME logical task; the abandon covers the old branch and replay repays neither. |
| runBadBaseStreakTerminates | bad-base-streak-terminates (DEF-8): three consecutive revisions with a fabricated base.planHash land as all-dropped bad-base entries; the dropped streak reaches its limit and the non-HITL RevisionGuards fallback (finish-with-partial) closes the run. |
| runBudgetDeniedRung | budget-denied-rung: the budget guard denies the rung respawn; the denial journals as termination.denied strictly before the verdict and the ladder takes its declared fallback path. |
| runCapFreezeThenFinish | cap-freeze-then-finish (DEF-7): the soft boundary crossed with live children; the cap decision precedes its effects; admitted nodes run to completion; the final quiescence wake gets the finish-only toolset; outcome ok with forcedFinish. |
| runClaimExclusivityAndChain | claim-exclusivity-and-chain (DEF-5): one revision adds TWO identical tasks; the first grafts (exclusive claim), the second admits fresh; the grafted node is severed and the key added a third time: the link points at the chain head and the drain is transitive, oldest first; oscillationCount for the key reaches 2. |
| runClassStormSingleTurn | class-storm-single-turn (DEF-2): five dependency-chained workers each escalate (Flavor A); the orchestrator resolves all five in ONE revision; the class-level decision carries five per-lineage debits in one entry. Store-independence (identical fold on JSONL and SQLite) is asserted by the replay suite over the frozen bytes. |
| runCombinedLoopDescent | combined-loop-descent (DEF-2): a verify-failed gate raises the ladder rung; the raised rung hits its turn limit at the top (trigger 'limit') and the node fails; the failure wakes a replan that decomposes the work into two depth-1 children; one child completes and the other escalates until its escalationUnits deny; Phi strictly decreases on every debiting entry and matches the embedded balances. |
| runConfigDriftResume | config-drift-resume (DEF-2): life 1 runs under maxRevisionsPerRun 2 and crashes at the pre-append kill point of its second revision; life 2 resumes with the knob DOUBLED. Balances continue from the journaled termination.init (the live config is ignored), a termination:config-drift event fires, and nothing is repaid. |
| runCrashAfterAppendBeforeEffects | crash-after-append-before-effects (DEF-8): the kill lands immediately after the durable plan.revision carrying add_task x2 plus cancel_task on a running node; the resume re-issues the effects: both children spawn live exactly once and the cancel lands. |
| runCrashBetweenCapAndEffects | crash-between-cap-and-effects (DEF-7): process death right after the cap decision entry, before any of its effects; resume re-derives the frozen state from the entry and rolls the forced finish forward. |
| runCrashBetweenLinkAndRoot | crash-between-link-and-root (DEF-5): the full-reuse scenario is cut strictly AFTER the durable node.link and BEFORE the by-ref root; the resume rolls forward: the link forward-matches, the root is re-issued, and nothing is paid twice. |
| runCrashDuringRevision | crash-during-revision: process death INSIDE the revision window, at the pre-append kill point: life 1 is truncated strictly BEFORE the second plan.revision entry; life 2 re-issues the revision live and rolls its effects forward. |
| runDecomposeMintsChildren | decompose-mints-children (DEF-3): an escalation decomposition mints FRESH logical tasks inside the decision entry; the spawn debits ride the same entry. |
| runEscalationStormFrozen | escalation-storm-frozen (DEF-7 set): three Flavor B escalations while the plan is frozen at the cap; each resolves through its journaled defaultDecision and the lineage counters hold. The branches CHAIN via dependencies so exactly one deadline timer is live at a time: the journal byte order stays deterministic (DEF-4 already guarantees the fold; the cassette asserts bytes). |
| runFinalizeFallbackSynthesized | finalize-fallback-synthesized (DEF-7): the final finish fails inside its turn limit; the engine journals orchestrator_finalize_fallback and synthesizes the deterministic partial by pure fold; outcome exhausted with the non-null value. |
| runGraftPartialSubtree | graft-partial-subtree (DEF-5): the three-rung limit ladder is severed mid-top-rung after two completed rung attempts; the byte-identical re-add grafts (exclusive link), the completed rung attempts forward-match through the scope alias, and only the interrupted rung reruns live, exactly once. |
| runHalfEscalatedLadder | half-escalated-ladder: some rungs terminal, the active rung dangling mid-attempt at the crash; resume continues the ladder without repaying completed rungs. |
| runIntraRevisionSelfConflict | intra-revision-self-conflict (DEF-8): one revision {cancel_task X, amend_task X, rewire_deps with an edge onto X} resolves strictly in submission order per the sequential intra-revision application semantics. |
| runKbPinReplay | kb-pin-replay: the pin at admission and the repin at the wake, card bytes embedded, model names withheld. |
| runKbProposeQuarantine | kb-propose-quarantine: injected garbage in a proposal is inert, and nothing commits during the run. |
| runKbRepinExpiry | kb-repin-expiry: the repin re-applies the claim filters against a FRESH read; a claim the store dropped between the pin and the wake stops steering, while the boot pin's bytes stand. |
| runLegacyJournalResume | legacy-journal-resume (DEF-3): a journal whose spawns carry no lineage records (the pre-lineage shape) resumes on the current engine; the legacy spawns canonize onto deterministic 'legacy:' LTIDs, forward matching pays nothing for them, and the NEW lineage-declaring spawn's admission entry carries sigVersion 1. |
| runOscillationBounded | oscillation-bounded (DEF-2): an escalated branch is cancelled and re-added byte-identically twice; every plan_revise call debits one revisionUnit (including the drop on the linked done node), each link debits one spawnUnit, the worker is paid exactly once, and the lineage counters never reset. |
| runOscillationFreeze | oscillation-freeze: the coarse-signature oscillation detector freezes further re-adds under hysteresis (distinct from the per-key osc_guard reject). |
| runOscillationFullReuse | oscillation-full-reuse (DEF-5): a branch whose escalated-terminal root is severed by cancel_task and re-added byte-identically links reuse_full: the verdict is embedded in the plan.revision, the node.link (mode full, claim shared) and the by-ref root are present, the reused subtree costs zero live calls, and reclaimedUsdAtLink equals the donor spend. |
| runOscillationGuardTrip | oscillation-guard-trip (DEF-5): the third re-add of one SpawnKey at maxOscillationsPerKey 2 rejects osc_guard as a typed plan_revise error; the run closes through the non-HITL path and the embedded verdicts replay identically. |
| runParkRacesChildCompletion | park-races-child-completion (DEF-8): park_task lands on a running node whose terminal appends moments later; parkRequested is extinguished by the child-result transition, no checkpoint is written, and the node is done. |
| runParkUnpark | park-unpark: park of a running node with checkpoint retention, later unpark and continuation. The worker pays one tool turn, hangs in its second, parks at the boundary, and the unparked continuation resumes from the retained checkpoint (the booted history carries the paid turn). |
| runQueueFailoverDuringForcedFinish | - |
| runRaceTimeoutVsLive | race-timeout-vs-live (DEF-2): a Flavor B deadline resolution and a live class decision race on one suspension; first-wins applies the timeout, the live attempt lands as a noop, and exactly ONE escalationUnits debit exists. Store-independence is asserted by the replay suite. |
| runReserveSurvivesRunExhaustion | reserve-survives-run-exhaustion (DEF-7): cheap workers eat the run ceiling until admission rejects the spawn that would invade the committed finalize reserve; the final wake executes from the reserve and the rejections forward-match on replay. |
| runRespawnPreservesCounter | respawn-preserves-counter (DEF-3): the worker escalates, the orchestrator respawns the SAME logical task with an amended prompt (new content key, same LTID) twice; the third escalation exceeds maxEscalationsPerLogicalTask, is denied on escalationUnits, and the run closes through the non-HITL fallback with identical verdicts and statsBefore on replay. |
| runReviseMidRun | revise-mid-run: a plan revision arrives while a worker subtree is mid-flight. The first worker HANGS until the revision cancels it; the added replacement completes. |
| runReviseRacingDefaultDecision | revise-racing-defaultDecision (DEF-8, mandatory): while the orchestrator sleeps, the upstream Flavor B timeout resolves a node done, a second node escalates, and a third completes; the wake submits ONE stale-based revision {waive_dep, park_task, cancel_task} whose trio drops with the exact reasons and the blockingRef pointing at the defaultDecision resolution. |
| runRevisionExhaustion | revision-exhaustion (DEF-2): the absolute revision budget hits zero; termination.denied precedes the typed error; the guards chain closes the run without HITL. |
| runRewordedLessonsCollide | reworded-lessons-collide (DEF-3): two attempts of one LTID whose prompts differ but whose signature inputs are identical and share the 'binary-search' tag; the engine computes equal approachSig values, lesson_add keys once, and plan_view groups both attempts into one approach. |
| runRungRetryLineage | rung-retry-lineage (DEF-3): the ladder raise continues the SAME logical task with relation rung-retry; attemptsUsed counts both rungs. |
| runStallStreakClassesAndPinning | stall-streak-classes-and-pinning (DEF-3): four attempts of one LTID land transient-error, task-error, no-progress, and ok; the pinned admission snapshots show stallStreak 0, 1, 2 and the post-ok pinned view shows 0; a wake turn re-executed after a crash reads the SAME LineageStats from its snapshot, not a fresh fold. |
| runWorktreeDisposedDegrade | worktree-disposed-degrade (DEF-5): a worktree-isolated graft donor whose tree was NOT retained degrades to a fresh admit with the embedded DedupNote graft_unsafe; a second section verifies reuse_full stays allowed for a worktree donor whose root is terminal (the pin condition applies to grafts only). |
| settled | - |
| unparkPlacementOf | - |
| wouldCreateDepCycle | Cycle check for rewire_deps (a resulting cycle drops the WHOLE op with dep_cycle; rewire_deps is atomic). Answers whether the graph with nodeId's deps replaced by deps contains a cycle reachable from nodeId. add_task cannot create cycles (nothing depends on a node that does not exist yet), so the check is rewire-only. |