Skip to content

Spec2Contract Handoff

Grzegorz Nowak edited this page Oct 10, 2026 · 2 revisions

Spec-to-contracts — Handoff (book ↔ in-tests contracts)

This page maps the Product Book's Handoff area — claim prefix PB-HANDOFF-01…PB-HANDOFF-46 (46 rows) — onto the existing pi-schematic tests. The contracts are carried mainly by T11 handoff.test.ts (tool/command/frame/eligibility integration), T12 handoff-eligibility.test.ts (pure threshold math), and T13 handoff-recovery.test.ts (lost-successor recovery); T14 handoff-import-graph.test.ts covers handoff module initialization order but maps to no PB-HANDOFF row (see the note under empty surfaces). Secondary sealing comes from T30 readonly-handoff.test.ts, T46 watchdog.test.ts, T37 state-invariants.test.ts, T01/T28 spawn*, T43 notifications.test.ts, T47 tests/e2e/basic.test.ts and T49 tests/e2e/real-host.test.ts. Status is conservative: "asserted" means an existing named test represents the claim, not that the suite passes.

Junction rows

Claim ID Assertion (terse) Fixture(s) Status Notes
PB-HANDOFF-01 handoff tool registered with the label Handoff — ⚠️ no test yet Tool is registered (T49 host starts and extension registers / commands are registered) but no test reads the registered entry's label; a test would assert pi.tools.get("handoff").label === "Handoff".
PB-HANDOFF-01 Calling it deliberately compacts context, keeps the notebook, clears the active topic T11, T49 ✅ asserted T11 handoff tool queues the split request and delivers it verbatim after compaction (cut + terminate), handoff with empty discardPages retains all pages (notebook kept), handoff compaction keeps the frame constant and the state contract intact; topic cleared asserted in handoff onComplete fails gracefully when the discard commit marker throws and successor delivery is requested as a followUp (queue-safe contract).
PB-HANDOFF-02 Optional nextInstruction string = successor instruction, verbatim T11 ✅ asserted T11 handoff tool metadata and schema describe the prompt contract (all params optional via Value.Check; no "task" field), handoff with no pending direction requires nextInstruction but not context.
PB-HANDOFF-03 Optional context string = model-owned situational remainder T11 ✅ asserted T11 handoff tool metadata and schema describe the prompt contract (Value.Check({context}) true; schema text /current state, blockers/), buildNextUserMessage carries the instruction verbatim and the context second.
PB-HANDOFF-04 Optional discardPages array applied during the handoff T11 ✅ asserted T11 successful handoff discards pages after compaction (Notebook: 0 pages kept, 1 discarded), handoff with empty discardPages retains all pages.
PB-HANDOFF-04 Page names are de-duplicated before staging — ⚠️ no test yet No test passes duplicate names. A test would call handoff with discardPages: ["stale","stale"] and assert the staged/deleted list (or report count) counts it once.
PB-HANDOFF-05 Returns { content: "Handoff started.", terminate: true }; turn terminates T11 ✅ asserted T11 handoff tool queues the split request and delivers it verbatim after compaction asserts result.content[0].text === "Handoff started." and result.terminate === true.
PB-HANDOFF-05 Tool runs in sequential execution mode — ⚠️ no test yet No test reads tool.executionMode for handoff (T01 asserts spawn is not sequential, so spawn.test.ts covers the inverse only). A test would assert pi.tools.get("handoff").executionMode === "sequential".
PB-HANDOFF-06 Second handoff while a compaction is in flight is rejected T11 ✅ asserted T11 handoff rejects overlapping compaction and preserves the first task (rejects /handoff compaction already in progress/i, first marker preserved). Exact trailing sentence retry after it completes is not asserted.
PB-HANDOFF-07 Advertises as preparation only; instruction must never be performed in this context, discarded at compaction T11 ✅ asserted T11 handoff tool metadata and schema describe the prompt contract (promptGuidelines /preparation only/), /handoff sends the direction back through the LLM without opening the editor (/Do NOT start this instruction/, /discarded at compaction/).
PB-HANDOFF-08 /handoff <direction> registered; stores direction as successor instruction, then asks model to curate notebook + supply context T11, T49 ✅ asserted T11 /handoff sends the direction back through the LLM without opening the editor (stores nextInstruction, message /Curate the notebook/, /Call the handoff tool with context/); T49 commands are registered.
PB-HANDOFF-09 Empty/whitespace direction rejected with Usage: /handoff <direction>, nothing queued T11 ✅ asserted T11 /handoff requires a direction (notify exactly "Usage: /handoff <direction>", sentUserMessages empty).
PB-HANDOFF-10 Pending human /handoff direction wins over model nextInstruction T11 ✅ asserted T11 a pending human direction wins over a model-supplied nextInstruction, a pending human direction needs no tool arguments, stored human direction survives a failed compaction and is delivered on retry.
PB-HANDOFF-11 Resolved instruction whitespace-trimmed; inner bytes preserved T11 ✅ asserted T11 a pending human direction wins over a model-supplied nextInstruction (trimmed human direction), handoff with no pending direction requires nextInstruction but not context (" Ship the fix " → "Ship the fix"), buildNextUserMessage preserves instruction bytes and normalizes context padding (byte-for-byte property).
PB-HANDOFF-12 /handoff starts a new request generation, invalidating earlier queued work before replacing its intent T11, T37 ◐ partly asserted T11 session_before_compact ignores a stale generation and handoff compaction ignores a delivery payload from a stale generation assert the consumers ignore mismatched generations; T37 reset increments handoffGeneration and clears compaction reservations and invalidateHandoffState clears branch-local compaction reservations assert the generation/reservation side of invalidation. Missing portion: no test issues a second /handoff over a queued request and asserts the first queued request is invalidated.
PB-HANDOFF-13 With a human direction pending, model is told to supply only the remaining context; watchdog says "call handoff with only the remaining context" T46 ✅ asserted T46 buildNudge uses prompt wording for eligible requested handoffs and topic boundaries asserts the directed nudge contains /call handoff with only the remaining context/ and /successor receives the instruction verbatim/.
PB-HANDOFF-14 /handoff prompt: "Do NOT start this instruction. This context is discarded at compaction." T11 ✅ asserted T11 /handoff sends the direction back through the LLM without opening the editor (/Do NOT start this instruction/, /discarded at compaction/).
PB-HANDOFF-15 Sticky request cancelled after 5 eligible turns without the tool, warning "Required handoff cancelled after 5 turns without completion." T11, T46 ✅ asserted T46 watchdog auto-cancels a required handoff after enough unanswered turns (uses MAX_HANDOFF_ATTEMPTS, /Required handoff cancelled/i, clears status); T11 command handoff waits for eligibility and retries without watchdog cancellation (ineligible turns don't consume the budget).
PB-HANDOFF-16 Empty resolved instruction rejected; error names current context percentage and tells model to save findings to notebook first T11 ◐ partly asserted T11 handoff tool rejects an empty nextInstruction with context usage and handoff tool rejects a whitespace-only nextInstruction assert the rejection and the percentage (42% / Context at ?), but the "Save findings to notebook, then call handoff…" guidance sentence is not asserted.
PB-HANDOFF-17 Missing context usage rejected: "Context usage unavailable; handoff rejected. Continue working and retry." T11, T47 ✅ asserted T11 handoff tool rejects when context usage is unavailable (/Context usage unavailable/, /rejected/), handoff rejects malformed numeric context usage, handoff tool rejects when context usage cannot be estimated; T47 handoff tool rejects when context usage is unavailable (ERR:Context usage unavailable).
PB-HANDOFF-18 Session below 30,000-token minimum rejected, message shows token count and approximate percentage T11 ✅ asserted T11 handoff tool rejects small session with clear error (~3% (5000 tokens)), handoff tool rejects small session with null percent without crashing, handoff tool rejects small session estimated from percent when tokens are unavailable, handoff tool rejects session just below the 30000-token minimum.
PB-HANDOFF-19 Tokens taken exactly from usage.tokens, else contextWindow × percent / 100; eligible iff tokens ≥ 30000 (finite, non-negative, overflow accepted) T11, T12 ✅ asserted T12 handoff eligibility prefers explicit tokens, handoff eligibility estimates tokens from percent and context window, context percentage normalization accepts finite non-negative usage, including overflow, handoff eligibility rejects arithmetic overflow, handoff eligibility is monotonic as explicit context tokens grow; T11 handoff tool accepts the exact 30000-token minimum, handoff tool accepts large estimated session when tokens are unavailable.
PB-HANDOFF-20 Rejected tool call throws and sends a queued follow-up with reason + retry guidance T11 ✅ asserted T11 handoff tool preserves pending requested handoff and re-engages LLM after synchronous small-session rejection (rejects + /Handoff failed/ + deliverAs: "followUp" + /required handoff remains pending/), same for …synchronous unavailable-usage rejection.
PB-HANDOFF-21 Compaction failure reported ("Handoff compaction failed: … The handoff can be retried.") and queued follow-up preserves pending-request state for retry T11, T30 ✅ asserted T11 async handoff compaction error retains discard pages and restores a ready retry status (exact message), synchronous compaction failure retains discard pages and restores a retryable handoff, stored human direction survives a failed compaction and is delivered on retry; T30 retry succeeds after a failed compaction attempt.
PB-HANDOFF-22 After handoff the LLM context holds only the fixed continuation frame; no pre-handoff message retained T11 ✅ asserted T11 handoff compaction keeps the frame constant and the state contract intact asserts the returned compaction summary equals buildHandoffCompactionSummary(...) and firstKeptEntryId === "leaf-1-handoff-cut" (an impossible id = nothing kept); the continuation frame is pinned byte-for-byte.
PB-HANDOFF-23 Frame carries no session-specific instruction or mutable posture, so /tree rollback cannot replay stale instruction/posture T11, T30 ✅ asserted T11 the continuation frame is constant and carries no task or constraints (no /## Task/, /Execution Constraints/i, /readonly/i); T30 the handoff summary stays readonly-free and the fresh context relearns readonly live (no readonly, no model-supplied instruction).
PB-HANDOFF-24 Each handoff cut individually identifiable in session history T11, T13 ✅ asserted T11 handoff compaction summaries identify each cut without changing the frame (distinct summaries, <!-- handoff-cut:… --> suffix); T13 recovery tests key delivery by cut id.
PB-HANDOFF-25 Successor gets exactly one real user message: ## Next instruction + verbatim instruction, then ## Context + trimmed context when non-empty T11 ✅ asserted T11 buildNextUserMessage carries the instruction verbatim and the context second (golden string, whitespace-only context adds no section), buildNextUserMessage preserves instruction bytes and normalizes context padding, handoff with no pending direction requires nextInstruction but not context.
PB-HANDOFF-26 Exact successor payload retained on the compaction entry, restorable without paraphrase T11, T13 ✅ asserted T11 a host delivery rejection finalizes the cut while its persisted payload remains recoverable (asserts cut.compaction.details.payload exactly, plus a UUID recoveryKey); T13 recovers the exact successor message from the newest handoff compaction.
PB-HANDOFF-27 TUI successor sent without operational report; headless appends report after \n\n## Handoff report\n\n T11 ✅ asserted T11 handoff success sends a completion notification (TUI successor equals buildNextUserMessage(...), no report), handoff onComplete fails gracefully when the discard commit marker throws (headless report after delimiter), successful handoff discards pages after compaction (TUI message has no ## Handoff report).
PB-HANDOFF-28 Retention outcome observable ("Handoff complete. Notebook: N pages kept[, M discarded]."); failed discard commit reported as retained with warning T11 ✅ asserted T11 successful handoff discards pages after compaction (/Notebook: 0 pages kept, 1 discarded/), handoff onComplete fails gracefully when the discard commit marker throws (Handoff completed, but notebook discard was not persisted …; retained all notebook pages.), post-commit reporting failure does not claim pages were retained.
PB-HANDOFF-29 Post-compaction messages delivered with deliverAs: "followUp" T11, T13 ✅ asserted T11 successor delivery is requested as a followUp (queue-safe contract), failed compaction releases the overlap guard without mutating state twice (failure guidance followUp), post-commit reporting failure does not claim pages were retained; T13 recovery sends assert options: { deliverAs: "followUp" }.
PB-HANDOFF-30 Fire-and-forget delivery: failed send detected from persisted branch, not an error T11, T13 ✅ asserted T11 a host delivery rejection finalizes the cut while its persisted payload remains recoverable (throws but payload durable); T13 recovers the exact successor message from the newest handoff compaction.
PB-HANDOFF-31 Recovery runs on session_start, session_tree, agent_settled T13, T49 ✅ asserted T13 a session start re-opens the delivery scope after an in-process session load, tree navigation and resume queue a missing successor in a fresh process, repeated tree triggers coalesce and a settled run retries only while absent, session start recovers on reasons other than load when the queue is empty; T49 recovery resends a lost successor and stops once it lands.
PB-HANDOFF-32 Only the newest cut considered; unreadable payload there recovers nothing (no older resurrection) T13 ✅ asserted T13 an unreadable newest handoff supersedes an older recoverable one, ignores legacy, malformed, and future handoff details, a non-handoff compaction does not supersede the last handoff cut.
PB-HANDOFF-33 Any user turn after the cut ends recovery; missing successor not resent after newer input T13, T49 ✅ asserted T13 a persisted successor ends recovery, a distinct user turn after the cut abandons recovery, any user-entry shape after the cut abandons recovery, a newer user turn abandons recovery even while the queue is still pending; T49 recovery never appends a lost handoff after newer user work, tree navigation never appends a lost handoff after newer user work.
PB-HANDOFF-34 Delivery attributed by session lineage (nearest cut on parentId chain), so identical payloads cannot mask a loss or duplicate T13 ✅ asserted T13 a predecessor's identical successor does not suppress a later lost delivery, an orphaned parent chain fails open toward resend, a cyclic parent chain terminates without an owner, an intermediate entry between cut and successor preserves ownership, a delivered successor edited away is not re-sent when an earlier cut shares its text, a successor carrying an appended operational report is owned delivery.
PB-HANDOFF-35 Recovery resends only the bare successor; recovered headless delivery drops the operational report T13 ✅ asserted T13 a recovered resend is the bare payload without the operational report.
PB-HANDOFF-36 Repeated recovery triggers coalesced so a lost successor is never delivered twice T13, T49 ✅ asserted T13 repeated tree triggers coalesce and a settled run retries only while absent, a cut shared across tree branches coalesces instead of double-sending, a direct delivery is latched against duplicate tree recovery until settle, identical payloads on separate branches each recover once; T49 persisted successor is not re-delivered by settle or tree navigation.
PB-HANDOFF-37 Recovery retries after a run settles; already delivered/queued successor never re-sent T13 ✅ asserted T13 repeated tree triggers coalesce and a settled run retries only while absent, a later settled run recovers an absent successor only after its queue drains, a recovery send failure releases its latch for the next trigger.
PB-HANDOFF-38 Recovery never fights an in-flight cut and never resends while messages are queued T13 ✅ asserted T13 a settled run during an in-flight cut does not recover an older payload, tree and session-start recovery wait for a queued follow-up to drain.
PB-HANDOFF-39 Under readonly the handoff tool is blocked at call time with a reason explaining it needs the temporary exception and suggesting spawn T30, T43 ◐ partly asserted T30 blocked readonly handoff never invokes compaction (block true, executor unreached); T43 parent readonly tool-call consumer uses centralized block copy (reason === READONLY_HANDOFF_BLOCK_REASON), LLM-facing handoff copy reflects both readonly bypass triggers. Missing portion: the Use spawn for same-topic delegation suggestion in the reason is never asserted.
PB-HANDOFF-40 Running /handoff activates a narrow temporary bypass even under readonly, enabling a real handoff T30, T46 ✅ asserted T30 /handoff command creates temporary bypass for handoff tool only (handoff unblocked; write + non-temp bash stay blocked), after handoff compaction, bypass is cleared and readonly persists, /handoff re-enables bypass after compaction; T46 context injects readonly handoff guidance after explicit user /handoff.
PB-HANDOFF-41 In readonly, an eligible human topic boundary equals /handoff; ineligible boundary stays advisory T30, T46 ✅ asserted T30 readonly topic boundary creates the same bypass contract as explicit /handoff, readonly topic boundary stays advisory until handoff is eligible, readonly human topic boundary promotes exactly at the token threshold without repeated advisory nudges, readonly agent topic boundary is not promoted to handoff bypass, readonly topic boundary promotion exposes the handoff status; T46 eligible readonly human topic boundary auto-creates handoff bypass equivalent to /handoff.
PB-HANDOFF-42 Readonly posture not frozen into summary; live nudge re-announces ON first post-handoff turn; enforcement live; state re-read so readonly resumes after compaction; OFF-to-OFF silent T11, T30 ✅ asserted T30 the handoff summary stays readonly-free and the fresh context relearns readonly live (ON nudge present, OFF-at-cut silent), session resume restores readonly enforcement from persisted state, session tree re-announces readonly even when the rehydrated value is unchanged; T11 handoff onComplete fails gracefully when the discard commit marker throws (readonlyNudgePending === false for OFF).
PB-HANDOFF-43 Active notebook topic cleared on successful handoff T11 ✅ asserted T11 successor delivery is requested as a followUp (queue-safe contract) and handoff onComplete fails gracefully when the discard commit marker throws assert activeNotebookTopic === null after a completed cut.
PB-HANDOFF-44 Spawned children never inherit handoff (or spawn); orchestration stays with the parent T01, T28 ✅ asserted T01 child tool names inherit active registered builtins and exclude recursive controls, buildChildToolNames (2-arg fallback) removes spawn and handoff from inherited tools; T28 buildChildToolNames excludes spawn and handoff from inherited tools.
PB-HANDOFF-45 Compaction starts a new input prefix (dropped history gone for billing/cache); extension creates cache-aware boundaries but does not configure provider cache TTLs/breakpoints T11 ◐ partly asserted T11 handoff compaction keeps the frame constant and the state contract intact asserts the boundary mechanism (firstKeptEntryId = impossible id, fixed frame). Missing portions: no assertion that the successor's prefix excludes dropped history for billing/cache, and no negative assertion that provider cache TTLs/breakpoints are never configured.
PB-HANDOFF-46 TUI footer status: 🤝 Handoff requested — waiting for eligible context, 🤝 Handoff required — ready to compact, 🤝 Handoff in progress; clears on completion/cancellation T11, T46, T49 ✅ asserted T11 /handoff sets the handoff status indicator, /handoff shows ready status when context is eligible, handoff status becomes ready when later context becomes eligible, handoff success sends a completion notification (cleared), turn_end fallback keeps requested handoff status sticky until real handoff happens, synchronous compaction failure … (in-progress preserved); T46 watchdog auto-cancels a required handoff after enough unanswered turns (clears on cancel); T49 readonly topic boundary enables the handoff bypass on the next context hook (in-progress then cleared).

Empty surfaces in this area

No PB-HANDOFF row is entirely unrepresented, but three whole contract surfaces have no fixture:

  • Tool label Handoff (PB-HANDOFF-01, part): would be sealed by asserting the registered tool's label equals "Handoff".
  • discardPages de-duplication (PB-HANDOFF-04, part): would be sealed by calling handoff with duplicate page names and asserting the staged/deleted set (or report count) contains each name once.
  • sequential execution mode (PB-HANDOFF-05, part): would be sealed by asserting pi.tools.get("handoff").executionMode === "sequential".

Additionally, T14 handoff-import-graph.test.ts materializes handoff module-initialization contracts (handoff modules must not top-level import notebook/store; the store is loaded lazily from the execution path), but the Product Book area carries no PB-HANDOFF claim for that surface, so it maps to no row here.

Area coverage summary

Claims Junction rows ✅ ◐ ⚠️
46 49 42 4 3

Clone this wiki locally