Self-Contained Question
Nothing burns a returning human's time faster than a vague ping like "The new version is friendlier and clearer — can we send it?" — no preview attached, no alternatives spelled out, and three follow-up messages after the agent restarted. Answering it forces you to excavate half an hour of logs just to learn what is actually being asked.
Self-Contained Question makes every ask a structured record that the hub checks for completeness before anyone ever sees it. One card carries the question, plain context, concrete options with outcomes, a reasoned recommendation, what work is waiting, a safe fallback if no answer arrives — and the actual artifact itself whenever looks or behavior decide.
Question
Why chat-style questions fail an asynchronous human
An agent writes a question from deep inside its own context window, surrounded by the files, drafts, and assumptions it just read. The human arrives hours later with zero of that context — often after the question was escalated through a lead agent who never saw the original thread either.
When a worker writes "The new payment-failed email is friendlier — OK to ship?" and repeats it twice after restarting, three failures stack up. First, the human has to scroll through history just to reconstruct the choice. Second, one missing decision arrives as three separate pings. Third, describing copy or layout in adjectives instead of showing the actual email invites a hurried "OK" — followed days later by a customer complaint and a reopened job.
Self-Contained Question eliminates all three failures inside the hub rather than hoping agents write better prose:
- Completeness is enforced at admission. Every question passes through a deterministic completeness check in the hub. A vague ask is refused immediately with the exact list of missing parts; the answerer never sees a half-baked prompt.
-
When looks or behavior decide, exhibits are mandatory. Setting
needs_exhibit = truerequires concrete attachments (rendered images, videos, live links, diffs, or verbatim text) for every option so the human judges the thing itself. -
One missing decision equals one versioned card. The asker tags the
decision with a stable
decision_key. If the worker restarts and asks again, the hub folds the repeat into a revision of the existing open question (version + 1), never creating a duplicate card.
Why force the asker to commit to a recommendation and a safe fallback?
Thinking through the outcomes and writing a concrete recommendation often reveals that the
agent can settle the matter itself — preventing unnecessary questions altogether. And naming
a safe if_unanswered default ensures a missed deadline
never leaves work hanging or ships an unapproved risky change.
Architecture and participants
The pattern centers on one durable record — Question — and
one hub admission gate — the Completeness Check. Workers never message
answerers directly: every draft question passes through the hub, which refuses incomplete
drafts, folds repeats by decision_key, and draws the
answerer's Question Card exclusively from the stored record.
Question record from which the card is drawn.
kind and
needs_exhibit, deduplicates retries via
decision_key, rejects answers against stale versions,
draws the card from the record alone, and expires overdue questions at
answer_by.
Question row —
showing effort time, rendered exhibits side by side, recommendation, blocked work, and
fallback behavior.
Execution flow
Toggle between the normal path — where a complete question passes the gate and lets the requester answer from one card — and the failure path — where the hub refuses a vague draft, folds a post-crash retry into version 2, and removes the card cleanly when a scope change causes the lead agent to withdraw it.
Because the question carries both rendered emails, options, recommendation, and effort estimate, the lead agent can pass it untouched to the requester — who sees the exact copy on one card and requests a subject-line tweak before anything ships.
Shows three common failure modes handled automatically by the hub: a vague ask, a worker crash retry, and an upstream scope change before check-in.
The vague draft is refused with incomplete_question
and never reaches the requester. After a crash retry with the same
decision_key, the hub bumps
version to 2 on the same record instead of creating a
second card — and withdrawing the question removes it from the inbox before check-in.
Version guard on replies: Every answer names the
version of the card the human read. If the question was
revised while the human was typing, the hub rejects the reply with
stale_question_version and shows the updated card first.
Concrete examples
Self-Contained Question applies whenever a human must make a judgment call asynchronously — from customer copy and pricing choices to API design tradeoffs.
Example 1 — Payment-failed customer email wording
No code or unit tests- Ask & exhibits
-
Worker 1rewrites Acme's failed-payment notice. Because customer wording is judged by reading it,needs_exhibitistrueand both the current email and new email are attached as rendered exhibits side by side. - Card contents
-
Effort: 2 minutes.
Recommendation: New email — explains the $49.00 decline on card 4242
and gives a direct "Update your card" button.
Blocked work: Only the email job waits; the rest of Thursday's
release proceeds.
Fallback (
if_unanswered): On Thursday at 9:00 a.m., ship with the current email and close this question. - Outcome
- At her Tuesday check-in, Dana reads the rendered email directly on the card — without opening any chat thread — and replies: "Use the new email, and put the dollar amount in the subject line." Seeing the real artifact prevented a post-release reopen.
Example 2 — Public API pagination default decision
Simple API change- Ask & exhibits
-
Worker 1needs a call ondecision_key = "orders-page-size": lower/v2/ordersdefault page size from 100 to 50, or keep 100 while adding a hardlimit <= 200cap. Each option attaches a verbatim JSON responsediffexhibit. - Crash retry
-
Worker 1's container restarts overnight and re-asks the same
decision_keyunder a new generated ID. The hub folds it intoversion = 2of the existing open card, keeping its originalidandopened_atso Dana still sees one card. - Fallback
- Effort: 3 minutes. Recommendation: Keep default 100 with a 200 cap to preserve backward compatibility. Fallback: Keep default 100 at Friday's 5:00 p.m. release freeze.
What this pattern is NOT — Live chat back-and-forth or policy-settled rules
Negative example- Scenario
- Asking a quick clarifying question during an active live chat session with one agent, or asking a human to re-approve a choice already covered by a standing rule.
- Why skip it
- In a live turn-by-turn conversation, the human already holds full context — requiring effort estimates and fallback clauses adds needless friction. And if a stored record or Delegation Policy already decides the choice, nobody should be asked at all.
When to use and when to skip
Use Self-Contained Question when
- The answerer is away when the question is written and reads it cold later among other work.
- Questions can be escalated across agents, so the final answerer never saw the originating thread.
- Agents restart or lose context and risk asking the same missing decision multiple times.
- Decisions depend on how copy, layouts, visuals, diffs, or live behavior actually look.
Skip it when
- One person is pairing synchronously with one agent in a live conversation.
- A standing Delegation Policy or existing hub record already settles the question.
- You only need to control notification timing — pair with Question Inbox for check-in batching and interrupt rules.
Data model and hub invariants
Self-Contained Question defines the canonical questions
table used across the catalog. It references requests and
parties (from
Orchestrator-Workers),
jobs (from Durable Job),
and interrupt_rules (from
Question Inbox). The human's reply is stored separately
in answers (defined by
Tracked Answer).
Question belongs to one
Request, optionally blocks one
Job, names one current
answerer_id (and optional
asker_id when not hub-opened), and optionally cites the
InterruptRule that paged the requester.
Table: questions
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Stable question identifier preserved across revisions and escalations. |
| request_id | uuid | NOT NULL, FK | References requests(id). |
| job_id | uuid | NULLABLE, FK | References jobs(id); empty only for pre-split request-level questions. |
| kind | text | NOT NULL | CHECK (kind IN ('decision', 'fact', 'action', 'review', 'reassignment')); drives required parts. |
| asker_id | uuid | NULLABLE, FK | References parties(id); NULL when opened by the hub itself. |
| answerer_id | uuid | NOT NULL, FK | References parties(id); mutated in place when escalated. |
| text | text | NOT NULL | What is needed from the answerer in one clear sentence. |
| context | text | NOT NULL | Plain-English background referring to nothing outside this card. |
| options | jsonb | NOT NULL | Array of {id, label, outcome}; empty list allowed for non-choice kinds, >= 2 for decision/review. |
| recommended_option | text | NULLABLE | Must match an option.id whenever options is non-empty. |
| recommendation_reason | text | NULLABLE | One-sentence rationale for recommended_option; required whenever options exist. |
| needs_exhibit | boolean | NOT NULL | true when the decision depends on how an artifact looks, sounds, or behaves. |
| exhibits | jsonb | NOT NULL | Array of {kind, location, caption, option?} where kind is image | video | live_link | diff | text. |
| effort_minutes | integer | NOT NULL | Positive integer estimating how many minutes answering takes. |
| blocked_work | text | NOT NULL | Names what is blocked on this answer and what continues without it. |
| if_unanswered | text | NOT NULL | Safe default action taken if no answer arrives by answer_by. |
| answer_by | timestamptz | NULLABLE | Deadline when the hub expires the question and the fallback runs; NULL means wait indefinitely. |
| decision_key | text | NOT NULL | Asker-chosen slug (e.g., payment-email-wording) used to fold retries into revisions. |
| decision_class | text | NULLABLE | Policy action code (e.g., merge_pull_request) matched by Escalation Chain. |
| version | integer | NOT NULL | Starts at 1; increments by 1 on every revision. |
| interrupt_rule_id | uuid | NULLABLE, FK | References interrupt_rules(id) when the question interrupted between check-ins. |
| state | text | NOT NULL | CHECK (state IN ('open', 'answered', 'withdrawn', 'expired')). |
| opened_at | timestamptz | NOT NULL | First stored timestamp; preserved across revisions and escalations. |
| closed_at | timestamptz | NULLABLE | Set when state transitions to withdrawn or expired. |
| closed_reason | text | NULLABLE | One-sentence explanation required when withdrawn or expired. |
Seven hub invariants
-
01Every question names its request, same-request job, and one answerer Database constraint
request_idandanswerer_idareNOT NULLforeign keys, and a composite foreign key(request_id, job_id)referencesjobs(request_id, id)wheneverjob_idis present. -
02At most one open question per decision key Database constraint
A partial unique index on
(request_id, COALESCE(job_id, '00000000-0000-0000-0000-000000000000'::uuid), decision_key) WHERE state = 'open'structurally prevents duplicate open cards for the same missing decision. -
03Closing timestamp and reason match withdrawn or expired state Database constraint
A row-level
CHECK ((state IN ('withdrawn', 'expired')) = (closed_at IS NOT NULL AND closed_reason IS NOT NULL))ensures every closed-without-answer card records why and when it closed. -
04Completeness gate refuses drafts lacking required parts Hub guard
askvalidatescontext, positiveeffort_minutes,blocked_work,if_unanswered, at least two options fordecision/review(and never exactly one option), plus a validrecommended_optionandrecommendation_reasonwhenever options are present — refusing gaps withincomplete_questionand the exact missing part list. -
05Visual or behavioral choices require exhibits per option Hub guard
When
needs_exhibitistrue, every option must have an exhibit naming itsoptionid (or at least one exhibit when optionless); otherwiseexhibitsis reported in theincomplete_questionrefusal. -
06Retries revise in place, and answers bind to the exact version Hub guard
A complete ask matching an open
decision_keykeeps the originalid,answerer_id, andopened_atwhile bumpingversion. Submitting an answer against an older revision is rejected withstale_question_version. -
07Terminal states never reopen; expiry waits for answer_by Hub guard
Once a question leaves
open, further mutations fail withquestion_not_open. Only the hub may callexpire, and calling it beforeanswer_by(or whenanswer_byis empty) fails withdeadline_not_reached.
Reference implementation
The same hub completeness check, decision_key revision
upsert, version-checked answer guard, withdrawal, and deadline expiry in TypeScript,
Python, and Elixir.
-- Completeness check, decision_key revision upsert, and lifecycle guards
inductive QuestionKind where
| decision | fact | action | review | reassignment
deriving Repr, BEq
-- «open» escapes the keyword `open`; elsewhere it is written `.open`
inductive QuestionState where
| «open» | answered | withdrawn | expired
deriving Repr, BEq
inductive ExhibitKind where
| image | video | liveLink | diff | text
deriving Repr, BEq
structure QuestionOption where
id : String
label : String
outcome : String
deriving Repr
structure Exhibit where
kind : ExhibitKind
location : String
caption : String
option : Option String := none
deriving Repr
structure Question where
id : String
requestId : String
jobId : Option String := none
kind : QuestionKind
answererId : String
text : String
context : String := ""
options : List QuestionOption := []
recommendedOption : Option String := none
recommendationReason : Option String := none
needsExhibit : Bool := false
exhibits : List Exhibit := []
effortMinutes : Int := 0
blockedWork : String := ""
ifUnanswered : String := ""
answerBy : Option Nat := none
decisionKey : String
version : Nat := 1
state : QuestionState := .open
openedAt : Nat
closedAt : Option Nat := none
closedReason : Option String := none
deriving Repr
inductive HubError where
| incompleteQuestion (missing : List String)
| staleQuestionVersion | deadlineNotReached | unknownQuestion | questionNotOpen
deriving Repr, BEq
def blank (v : Option String) : Bool :=
match v with
| some s => s.trimAscii.isEmpty
| none => true
def missingParts (q : Question) : List String :=
let needsChoices := q.kind == .decision || q.kind == .review
let n := q.options.length
let validRec := q.options.any (some ·.id == q.recommendedOption) && !blank q.recommendationReason
let shown :=
if q.options.isEmpty then !q.exhibits.isEmpty
else q.options.all fun o => q.exhibits.any (·.option == some o.id)
-- Each part paired with "is it missing?"; keep the names of the missing ones
[ ("context", blank q.context),
("effort_minutes", decide (q.effortMinutes ≤ 0)),
("blocked_work", blank q.blockedWork),
("if_unanswered", blank q.ifUnanswered),
("options", (needsChoices && n < 2) || (!needsChoices && n == 1)),
("recommendation", !q.options.isEmpty && !validRec),
("exhibits", q.needsExhibit && !shown) ].filterMap fun (part, missing) =>
if missing then some part else none
structure QuestionStore where
items : List Question := []
deriving Repr
namespace QuestionStore
abbrev Result := Except HubError (Question × QuestionStore)
private def mustFindOpen (store : QuestionStore) (id : String) : Except HubError Question := do
let some q := store.items.find? (·.id == id) | throw .unknownQuestion
unless q.state == .open do throw .questionNotOpen
return q
-- Writes the changed question back over the stored one with the same id.
private def put (store : QuestionStore) (q : Question) : Question × QuestionStore :=
(q, { store with items := store.items.map fun item => if item.id == q.id then q else item })
def ask (store : QuestionStore) (draft : Question) : Result := do
let missing := missingParts draft
unless missing.isEmpty do throw (.incompleteQuestion missing)
let existing := store.items.find? fun q =>
q.state == .open && q.requestId == draft.requestId &&
q.jobId == draft.jobId && q.decisionKey == draft.decisionKey
match existing with
| none =>
let created := { draft with version := 1, state := .open }
return (created, { store with items := store.items ++ [created] })
| some existing =>
-- Fold repeat into a revision, preserving identity and original openedAt
return store.put { draft with id := existing.id, answererId := existing.answererId,
openedAt := existing.openedAt,
version := existing.version + 1, state := .open }
def checkAnswerVersion (store : QuestionStore) (id : String) (expectedVersion : Nat) :
Except HubError Question := do
let q ← store.mustFindOpen id
unless q.version == expectedVersion do throw .staleQuestionVersion
return q
def withdraw (store : QuestionStore) (id reason : String) (now : Nat) : Result := do
let q ← store.mustFindOpen id
return store.put { q with state := .withdrawn, closedAt := some now,
closedReason := some reason }
def expire (store : QuestionStore) (id : String) (now : Nat) : Result := do
let q ← store.mustFindOpen id
match q.answerBy with
| some deadline => if now < deadline then throw .deadlineNotReached
| none => throw .deadlineNotReached
let reason := s!"Deadline reached; applied fallback: {q.ifUnanswered}"
return store.put { q with state := .expired, closedAt := some now,
closedReason := some reason }
-- Checked by Lean: an incomplete draft is refused, naming exactly the missing parts.
theorem ask_incomplete (store : QuestionStore) (draft : Question)
(h : missingParts draft ≠ []) :
store.ask draft = .error (.incompleteQuestion (missingParts draft)) := by
simp [ask, h]
rfl
end QuestionStore
// Completeness check, decision_key revision upsert, and lifecycle guards
type QuestionKind = "decision" | "fact" | "action" | "review" | "reassignment";
type QuestionState = "open" | "answered" | "withdrawn" | "expired";
type ExhibitKind = "image" | "video" | "live_link" | "diff" | "text";
interface QuestionOption { id: string; label: string; outcome: string; }
interface Exhibit { kind: ExhibitKind; location: string; caption: string; option: string | null; }
interface Question {
id: string;
requestId: string;
jobId: string | null;
kind: QuestionKind;
answererId: string;
text: string;
context: string;
options: QuestionOption[];
recommendedOption: string | null;
recommendationReason: string | null;
needsExhibit: boolean;
exhibits: Exhibit[];
effortMinutes: number;
blockedWork: string;
ifUnanswered: string;
answerBy: number | null;
decisionKey: string;
version: number;
state: QuestionState;
openedAt: number;
closedAt: number | null;
closedReason: string | null;
}
type AskResult =
| { ok: true; question: Question }
| { ok: false; error: "incomplete_question"; missing: string[] };
const blank = (v: string | null | undefined) => !v || v.trim() === "";
function missingParts(q: Question): string[] {
const missing: string[] = [];
if (blank(q.context)) missing.push("context");
if (!Number.isInteger(q.effortMinutes) || q.effortMinutes <= 0) missing.push("effort_minutes");
if (blank(q.blockedWork)) missing.push("blocked_work");
if (blank(q.ifUnanswered)) missing.push("if_unanswered");
const needsChoices = q.kind === "decision" || q.kind === "review";
if ((needsChoices && q.options.length < 2) || (!needsChoices && q.options.length === 1)) {
missing.push("options");
}
if (q.options.length > 0) {
const validRec = q.options.some((o) => o.id === q.recommendedOption) && !blank(q.recommendationReason);
if (!validRec) missing.push("recommendation");
}
if (q.needsExhibit) {
const shown = q.options.length === 0
? q.exhibits.length > 0
: q.options.every((o) => q.exhibits.some((e) => e.option === o.id));
if (!shown) missing.push("exhibits");
}
return missing;
}
class QuestionStore {
private items: Question[] = [];
ask(draft: Question): AskResult {
const missing = missingParts(draft);
if (missing.length > 0) return { ok: false, error: "incomplete_question", missing };
const existing = this.items.find(
(q) => q.state === "open" && q.requestId === draft.requestId &&
q.jobId === draft.jobId && q.decisionKey === draft.decisionKey
);
if (!existing) {
const created = { ...draft, version: 1, state: "open" as const };
this.items.push(created);
return { ok: true, question: created };
}
// Fold repeat into a revision, preserving identity and original openedAt
const revised: Question = {
...draft, id: existing.id, answererId: existing.answererId,
openedAt: existing.openedAt, version: existing.version + 1, state: "open"
};
this.items = this.items.map((q) => (q.id === existing.id ? revised : q));
return { ok: true, question: revised };
}
checkAnswerVersion(id: string, expectedVersion: number): Question {
const q = this.mustFindOpen(id);
if (q.version !== expectedVersion) throw new Error("stale_question_version");
return q;
}
withdraw(id: string, reason: string, now: number): Question {
const q = this.mustFindOpen(id);
q.state = "withdrawn";
q.closedAt = now;
q.closedReason = reason;
return q;
}
expire(id: string, now: number): Question {
const q = this.mustFindOpen(id);
if (q.answerBy === null || now < q.answerBy) throw new Error("deadline_not_reached");
q.state = "expired";
q.closedAt = now;
q.closedReason = `Deadline reached; applied fallback: ${q.ifUnanswered}`;
return q;
}
private mustFindOpen(id: string): Question {
const q = this.items.find((item) => item.id === id);
if (!q) throw new Error("unknown_question");
if (q.state !== "open") throw new Error("question_not_open");
return q;
}
}
# Completeness check, decision_key revision upsert, and lifecycle guards
from dataclasses import dataclass, field, replace
from typing import Literal, Optional
@dataclass
class QuestionOption:
id: str
label: str
outcome: str
@dataclass
class Exhibit:
kind: Literal["image", "video", "live_link", "diff", "text"]
location: str
caption: str
option: Optional[str] = None
@dataclass
class Question:
id: str
request_id: str
kind: Literal["decision", "fact", "action", "review", "reassignment"]
answerer_id: str
text: str
decision_key: str
opened_at: int
job_id: Optional[str] = None
context: str = ""
options: list[QuestionOption] = field(default_factory=list)
recommended_option: Optional[str] = None
recommendation_reason: Optional[str] = None
needs_exhibit: bool = False
exhibits: list[Exhibit] = field(default_factory=list)
effort_minutes: int = 0
blocked_work: str = ""
if_unanswered: str = ""
answer_by: Optional[int] = None
version: int = 1
state: Literal["open", "answered", "withdrawn", "expired"] = "open"
closed_at: Optional[int] = None
closed_reason: Optional[str] = None
class HubError(Exception):
pass
def missing_parts(q: Question) -> list[str]:
missing: list[str] = []
if not q.context.strip():
missing.append("context")
if not isinstance(q.effort_minutes, int) or q.effort_minutes <= 0:
missing.append("effort_minutes")
if not q.blocked_work.strip():
missing.append("blocked_work")
if not q.if_unanswered.strip():
missing.append("if_unanswered")
needs_choices = q.kind in ("decision", "review")
if (needs_choices and len(q.options) < 2) or (not needs_choices and len(q.options) == 1):
missing.append("options")
if q.options:
valid_rec = any(o.id == q.recommended_option for o in q.options) and bool(
(q.recommendation_reason or "").strip()
)
if not valid_rec:
missing.append("recommendation")
if q.needs_exhibit:
shown = (
len(q.exhibits) > 0
if not q.options
else all(any(e.option == o.id for e in q.exhibits) for o in q.options)
)
if not shown:
missing.append("exhibits")
return missing
class QuestionStore:
def __init__(self) -> None:
self.items: list[Question] = []
def ask(self, draft: Question) -> tuple[str, object]:
missing = missing_parts(draft)
if missing:
return ("incomplete_question", missing)
existing = next(
(
q for q in self.items
if q.state == "open" and q.request_id == draft.request_id
and q.job_id == draft.job_id and q.decision_key == draft.decision_key
),
None,
)
if existing is None:
created = replace(draft, version=1, state="open")
self.items.append(created)
return ("ok", created)
revised = replace(
draft, id=existing.id, answerer_id=existing.answerer_id,
opened_at=existing.opened_at, version=existing.version + 1, state="open"
)
self.items = [revised if q.id == existing.id else q for q in self.items]
return ("ok", revised)
def check_answer_version(self, q_id: str, expected_version: int) -> Question:
q = self._must_find_open(q_id)
if q.version != expected_version:
raise HubError("stale_question_version")
return q
def withdraw(self, q_id: str, reason: str, now: int) -> Question:
q = self._must_find_open(q_id)
q.state, q.closed_at, q.closed_reason = "withdrawn", now, reason
return q
def expire(self, q_id: str, now: int) -> Question:
q = self._must_find_open(q_id)
if q.answer_by is None or now < q.answer_by:
raise HubError("deadline_not_reached")
q.state, q.closed_at = "expired", now
q.closed_reason = f"Deadline reached; applied fallback: {q.if_unanswered}"
return q
def _must_find_open(self, q_id: str) -> Question:
q = next((item for item in self.items if item.id == q_id), None)
if q is None:
raise HubError("unknown_question")
if q.state != "open":
raise HubError("question_not_open")
return q
# Completeness check, decision_key revision upsert, and lifecycle guards
defmodule Questions do
def missing_parts(q) do
[
context: blank?(q.context),
effort_minutes: not (is_integer(q.effort_minutes) and q.effort_minutes > 0),
blocked_work: blank?(q.blocked_work),
if_unanswered: blank?(q.if_unanswered),
options: too_few_options?(q),
recommendation: q.options != [] and not recommended?(q),
exhibits: q.needs_exhibit and not shown?(q)
]
|> Enum.filter(fn {_part, missing?} -> missing? end)
|> Keyword.keys()
end
def ask(questions, new) do
case {missing_parts(new), Enum.find(questions, &same_decision?(&1, new))} do
{[], nil} -> {:ok, [%{new | version: 1, state: :open} | questions]}
{[], open} -> {:ok, replace(questions, revise(open, new))}
{parts, _} -> {:error, {:incomplete_question, parts}}
end
end
def check_answer_version(questions, id, expected_version) do
with {:ok, q} <- fetch_open(questions, id),
true <- q.version == expected_version || {:error, :stale_question_version} do
{:ok, q}
end
end
def withdraw(questions, id, reason, now) do
with {:ok, q} <- fetch_open(questions, id) do
closed = %{q | state: :withdrawn, closed_at: now, closed_reason: reason}
{:ok, replace(questions, closed)}
end
end
def expire(questions, id, now) do
with {:ok, q} <- fetch_open(questions, id),
true <- (q.answer_by != nil and now >= q.answer_by) || {:error, :deadline_not_reached} do
closed = %{
q
| state: :expired,
closed_at: now,
closed_reason: "Deadline reached; applied fallback: " <> q.if_unanswered
}
{:ok, replace(questions, closed)}
end
end
defp too_few_options?(%{kind: k, options: opts}) when k in [:decision, :review], do: length(opts) < 2
defp too_few_options?(%{options: opts}), do: length(opts) == 1
defp recommended?(q) do
Enum.any?(q.options, &(&1.id == q.recommended_option)) and not blank?(q.recommendation_reason)
end
defp shown?(%{options: [], exhibits: ex}), do: ex != []
defp shown?(q), do: Enum.all?(q.options, fn o -> Enum.any?(q.exhibits, &(&1.option == o.id)) end)
defp same_decision?(q, new) do
q.state == :open and q.request_id == new.request_id and
q.job_id == new.job_id and q.decision_key == new.decision_key
end
defp revise(open, new) do
%{new | id: open.id, answerer_id: open.answerer_id, opened_at: open.opened_at,
version: open.version + 1, state: :open}
end
defp fetch_open(questions, id) do
case Enum.find(questions, &(&1.id == id)) do
nil -> {:error, :unknown_question}
%{state: :open} = q -> {:ok, q}
_closed -> {:error, :question_not_open}
end
end
defp blank?(v), do: not is_binary(v) or String.trim(v) == ""
defp replace(list, item), do: Enum.map(list, &if(&1.id == item.id, do: item, else: &1))
end
Refusal, crash-retry deduplication, and withdrawal trace
Walking Example 1 (payment-failed email) through the failure path shows
how the hub blocks a vague draft with incomplete_question,
folds a worker crash retry into version = 2, guards
against stale_question_version, and withdraws the card
cleanly when scope changes:
1. Worker 1 submits vague ask (only text filled in; needsExhibit=true)
store.ask(q_vague)
-> refused: incomplete_question [context, effort_minutes, blocked_work, if_unanswered, options, exhibits]
2. Worker 1 fills all parts & attaches rendered current + new email exhibits:
store.ask(q_email_v1) // id="q_email_1", decisionKey="payment-email-wording"
-> ok (stored: id="q_email_1", version=1, state="open")
3. Worker 1 crashes, restarts, and asks same decisionKey under new id "q_email_retry":
store.ask({ ...q_email_v1, id: "q_email_retry", text: "Which failed-payment email?" })
-> ok (revised in place: id="q_email_1", version=2, same openedAt — still 1 card!)
4. Stale client tries to submit an answer targeting version 1:
store.checkAnswerVersion("q_email_1", expectedVersion: 1)
-> error: stale_question_version (client refreshes to show version 2 first)
5. Scope changes elsewhere (email dropped); Lead withdraws before check-in:
store.withdraw("q_email_1", reason: "Email replaced by in-app notice", now: Tue 08:15)
-> ok (state="withdrawn", closedReason recorded; card leaves inbox before 09:00)
Tradeoffs and practical guidance
Shifting effort from the returning human back onto the asking agent makes check-ins calm and sharp, with three real tradeoffs to keep in view:
- Asking costs the agent more upfront: rendering exhibits, writing per-option outcomes, and committing to a recommendation takes extra tokens and time — which is often a feature (agents realize they don't need to ask) but pure drag for trivial live clarifications.
-
Structural completeness is not semantic truth: the hub can verify that
contextandrecommendation_reasonare non-empty, yet an agent can still omit a subtle edge case or anchor the human toward a flawed recommendation. - Exhibit storage lifecycle matters: exhibits must be copied into durable hub storage rather than linking into an ephemeral worker sandbox that disappears before the human opens the card.
Practical implementation notes
-
Keep required parts minimal and vary them by
kind: adecisionorreviewneeds >= 2 options and a recommendation, whereas a simplefactor sign-inactionneeds neither. Unnecessary required fields train agents to emit boilerplate that humans learn to ignore. -
Let the asker pick
decision_key: free-text fuzzy matching misses restarts because agents rarely word a question identically twice; a short slug likepayment-email-wordingcatches repeats deterministically. -
Require conservative fallbacks: whatever
if_unansweredsays will happen without human approval, so default to the option that changes the least (for example, keeping the current email). - Tie withdrawal to lifecycle events: hook job cancellation, request scope edits, and PR merges to auto-withdraw obsolete open questions so dead asks vanish before check-in.
Known uses and related patterns
- Camunda BPMN User Tasks: models human steps as durable records with structured forms, due dates, and explicit assignment — pre-authored by a process designer in BPMN, whereas here an agent authors the card dynamically when hitting an unknown.
-
Anthropic Claude Agent SDK (
AskUserQuestion): structures agent asks with finite options and optional visual previews, though it targets in-session interaction without mandatory fallback clauses ordecision_keyrevision folding. -
Model Context Protocol (MCP) Elicitation & LangGraph
interrupt: provide structured JSON-schema user input requests and paused execution payloads; this pattern adds the hub-enforced recommendation, exhibits, effort estimate, and safe fallback needed for asynchronous review. -
Hohpe & Woolf's Request-Reply, Correlation Identifier, and Message Expiration:
classic messaging patterns supply the reply linkage and
answer_bydeadline; Self-Contained Question specifies what the payload must contain when the receiver is a human arriving cold. - Volgenic: structures every owner ask as a versioned record with context, concrete options, outcomes, one reasoned recommendation, and visual exhibits before surfacing it in the Needs Attention queue.
Related patterns
- Question Inbox — decides when and where questions notify the requester; Self-Contained Question decides what each question must contain.
- Tracked Answer — starts where this pattern ends, storing the
Answerrecord tied toquestion_versionand verifying that work applies it. - Escalation Chain — routes the question using
decision_class; because the card is self-contained, escalating it never loses context. - Delegation Policy — eliminates recurring questions by turning repeated answers into standing rules.
- Derived Status Board — displays open
Questionrecords directly on each blocked request line. - Orchestrator-Workers & Durable Job — define the
Request,Party, andJobrecords that every question links to.