Context Handoff
Nothing wears down a person directing AI agents faster than repeating themselves. You mention one crucial constraint on Monday, a replacement worker spins up on Wednesday from a hand-written prompt that forgot to include it, and you return to review work built on an assumption you already ruled out.
Context Handoff takes human and agent memory out of the critical path. Whenever an agent starts or takes over a job, the hub automatically assembles a structured Briefing directly from its durable records — recorded Facts, the pinned spec, active policies, open questions, and the latest checkpoint — and checks a deterministic digest before any hard-to-undo step so late instructions never slip past a running worker.
Fact, Briefing
Why hand-written prompts and raw transcripts both fail
In multi-agent work across communications, operations, research, and engineering, an agent starting a job on Wednesday cannot ask about a constraint it has never heard of. When the lead agent writes each worker's opening prompt by hand, whatever fact the lead happened to recall on Tuesday quietly disappears during Wednesday's takeover.
Forwarding raw chat logs is just as brittle: important constraints often arrive in a different conversation or earlier request, and dumping hundreds of conversational turns drowns a fresh worker in noise. Worse, even a complete opening briefing can go stale mid-job if the requester adds a freeze or exception an hour before the worker takes an irreversible action.
Context Handoff eliminates silent drop-off with three structural rules enforced by the hub:
-
Statements that later work depends on become durable Facts. The lead
records each requester constraint once as an immutable
Factwith its scope, source, and timestamp — never leaving it buried in a chat transcript. -
The Hub assembles every Briefing deterministically from records. No
agent summarizes briefings by hand. On start, takeover, or recheck, the hub copies the
current spec, facts, policies, open questions, and latest checkpoint into a stored
Briefingstamped with a contentdigest. -
Irreversible steps require an acknowledged, current briefing. Before a
worker runs a migration, sends external mail, or deploys, the hub compares its held
digestagainst a fresh assembly — rejecting stale copies withbriefing_staleand delivering the exact delta.
Why hash the record IDs instead of asking a model to summarize context?
Copying exact records through a deterministic template removes the chance of a summarizer
dropping a subtle negation ("do not change the schema"). And computing a
digest over the included record IDs (plus
newer_version) makes staleness detection instant and exact
— while creating an audit trail showing whether a missed fact was never recorded, out of
scope, or delivered and ignored.
Architecture and participants
Whenever a job starts, transfers to a replacement worker, or hits a pre-action recheck, the
Hub reads five durable record types —
Request spec, Fact,
Policy, Checkpoint, and
Question — and writes an immutable
Briefing record delivered identically to workers and
checkers alike.
Fact rows with source and scope, and assigns jobs —
never hand-writing ad-hoc handoff summaries.
Briefing from live
records, stores its verbatim body and digest, tracks acknowledgment, and blocks
irreversible steps when a held briefing is stale.
Execution flow
Toggle between the normal takeover path — where a fact recorded on Monday automatically reaches Worker 2 on Wednesday without anyone forwarding it — and the stale-briefing path — where a last-minute freeze fact blocks an irreversible step on Thursday.
The requester states a key fact once on Monday; the lead records it. When Worker 1's machine shuts down after saving a checkpoint, the hub automatically assembles Worker 2's takeover briefing with the spec, Monday's fact, policies, and Worker 1's checkpoint.
Same steps 1–9 as normal flow; begins while Worker 2 holds Wednesday's takeover briefing.
After the requester adds a freeze instruction on Wednesday afternoon, Worker 2 checks
its briefing before running a hard-to-undo step on Thursday. The digest mismatch raises
briefing_stale, delivers a fresh recheck briefing
marking the new fact, and stops the unsafe step before it runs.
Concrete examples
Context Handoff prevents repeated explanations and mid-flight policy violations across any workflow where agents hand off work or execute irreversible actions.
Example 1 — Customer pricing announcement rollout
No code or unit tests- Fact recorded
-
On Monday, the marketing director tells the lead agent: "Enterprise annual
contracts require 90 days' notice — never send them the 30-day template." The
lead records this as a requester-wide
Fact. - Takeover briefing
-
Worker 1 drafts the templates and hits its context limit; Worker 2 takes over via a
hub-assembled
takeoverbriefing that automatically includes the 90-day fact verbatim alongside Worker 1's checkpoint. - Pre-send recheck
-
On Thursday morning, legal adds a new fact: "Hold all EMEA sends until German
sign-off." Before scheduling the irreversible bulk send, Worker 2's digest check
fails with
briefing_stale, surfaces the EMEA hold, and pauses that segment automatically.
Example 2 — Shared invoice database and schema freeze
Everyday engineering- Fact recorded
-
On Monday, the requester mentions: "The web app and the API share one
database." The lead records it as a
Factwith source and timestamp. - Takeover briefing
- Worker 1 finishes the invoice API endpoint, saves a checkpoint, and its machine is shut down. On Wednesday, Worker 2 takes over with a hub-assembled briefing carrying spec v2, Monday's shared-DB fact, active policies, and Worker 1's checkpoint — so it reads invoices directly instead of inventing an unnecessary sync job.
- Pre-migration recheck
-
On Wednesday afternoon, the requester adds a freeze fact: "Do not change the
database schema until Friday's release." On Thursday, before running a schema
migration, Worker 2 checks its briefing; the hub returns
briefing_stalewith the new fact, and Worker 2 parks the migration until Friday.
What this pattern is NOT — Single-thread chat or live model switch
Negative example- Request
- One agent completing an entire task in a single conversation, or moving a live back-and-forth chat to a different model mid-discussion.
- Why skip it
- A single conversation already holds its own context, and switching models mid-chat needs the literal turn-by-turn transcript rather than a newly compiled job briefing.
When to use and when to skip
Use Context Handoff when
- Workers, replacements, or checkers start after the requester stated facts they rely on.
- Work spans multiple sessions or days, making human or lead-agent prompt copying error-prone.
- Facts, policies, or specs can change mid-job before hard-to-undo steps execute.
- You want an audit trail proving exactly what context each agent received and acknowledged.
Skip it when
- One agent handles the entire request inside a single live conversation from start to finish.
- The next agent must literally continue the same conversational dialogue turn by turn (forward the transcript instead).
Data model and hub invariants
Context Handoff defines two durable tables — facts and
briefings — assembling context from eight records defined
across the catalog: parties,
requests, jobs,
attempts, request_specs,
checkpoints, policies,
and questions.
Fact rows are append-only (superseded via
replaced_by_id or withdrawn_at).
Each Briefing captures the exact record IDs, verbatim
body, and SHA-256 digest delivered to one recipient at one point in time.
Table: facts
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique fact identifier. |
| request_id | uuid | NULLABLE, FK | References requests(id); null means general across all requests by this requester. |
| text | text | NOT NULL | Concise single-sentence fact, using the requester's exact words whenever possible. |
| stated_by_id | uuid | NOT NULL, FK | References parties(id); the requester who stated it. |
| source | text | NOT NULL | Link or short citation (e.g. "Requester to lead agent in chat"). |
| stated_at | timestamptz | NOT NULL | When the requester stated the fact. |
| recorded_by_id | uuid | NOT NULL, FK | References parties(id); typically the lead agent. |
| replaced_by_id | uuid | NULLABLE, FK | Self-FK to facts(id) when superseded by a newer fact. |
| withdrawn_at | timestamptz | NULLABLE | Timestamp if withdrawn without a replacement. |
Table: briefings
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique briefing identifier. |
| recipient_id | uuid | NOT NULL, FK | References parties(id); worker or checker. |
| job_id | uuid | NOT NULL, FK | References jobs(id). |
| attempt_id | uuid | NULLABLE, FK | References attempts(id); null when recipient is a checker. |
| kind | text | NOT NULL | CHECK (kind IN ('start', 'takeover', 'recheck')). |
| request_spec_id | uuid | NOT NULL, FK | References request_specs(id) pinned by the job. |
| newer_version | integer | NULLABLE | Current spec version number if the request moved ahead of the job's pinned spec. |
| checkpoint_id | uuid | NULLABLE, FK | References checkpoints(id); latest checkpoint when one exists. |
| fact_ids | jsonb | NOT NULL | Ordered list of current scoped Fact IDs (oldest first). |
| policy_ids | jsonb | NOT NULL | List of active Policy IDs in scope for this job. |
| question_ids | jsonb | NOT NULL | List of open Question IDs on this job. |
| body | text | NOT NULL | Exact rendered text delivered to the recipient (never edited). |
| digest | text | NOT NULL | Deterministic SHA-256 hash of the six source ID fields and newer_version. |
| assembled_at | timestamptz | NOT NULL | Timestamp when the hub assembled this briefing. |
| acknowledged_at | timestamptz | NULLABLE | Set once when the recipient confirms it read the briefing. |
Six hub invariants
-
01Facts are append-only; corrections replace or withdraw without editing Database constraint
A fact is current iff
replaced_by_id IS NULL AND withdrawn_at IS NULL. Attempting to supersede an already-inactive fact fails withfact_already_inactive. -
02Briefings include only current, in-scope records at assembly time Hub guard
Assembly gathers only active facts matching the job's
request_id(or general facts whererequest_id IS NULLstated by that request's requester), plus the job's spec,newer_versionflag, active policies, open questions, and latest checkpoint. -
03Every attempt begins with a briefing created in the same transaction Hub guard
Opening an attempt always creates its initial
startortakeoverbriefing atomically, guaranteeing zero unbriefed worker sessions. -
04Briefings never change after assembly except one-time acknowledgment Hub guard
body,digest, and source ID arrays are immutable;acknowledged_attransitions fromNULLto a timestamp once. -
05Digest hashes source record IDs and newer_version deterministically Hub guard
Because the digest covers sorted source IDs and
newer_versionrather than formatting quirks, a briefing is stale iff a freshly assembled briefing produces a differentdigest. -
06Hard-to-undo steps require an acknowledged, current briefing Hub guard
Before allowing an irreversible step, the hub verifies
acknowledged_atis set (elsebriefing_not_acknowledged) and rechecks the digest (elsebriefing_stalewith the newly added facts).
Reference implementation
The same deterministic briefing assembler, digest check, and irreversible-step gate in Lean, TypeScript, Python, and Elixir.
-- Hub guards for Context Handoff (deterministic assembly + digest staleness check)
import Std.Data.HashMap
open Std (HashMap)
inductive BriefingKind where
| start | takeover | recheck
deriving Repr, BEq
structure Fact where
id : String
requestId : Option String -- `none`: a standing fact about the requester
text : String
statedById : String
source : String
statedAt : String
replacedById : Option String := none
withdrawnAt : Option String := none
deriving Repr
structure Job where
id : String
requestId : String
requesterId : String
requestSpecId : String
currentSpecVersion : Nat
jobSpecVersion : Nat
latestCheckpointId : Option String := none
policyIds : List String := []
openQuestionIds : List String := []
deriving Repr
structure Briefing where
id : String
jobId : String
recipientId : String
attemptId : Option String
kind : BriefingKind
factIds : List String
newerVersion : Option Nat
body : String
digest : String
assembledAt : String
acknowledgedAt : Option String := none
deriving Repr
inductive HubError where
| factAlreadyInactive | unknownJob | unknownBriefing | briefingNotAcknowledged
| briefingStale (addedFactIds : List String) -- carries the facts the holder hasn't seen
deriving Repr, BEq
-- The hub is plain data; every guard returns a new hub or an error.
structure BriefingHub where
jobs : HashMap String Job := {}
facts : HashMap String Fact := {}
briefings : HashMap String Briefing := {}
namespace BriefingHub
def recordFact (hub : BriefingHub) (fact : Fact) : Fact × BriefingHub :=
(fact, { hub with facts := hub.facts.insert fact.id fact })
def replaceFact (hub : BriefingHub) (oldId : String) (replacement : Fact) :
Except HubError BriefingHub :=
-- Only a fact that is neither replaced nor withdrawn (bound as `prev`) can be replaced.
match hub.facts.get? oldId with
| some prev@{ replacedById := none, withdrawnAt := none, .. } =>
let facts := hub.facts
|>.insert replacement.id replacement
|>.insert oldId { prev with replacedById := some replacement.id }
pure { hub with facts }
| _ => throw .factAlreadyInactive
-- Stands in for SHA-256 of a canonical encoding: Lean's core library has no crypto.
def computeDigest (job : Job) (newerVersion : Option Nat) (factIds : List String) : String :=
let key := (job.requestSpecId, newerVersion, job.latestCheckpointId,
factIds.mergeSort, job.policyIds.mergeSort, job.openQuestionIds.mergeSort)
toString (hash key)
def assemble (hub : BriefingHub) (jobId recipientId : String) (attemptId : Option String)
(kind : BriefingKind) (briefingId now : String) :
Except HubError (Briefing × BriefingHub) := do
let some job := hub.jobs.get? jobId | throw .unknownJob
let activeFacts := hub.facts.values
|>.filter (fun f => f.replacedById.isNone && f.withdrawnAt.isNone)
|>.filter (fun f => f.requestId == some job.requestId
|| (f.requestId.isNone && f.statedById == job.requesterId))
|>.mergeSort (fun a b => a.statedAt <= b.statedAt)
let newerVersion :=
if job.currentSpecVersion > job.jobSpecVersion then some job.currentSpecVersion else none
let factIds := activeFacts.map (·.id) -- `(·.id)` is `fun f => f.id`
let digest := computeDigest job newerVersion factIds
let body := "\n".intercalate (activeFacts.map fun f => s!"- {f.text} ({f.source})")
let briefing : Briefing := {
id := briefingId, jobId, recipientId, attemptId, kind,
factIds, newerVersion, body, digest, assembledAt := now }
pure (briefing, { hub with briefings := hub.briefings.insert briefingId briefing })
def acknowledge (hub : BriefingHub) (briefingId now : String) :
Except HubError (Briefing × BriefingHub) := do
let some b := hub.briefings.get? briefingId | throw .unknownBriefing
-- `<|>` keeps the first acknowledgement time if there already is one.
let acked := { b with acknowledgedAt := b.acknowledgedAt <|> some now }
pure (acked, { hub with briefings := hub.briefings.insert briefingId acked })
-- Success means the held briefing is still current; the recheck briefing is kept.
def assertIrreversibleStepAllowed (hub : BriefingHub) (briefingId recheckId now : String) :
Except HubError BriefingHub := do
let some held := hub.briefings.get? briefingId | throw .unknownBriefing
if held.acknowledgedAt.isNone then throw .briefingNotAcknowledged
let (fresh, hub) ←
hub.assemble held.jobId held.recipientId held.attemptId .recheck recheckId now
unless fresh.digest == held.digest do
throw (.briefingStale (fresh.factIds.filter (!held.factIds.contains ·)))
pure hub
end BriefingHub
-- Invariant: no irreversible step is allowed on a briefing the hub never assembled.
theorem irreversibleStep_unknown (b r now : String) :
({} : BriefingHub).assertIrreversibleStepAllowed b r now = throw .unknownBriefing := by
simp [BriefingHub.assertIrreversibleStepAllowed]
// Hub guards for Context Handoff (deterministic assembly + digest staleness check)
import { createHash } from "node:crypto";
type BriefingKind = "start" | "takeover" | "recheck";
interface Fact {
id: string;
requestId: string | null;
text: string;
statedById: string;
source: string;
statedAt: string;
replacedById: string | null;
withdrawnAt: string | null;
}
interface Job {
id: string;
requestId: string;
requesterId: string;
requestSpecId: string;
currentSpecVersion: number;
jobSpecVersion: number;
latestCheckpointId: string | null;
policyIds: string[];
openQuestionIds: string[];
}
interface Briefing {
id: string;
jobId: string;
recipientId: string;
attemptId: string | null;
kind: BriefingKind;
factIds: string[];
newerVersion: number | null;
body: string;
digest: string;
assembledAt: string;
acknowledgedAt: string | null;
}
class BriefingHub {
private jobs = new Map<string, Job>();
private facts = new Map<string, Fact>();
private briefings = new Map<string, Briefing>();
recordFact(fact: Fact): Fact {
this.facts.set(fact.id, fact);
return fact;
}
replaceFact(oldId: string, replacement: Fact): void {
const prev = this.facts.get(oldId);
if (!prev || prev.replacedById || prev.withdrawnAt) {
throw new Error("fact_already_inactive");
}
this.facts.set(replacement.id, replacement);
prev.replacedById = replacement.id;
}
assemble(
jobId: string,
recipientId: string,
attemptId: string | null,
kind: BriefingKind,
briefingId: string,
now: string
): Briefing {
const job = this.jobs.get(jobId);
if (!job) throw new Error("unknown_job");
const activeFacts = [...this.facts.values()]
.filter((f) => !f.replacedById && !f.withdrawnAt)
.filter((f) => f.requestId === job.requestId || (f.requestId === null && f.statedById === job.requesterId))
.sort((a, b) => a.statedAt.localeCompare(b.statedAt));
const newerVersion = job.currentSpecVersion > job.jobSpecVersion ? job.currentSpecVersion : null;
const factIds = activeFacts.map((f) => f.id);
const digest = this.computeDigest(job, newerVersion, factIds);
const body = activeFacts.map((f) => `- ${f.text} (${f.source})`).join("\n");
const briefing: Briefing = {
id: briefingId, jobId, recipientId, attemptId, kind,
factIds, newerVersion, body, digest, assembledAt: now, acknowledgedAt: null
};
this.briefings.set(briefingId, briefing);
return briefing;
}
acknowledge(briefingId: string, now: string): Briefing {
const b = this.briefings.get(briefingId);
if (!b) throw new Error("unknown_briefing");
if (!b.acknowledgedAt) b.acknowledgedAt = now;
return b;
}
assertIrreversibleStepAllowed(briefingId: string, recheckId: string, now: string): "current" {
const held = this.briefings.get(briefingId);
if (!held) throw new Error("unknown_briefing");
if (!held.acknowledgedAt) throw new Error("briefing_not_acknowledged");
const fresh = this.assemble(held.jobId, held.recipientId, held.attemptId, "recheck", recheckId, now);
if (fresh.digest !== held.digest) {
throw new Error("briefing_stale");
}
return "current";
}
private computeDigest(job: Job, newerVersion: number | null, factIds: string[]): string {
const payload = JSON.stringify([
job.requestSpecId, newerVersion, job.latestCheckpointId,
[...factIds].sort(), [...job.policyIds].sort(), [...job.openQuestionIds].sort()
]);
return createHash("sha256").update(payload).digest("hex");
}
}
# Hub guards for Context Handoff (deterministic assembly + digest staleness check)
from dataclasses import dataclass, field
import hashlib
import json
from typing import Literal, Optional
@dataclass
class Fact:
id: str
request_id: Optional[str]
text: str
stated_by_id: str
source: str
stated_at: str
replaced_by_id: Optional[str] = None
withdrawn_at: Optional[str] = None
@dataclass
class Job:
id: str
request_id: str
requester_id: str
request_spec_id: str
current_spec_version: int
job_spec_version: int
latest_checkpoint_id: Optional[str] = None
policy_ids: list[str] = field(default_factory=list)
open_question_ids: list[str] = field(default_factory=list)
@dataclass
class Briefing:
id: str
job_id: str
recipient_id: str
attempt_id: Optional[str]
kind: Literal["start", "takeover", "recheck"]
fact_ids: list[str]
newer_version: Optional[int]
body: str
digest: str
assembled_at: str
acknowledged_at: Optional[str] = None
class HubError(Exception):
pass
class BriefingHub:
def __init__(self) -> None:
self.jobs: dict[str, Job] = {}
self.facts: dict[str, Fact] = {}
self.briefings: dict[str, Briefing] = {}
def record_fact(self, fact: Fact) -> Fact:
self.facts[fact.id] = fact
return fact
def replace_fact(self, old_id: str, replacement: Fact) -> None:
prev = self.facts.get(old_id)
if prev is None or prev.replaced_by_id or prev.withdrawn_at:
raise HubError("fact_already_inactive")
self.facts[replacement.id] = replacement
prev.replaced_by_id = replacement.id
def assemble(
self,
job_id: str,
recipient_id: str,
attempt_id: Optional[str],
kind: Literal["start", "takeover", "recheck"],
briefing_id: str,
now: str,
) -> Briefing:
job = self.jobs.get(job_id)
if job is None:
raise HubError("unknown_job")
active = [
f for f in self.facts.values()
if f.replaced_by_id is None and f.withdrawn_at is None
and (f.request_id == job.request_id or (f.request_id is None and f.stated_by_id == job.requester_id))
]
active.sort(key=lambda f: f.stated_at)
newer = job.current_spec_version if job.current_spec_version > job.job_spec_version else None
fact_ids = [f.id for f in active]
digest = self._digest(job, newer, fact_ids)
body = "\n".join(f"- {f.text} ({f.source})" for f in active)
briefing = Briefing(
id=briefing_id, job_id=job_id, recipient_id=recipient_id, attempt_id=attempt_id,
kind=kind, fact_ids=fact_ids, newer_version=newer, body=body, digest=digest,
assembled_at=now,
)
self.briefings[briefing_id] = briefing
return briefing
def acknowledge(self, briefing_id: str, now: str) -> Briefing:
b = self.briefings.get(briefing_id)
if b is None:
raise HubError("unknown_briefing")
if b.acknowledged_at is None:
b.acknowledged_at = now
return b
def assert_irreversible_step_allowed(self, briefing_id: str, recheck_id: str, now: str) -> str:
held = self.briefings.get(briefing_id)
if held is None:
raise HubError("unknown_briefing")
if held.acknowledged_at is None:
raise HubError("briefing_not_acknowledged")
fresh = self.assemble(held.job_id, held.recipient_id, held.attempt_id, "recheck", recheck_id, now)
if fresh.digest != held.digest:
raise HubError("briefing_stale")
return "current"
def _digest(self, job: Job, newer: Optional[int], fact_ids: list[str]) -> str:
raw = json.dumps([
job.request_spec_id, newer, job.latest_checkpoint_id,
sorted(fact_ids), sorted(job.policy_ids), sorted(job.open_question_ids),
])
return hashlib.sha256(raw.encode()).hexdigest()
# Hub guards for Context Handoff (pure functional core)
defmodule BriefingHub do
defstruct jobs: %{}, facts: %{}, briefings: %{}
def record_fact(%BriefingHub{} = hub, fact) do
{:ok, fact, %{hub | facts: Map.put(hub.facts, fact.id, fact)}}
end
def replace_fact(%BriefingHub{} = hub, old_id, replacement) do
case Map.get(hub.facts, old_id) do
%{replaced_by_id: nil, withdrawn_at: nil} = prev ->
facts =
hub.facts
|> Map.put(replacement.id, replacement)
|> Map.put(old_id, %{prev | replaced_by_id: replacement.id})
{:ok, %{hub | facts: facts}}
_ ->
{:error, :fact_already_inactive}
end
end
def assemble(%BriefingHub{} = hub, job_id, recipient_id, attempt_id, kind, briefing_id, now) do
with {:ok, job} <- Map.fetch(hub.jobs, job_id) |> or_err(:unknown_job) do
active =
hub.facts
|> Map.values()
|> Enum.filter(&(is_nil(&1.replaced_by_id) and is_nil(&1.withdrawn_at)))
|> Enum.filter(&(&1.request_id == job.request_id or (is_nil(&1.request_id) and &1.stated_by_id == job.requester_id)))
|> Enum.sort_by(& &1.stated_at)
newer = if job.current_spec_version > job.job_spec_version, do: job.current_spec_version
fact_ids = Enum.map(active, & &1.id)
digest = compute_digest(job, newer, fact_ids)
body = Enum.map_join(active, "\n", &"- #{&1.text} (#{&1.source})")
briefing = %{
id: briefing_id, job_id: job_id, recipient_id: recipient_id, attempt_id: attempt_id,
kind: kind, fact_ids: fact_ids, newer_version: newer, body: body, digest: digest,
assembled_at: now, acknowledged_at: nil
}
{:ok, briefing, %{hub | briefings: Map.put(hub.briefings, briefing_id, briefing)}}
end
end
def acknowledge(%BriefingHub{} = hub, briefing_id, now) do
with {:ok, b} <- Map.fetch(hub.briefings, briefing_id) |> or_err(:unknown_briefing) do
acked = %{b | acknowledged_at: b.acknowledged_at || now}
{:ok, acked, %{hub | briefings: Map.put(hub.briefings, briefing_id, acked)}}
end
end
def assert_irreversible_step_allowed(%BriefingHub{} = hub, briefing_id, recheck_id, now) do
with {:ok, held} <- Map.fetch(hub.briefings, briefing_id) |> or_err(:unknown_briefing),
true <- not is_nil(held.acknowledged_at) || {:error, :briefing_not_acknowledged},
{:ok, fresh, hub} <- assemble(hub, held.job_id, held.recipient_id, held.attempt_id, :recheck, recheck_id, now) do
if fresh.digest == held.digest do
{:ok, :current}
else
added = fresh.fact_ids -- held.fact_ids
{:error, :briefing_stale, fresh, added, hub}
end
end
end
defp compute_digest(job, newer, fact_ids) do
key = [
job.request_spec_id, newer, job.latest_checkpoint_id,
Enum.sort(fact_ids), Enum.sort(job.policy_ids), Enum.sort(job.open_question_ids)
]
:sha256 |> :crypto.hash(:erlang.term_to_binary(key)) |> Base.encode16(case: :lower)
end
defp or_err({:ok, val}, _err), do: {:ok, val}
defp or_err(:error, err), do: {:error, err}
end
Takeover and schema-freeze trace
Walking Example 2 (shared invoice database and schema freeze) through
these guards shows Monday's fact flowing into Wednesday's takeover briefing automatically
and Thursday's migration stopping on briefing_stale:
1. hub.recordFact(fact_shared_db)
// requestId: req_invoices, text: "The web app and the API share one database"
-> ok (fact_shared_db active; source and timestamp recorded)
2. // Wednesday takeover: Worker 2 replaces Worker 1
held = hub.assemble(job_invoices, worker_2, attempt_2, "takeover", "br_takeover_1", "Wed 09:40Z")
hub.acknowledge("br_takeover_1", "Wed 09:41Z")
-> ok (fact_ids: [fact_shared_db]; checkpoint_id: cp_api_done; digest: "8a4f...")
3. hub.assertIrreversibleStepAllowed("br_takeover_1", "br_recheck_1", "Wed 12:00Z")
-> ok ("current" — acknowledged and digest matches current records)
4. // Wednesday 16:30Z: requester adds schema freeze fact (requestId: null)
hub.recordFact(fact_schema_freeze)
-> ok (general fact active for all requests by requester_dana)
5. // Thursday 09:00Z: Worker 2 checks briefing before running DB migration
hub.assertIrreversibleStepAllowed("br_takeover_1", "br_recheck_2", "Thu 09:00Z")
-> error: briefing_stale (added: [fact_schema_freeze]; br_recheck_2 stored)
6. hub.acknowledge("br_recheck_2", "Thu 09:01Z")
-> ok (Worker 2 skips migration and parks job until Friday's release)
Tradeoffs and practical guidance
Context Handoff shifts handoff reliability from ad-hoc prompting to structured records. Keep three practical tradeoffs in mind:
- Fact capture still requires judgment: the lead agent must still recognize when a requester sentence is a durable constraint worth recording. A missed fact stays invisible; an inaccurately recorded fact spreads to every worker with the requester's authority.
- Briefings can bloat over time: accumulating too many requester-wide facts adds tokens to every job and buries the crucial constraint. Scope facts narrowly and withdraw outdated ones promptly.
- Pre-action rechecks add a round trip: workers must call the hub before irreversible actions — and only external hub enforcement guarantees they never skip it.
Practical implementation notes
- Copy records verbatim through a fixed template: never let a model paraphrase facts or policies during briefing assembly; deterministic templates cannot silently invert a constraint.
- Enforce the recheck outside the worker: pair Context Handoff with a Policy Gate on irreversible actions (migrations, production deploys, customer emails) so the hub refuses any unacknowledged or stale briefing automatically.
- Allow no side-channel DMs: if the lead whispers a job-specific detail in a private message to Worker 1, Worker 2 will never receive it; job-specific instructions belong on the job record so assembly always picks them up.
-
Scope facts carefully: attach request-specific constraints to
request_idand reserverequest_id = NULLfor standing truths that genuinely apply across every request from that requester.
Known uses and related patterns
- OpenAI Agents SDK Handoffs: transfers conversation history between agents with optional input filters; Context Handoff pulls durable facts even when they originated in separate threads and detects mid-job staleness via digests.
- Claude Code subagent delegation: starts fresh subagent contexts with a delegation prompt plus repository instruction files; Context Handoff replaces manual delegation summaries with hub-assembled, versioned briefings.
- Letta shared memory blocks: shares mutable memory blocks across agents; Context Handoff additionally stores an immutable per-delivery briefing snapshot with digest and acknowledgment timestamps for auditability.
- Volgenic: composes each fresh agent's starting prompt from live hub records (policies, work items, linked references) inside one read transaction rather than relying on ad-hoc chat summaries.
- Hohpe & Woolf's Content Enricher: from Enterprise Integration Patterns — augments an outbound message from an authoritative store when the sender lacks complete data; the hub acts as a Content Enricher for every agent start.
Related patterns
- Request Spec — most easily confused with Context Handoff; Request Spec stores what the requester wants, while Context Handoff delivers that spec plus facts, policies, and checkpoints to each agent.
- Durable Job — defines the attempt and checkpoint records; Durable Job decides who owns the job, while Context Handoff decides what that owner is told.
- Tracked Answer — tracks one human reply until applied; Context Handoff's digest check catches any newly recorded fact or spec change before irreversible steps.
- Change Propagation — proactively flags affected jobs when a spec changes; a stale briefing is how an active worker discovers the drift at its own check boundary.
- Policy Gate — enforces the current-briefing check automatically at irreversible transitions.
- Orchestrator-Workers, Delegation Policy & Self-Contained Question — define the Request, Policy, and Question records assembled into each briefing.