Request Spec
When you hand a request to a team of AI agents, the conversation where you explained why you wanted it rarely reaches the workers that actually do the work. Worse, if your priorities change while jobs are already running, isolated workers keep building against yesterday's goal without ever knowing the target moved.
Request Spec gives every request one short, versioned record of what is wanted, why it matters, how anyone can tell it is done, and which open questions must be settled first. Every job pins the exact spec version it works from, so the hub can block premature guesses and catch stale work automatically whenever meaning changes.
Request spec
Why passing a chat message isn't enough
Across engineering, research, legal review, and operations, most agents join a request after the requester stated it. If a lead agent only copies a one-line task title into a job, the requester's underlying reason disappears. A worker faithfully executes the literal title — and misses the real problem completely.
Two second-order failures follow quickly. First, when an important fact is still unknown, eager workers guess instead of investigating, wasting an entire run on the wrong premise. Second, when the requester clarifies or narrows the goal mid-flight, a running worker has no structural way to know its work is now outdated — so an obsolete result slips cleanly through close-out.
Request Spec solves both problems with three rules enforced in hub code rather than left to memory or prompt reminders:
- One immutable versioned record holds meaning, never progress. Each revision stores the outcome, the reason, observable acceptance criteria, open points, and which parts were proposed by the lead versus confirmed by the requester. Ticking off finished steps lives outside the spec so a new version number always means intent changed.
- Blocking open points must be settled before main work starts. While a spec has a blocking open point, the hub refuses to assign ordinary execution jobs — only the time-boxed investigation (a spike) linked to that open point may run.
-
Every job pins a spec version, and the hub checks it at close-out. A
worker reports which version it built against; if a newer version has been published in
the meantime, the hub rejects completion with
job_spec_staleuntil the lead reconciles and updates the job.
Why mark lead-written parts as proposed instead of pausing for approval? Because asking the requester to approve every obvious criterion upfront wastes the exact human attention asynchronous agents are meant to save. Marking proposals lets low-risk work proceed while giving the requester a crisp checklist to confirm or correct at her next check-in — reserving hard stops only for blocking open points where guessing wrong would be expensive.
Architecture and participants
The Hub stores every version of a request's spec as an
immutable row and derives the current version as the highest version
number for that request. Every Job holds a required
request_spec_id foreign key so workers and checkers always
read the exact version the job was scoped against.
Request spec versions numbered from
1, blocks non-spike assignment while blocking open points remain, and refuses job
completion when a job's pinned version is behind current.
proposed_parts,
records open points with spike budgets or questions, and repins jobs when meaning shifts.
request_spec_id and report that
version ID when finishing.
Execution flow
Toggle between the normal path — where a short spike resolves a blocking unknown before the main job starts — and the mid-flight change path — where the requester revises the goal while a worker is building and the hub blocks the stale completion report.
Version 1 captures the requester's outcome and reason plus one blocking open point. The hub allows only the time-boxed spike to run; once findings arrive, version 2 closes the open point and unlocks the main job, which finishes cleanly while version 2 is still current.
Same steps 1–8 as normal flow; begins while the execution worker is running against spec v2.
When the requester adds a constraint mid-flight, the lead publishes version 3. The
worker finishes unaware against version 2, so the hub rejects close-out with
job_spec_stale, alerts the lead to repin the job to
version 3, and only accepts completion once the worker adapts to version 3.
Concrete examples
Request Spec applies anywhere work is handed across sessions and judged against a moving goal — whether the deliverable is a legal memo, an operations runbook, or production code.
Example 1 — Vendor data-residency audit brief
No code or unit tests- Request
- "Summarize our top three cloud vendors' EU data-residency guarantees so legal counsel can clear our Q3 European launch."
- Spec v1 & spike
- The lead records the outcome, the EU launch reason, two proposed criteria, and one blocking open point: "Do any of the three vendors replicate backup snapshots or support logs outside the EU?" (20-minute spike). Worker 1 discovers Vendor B copies error logs to US-East.
- Spec v2 & v3 shift
-
The lead publishes v2 adding a criterion covering backups and logs,
then assigns the full brief to Worker 2. Mid-afternoon, counsel asks to include UK
GDPR adequacy as well (v3). When Worker 2 reports finished from v2,
the hub rejects closure (
job_spec_stale), repins the job to v3, and delivers one audit brief covering both EU and UK requirements.
Example 2 — Customer bulk-import concurrency cap
Everyday engineering- Request
- "Cap imports at five at a time so one customer's bulk upload cannot starve everyone else."
- Spec v1 & spike
- Without a spec, a worker only caps the web upload screen and misses bulk uploads entirely. With Request Spec, v1 records the starvation reason and one blocking open point: "Which code paths start an import?" (30-minute spike). Worker 1 reports that bulk uploads enter via a separate background queue.
- Spec v2 & v3 shift
-
The lead writes v2 with criterion 3 ("The limit covers both the
upload screen and the background queue") and assigns Worker 2 against v2.
Mid-build, the requester adds: "Make it two at a time on the free plan"
(v3). Worker 2 finishes from v2, hits
job_spec_stale, receives the v3 diff, adds the free-plan cap, and closes cleanly against v3.
What this pattern is NOT — Quick single-session edit
Negative example- Request
- Fix a typo on a landing page or adjust a chart's axis formatting while chatting live with one agent.
- Why skip it
- One person and one agent in a single thread already share full conversational context, and undoing a misreading takes seconds. Authoring and versioning a formal spec here costs more than any mistake it prevents.
When to use and when to skip
Use Request Spec when
- Workers or checkers start after the requester stated the goal and never heard her underlying reason.
- Someone other than the worker judges completion and needs explicit, observable criteria to check against.
- Requirements may shift while jobs are in flight and stale output must not silently close the request.
- A wrong assumption would be costly to uncover late, making a cheap upfront spike worthwhile.
Skip it when
- One human collaborates directly with one agent inside a single live conversation that already holds the context.
- The task is cheap and trivial to redo — let the agent act on its reading and show that reading alongside the result.
- You are tempted to dump implementation plans or progress checkboxes into the spec (keep those on jobs).
Data model and hub invariants
Request Spec defines one table — request_specs — linked to
requests and parties
(defined by Orchestrator-Workers) and
referenced by every row in jobs (defined by
Durable Job) through
request_spec_id. One row equals one version.
Request has one or more immutable
RequestSpec rows numbered from 1. Every
Job pins exactly one spec version via
request_spec_id.
Table: request_specs
| Column | Postgres type | Nullability | Notes |
|---|---|---|---|
| id | uuid | NOT NULL, PK | Unique identifier for this specific version. |
| request_id | uuid | NOT NULL, FK | References requests(id). |
| version | integer | NOT NULL | Starts at 1 per request, increments without gaps; highest number is current. |
| outcome | text | NOT NULL | One or two sentences stating what must be true when finished. |
| reason | text | NOT NULL | Why the requester wants the outcome; disambiguates edge cases. |
| acceptance_criteria | jsonb | NOT NULL | Array of {number, text} conditions; numbers never reuse. |
| open_points | jsonb | NOT NULL | Array of unsettled questions (see structured fields below); empty when all settled. |
| proposed_parts | jsonb | NOT NULL | Names of unconfirmed lead proposals: outcome, reason, or criterion:<n>. |
| confirmed_parts | jsonb | NOT NULL | Array of {part, confirmed_at} moved here as the requester confirms proposals. |
| required_claims | jsonb | NOT NULL | Claim kinds required for completion (e.g. reported_finished, checked). |
| author_id | uuid | NOT NULL, FK | References parties(id); must be the request's requester or lead. |
| created_at | timestamptz | NOT NULL | Timestamp when this version was published. |
Structured entry shape: open_points
| Field | Type | Nullability | Notes |
|---|---|---|---|
| key | text | NOT NULL | Stable slug across versions (e.g. import-paths). |
| text | text | NOT NULL | The unresolved point phrased as a concrete question. |
| blocking | boolean | NOT NULL | When true, only a spike linked to an open point may be assigned. |
| settle_with | text | NOT NULL | question (ask requester) or spike (time-boxed worker probe). |
| budget_minutes | integer | NULLABLE | Required positive limit when settle_with = 'spike'; null for questions. |
| question_id | uuid | NULLABLE | Linked Question ID once sent; null beforehand. |
| job_id | uuid | NULLABLE | Linked spike Job ID once created; null beforehand. |
| linked_at | timestamptz | NULLABLE | Timestamp when question_id or job_id was recorded. |
Seven hub invariants
-
01Every request starts at version 1 with gap-free numbering Database constraint
Version 1 is written in the same transaction that creates the request.
UNIQUE (request_id, version)andCHECK (version >= 1)guarantee clean monotonic numbering. -
02Current version is always derived as the highest version number Database constraint
No mutable
current_spec_idcolumn exists onrequests, so every pattern computes the current spec consistently viaMAX(version)without pointer drift. -
03Spec wording never mutates after publication Hub guard
Outcome, reason, and criteria are append-only across versions. Only two timestamped metadata writes occur in place: moving a part from
proposed_partsintoconfirmed_parts, and linking an open point'squestion_idor spikejob_id. -
04Only the requester or lead agent may publish a version Hub guard
revise_specrejects any other party withonly_requester_or_lead_may_revise. Anything the lead adds without requester words goes intoproposed_parts. -
05Criteria or an open point must exist, and spikes require a budget Hub guard
Publishing a version with neither criteria nor open points fails with
criteria_or_open_point_required; any open point withsettle_with = 'spike'and no positivebudget_minutesfails withspike_budget_required. -
06Blocking open points restrict assignment to linked spikes Hub guard
Every job pins one spec of its own request. While the current spec contains a blocking open point,
assign_jobrejects any job not named by an open point'sjob_idwithblocking_open_point. -
07Jobs close only against the current spec version Hub guard
finish_jobrejects withreport_names_wrong_versionif the worker reports a different spec ID than its job pins, and withjob_spec_staleif a higher spec version now exists.
Reference implementation
The same minimal spec versioning and gating logic in Lean, TypeScript, Python, and Elixir. Every invariant lives in deterministic hub functions rather than worker prompt reminders.
-- Hub guards for Request Spec (immutable versions + spike & staleness gates)
import Std.Data.HashMap
open Std (HashMap)
structure Criterion where
number : Nat
text : String
deriving Repr
inductive SettleWith where
| question | spike
deriving Repr, BEq
structure OpenPoint where
key : String
text : String
blocking : Bool
settleWith : SettleWith
budgetMinutes : Option Nat := none
jobId : Option String := none
deriving Repr
structure ConfirmedPart where
part : String
confirmedAt : String
deriving Repr
structure RequestSpec where
id : String
requestId : String
version : Nat
outcome : String
reason : String
acceptanceCriteria : List Criterion := []
openPoints : List OpenPoint := []
proposedParts : List String := []
confirmedParts : List ConfirmedPart := []
authorId : String
deriving Repr
-- The fields a revision may change; `none` keeps the previous version's value.
structure SpecChanges where
outcome : Option String := none
reason : Option String := none
acceptanceCriteria : Option (List Criterion) := none
openPoints : Option (List OpenPoint) := none
proposedParts : Option (List String) := none
structure Request where
id : String
requesterId : String
leadId : String
deriving Repr
inductive JobStatus where
| «open» | done -- «» lets a keyword like `open` be used as a name
deriving Repr, BEq
structure Job where
id : String
requestId : String
requestSpecId : String
status : JobStatus := .open
deriving Repr
inductive HubError where
| invalidInitialSpec | unknownRequest | onlyRequesterOrLeadMayRevise
| jobSpecStale | blockingOpenPoint | unknownJob | onlyLeadMayRepin
| reportNamesWrongVersion | criteriaOrOpenPointRequired | spikeBudgetRequired
deriving Repr, BEq
-- The hub is plain data; every guard returns a new hub or an error.
structure SpecHub where
requests : HashMap String Request := {}
specs : HashMap String RequestSpec := {}
jobs : HashMap String Job := {}
namespace SpecHub
def validateSpec (spec : RequestSpec) : Except HubError Unit := do
if spec.acceptanceCriteria.isEmpty && spec.openPoints.isEmpty then
throw .criteriaOrOpenPointRequired
-- `Option.any`: false when there is no budget, else whether it is above zero.
for p in spec.openPoints do
if p.settleWith == .spike && !p.budgetMinutes.any (· > 0) then
throw .spikeBudgetRequired
def createRequestWithV1 (hub : SpecHub) (req : Request) (specV1 : RequestSpec) :
Except HubError (RequestSpec × SpecHub) := do
unless specV1.requestId == req.id && specV1.version == 1 do throw .invalidInitialSpec
validateSpec specV1
pure (specV1, { hub with requests := hub.requests.insert req.id req,
specs := hub.specs.insert specV1.id specV1 })
def currentSpec (hub : SpecHub) (requestId : String) : Except HubError RequestSpec :=
-- `(·.requestId == requestId)` is shorthand for `fun s => s.requestId == requestId`.
match hub.specs.values.filter (·.requestId == requestId) with
| [] => throw .unknownRequest
| s :: rest => pure (rest.foldl (fun a b => if b.version > a.version then b else a) s)
def reviseSpec (hub : SpecHub) (requestId actorId specId : String) (changes : SpecChanges) :
Except HubError (RequestSpec × SpecHub) := do
let some req := hub.requests.get? requestId | throw .unknownRequest
unless actorId == req.requesterId || actorId == req.leadId do
throw .onlyRequesterOrLeadMayRevise
let prev ← hub.currentSpec requestId
-- A revision is a new record; earlier versions are never edited.
let next := { prev with
id := specId, version := prev.version + 1, authorId := actorId, confirmedParts := []
outcome := changes.outcome.getD prev.outcome
reason := changes.reason.getD prev.reason
acceptanceCriteria := changes.acceptanceCriteria.getD prev.acceptanceCriteria
openPoints := changes.openPoints.getD prev.openPoints
proposedParts := changes.proposedParts.getD prev.proposedParts }
validateSpec next
pure (next, { hub with specs := hub.specs.insert specId next })
def assignJob (hub : SpecHub) (jobId requestId specId : String) :
Except HubError (Job × SpecHub) := do
let current ← hub.currentSpec requestId
unless current.id == specId do throw .jobSpecStale
let blocking := current.openPoints.filter (·.blocking)
unless blocking.isEmpty || blocking.any (·.jobId == some jobId) do
throw .blockingOpenPoint
let job : Job := { id := jobId, requestId, requestSpecId := specId }
pure (job, { hub with jobs := hub.jobs.insert jobId job })
def repinJob (hub : SpecHub) (jobId actorId specId : String) :
Except HubError (Job × SpecHub) := do
let some job := hub.jobs.get? jobId | throw .unknownJob
let some req := hub.requests.get? job.requestId | throw .onlyLeadMayRepin
unless req.leadId == actorId do throw .onlyLeadMayRepin
let current ← hub.currentSpec job.requestId
unless current.id == specId do throw .jobSpecStale
let job := { job with requestSpecId := specId }
pure (job, { hub with jobs := hub.jobs.insert jobId job })
def finishJob (hub : SpecHub) (jobId reportedSpecId : String) :
Except HubError (Job × SpecHub) := do
let some job := hub.jobs.get? jobId | throw .unknownJob
unless reportedSpecId == job.requestSpecId do throw .reportNamesWrongVersion
let current ← hub.currentSpec job.requestId
unless job.requestSpecId == current.id do throw .jobSpecStale
let job := { job with status := .done }
pure (job, { hub with jobs := hub.jobs.insert jobId job })
end SpecHub
-- Invariant: a spec with neither acceptance criteria nor open points is always rejected.
theorem empty_spec_rejected (spec : RequestSpec) :
SpecHub.validateSpec { spec with acceptanceCriteria := [], openPoints := [] }
= throw .criteriaOrOpenPointRequired := by
simp [SpecHub.validateSpec]
// Hub guards for Request Spec (immutable versions + spike & staleness gates)
interface Criterion { number: number; text: string; }
interface OpenPoint {
key: string;
text: string;
blocking: boolean;
settleWith: "question" | "spike";
budgetMinutes: number | null;
jobId: string | null;
}
interface RequestSpec {
id: string;
requestId: string;
version: number;
outcome: string;
reason: string;
acceptanceCriteria: Criterion[];
openPoints: OpenPoint[];
proposedParts: string[];
confirmedParts: Array<{ part: string; confirmedAt: string }>;
authorId: string;
}
interface Request { id: string; requesterId: string; leadId: string; }
interface Job { id: string; requestId: string; requestSpecId: string; status: "open" | "done"; }
class SpecHub {
private requests = new Map<string, Request>();
private specs = new Map<string, RequestSpec>();
private jobs = new Map<string, Job>();
createRequestWithV1(req: Request, specV1: RequestSpec): RequestSpec {
if (specV1.requestId !== req.id || specV1.version !== 1) {
throw new Error("invalid_initial_spec");
}
this.validateSpec(specV1);
this.requests.set(req.id, req);
this.specs.set(specV1.id, specV1);
return specV1;
}
currentSpec(requestId: string): RequestSpec {
const list = [...this.specs.values()].filter((s) => s.requestId === requestId);
if (list.length === 0) throw new Error("unknown_request");
return list.reduce((a, b) => (b.version > a.version ? b : a));
}
reviseSpec(
requestId: string,
actorId: string,
specId: string,
changes: Partial<Pick<RequestSpec, "outcome" | "reason" | "acceptanceCriteria" | "openPoints" | "proposedParts">>
): RequestSpec {
const req = this.requests.get(requestId);
if (!req) throw new Error("unknown_request");
if (actorId !== req.requesterId && actorId !== req.leadId) {
throw new Error("only_requester_or_lead_may_revise");
}
const prev = this.currentSpec(requestId);
const next: RequestSpec = {
...prev,
...changes,
id: specId,
version: prev.version + 1,
authorId: actorId,
confirmedParts: []
};
this.validateSpec(next);
this.specs.set(specId, next);
return next;
}
assignJob(jobId: string, requestId: string, specId: string): Job {
const current = this.currentSpec(requestId);
if (current.id !== specId) throw new Error("job_spec_stale");
const blocking = current.openPoints.filter((p) => p.blocking);
if (blocking.length > 0 && !blocking.some((p) => p.jobId === jobId)) {
throw new Error("blocking_open_point");
}
const job: Job = { id: jobId, requestId, requestSpecId: specId, status: "open" };
this.jobs.set(jobId, job);
return job;
}
repinJob(jobId: string, actorId: string, specId: string): Job {
const job = this.jobs.get(jobId);
if (!job) throw new Error("unknown_job");
const req = this.requests.get(job.requestId);
if (!req || req.leadId !== actorId) throw new Error("only_lead_may_repin");
const current = this.currentSpec(job.requestId);
if (current.id !== specId) throw new Error("job_spec_stale");
job.requestSpecId = specId;
return job;
}
finishJob(jobId: string, reportedSpecId: string): Job {
const job = this.jobs.get(jobId);
if (!job) throw new Error("unknown_job");
if (reportedSpecId !== job.requestSpecId) {
throw new Error("report_names_wrong_version");
}
const current = this.currentSpec(job.requestId);
if (job.requestSpecId !== current.id) {
throw new Error("job_spec_stale");
}
job.status = "done";
return job;
}
private validateSpec(spec: RequestSpec): void {
if (spec.acceptanceCriteria.length === 0 && spec.openPoints.length === 0) {
throw new Error("criteria_or_open_point_required");
}
for (const p of spec.openPoints) {
if (p.settleWith === "spike" && (!p.budgetMinutes || p.budgetMinutes <= 0)) {
throw new Error("spike_budget_required");
}
}
}
}
# Hub guards for Request Spec (immutable versions + spike & staleness gates)
from dataclasses import dataclass, field
from typing import Literal, Optional
@dataclass(frozen=True)
class Criterion:
number: int
text: str
@dataclass
class OpenPoint:
key: str
text: str
blocking: bool
settle_with: Literal["question", "spike"]
budget_minutes: Optional[int] = None
job_id: Optional[str] = None
@dataclass
class RequestSpec:
id: str
request_id: str
version: int
outcome: str
reason: str
author_id: str
acceptance_criteria: list[Criterion] = field(default_factory=list)
open_points: list[OpenPoint] = field(default_factory=list)
proposed_parts: list[str] = field(default_factory=list)
confirmed_parts: list[tuple[str, str]] = field(default_factory=list)
@dataclass
class Request:
id: str
requester_id: str
lead_id: str
@dataclass
class Job:
id: str
request_id: str
request_spec_id: str
status: Literal["open", "done"] = "open"
class HubError(Exception):
pass
class SpecHub:
def __init__(self) -> None:
self.requests: dict[str, Request] = {}
self.specs: dict[str, RequestSpec] = {}
self.jobs: dict[str, Job] = {}
def create_request_with_v1(self, req: Request, spec_v1: RequestSpec) -> RequestSpec:
if spec_v1.request_id != req.id or spec_v1.version != 1:
raise HubError("invalid_initial_spec")
self._validate(spec_v1)
self.requests[req.id] = req
self.specs[spec_v1.id] = spec_v1
return spec_v1
def current_spec(self, request_id: str) -> RequestSpec:
matches = [s for s in self.specs.values() if s.request_id == request_id]
if not matches:
raise HubError("unknown_request")
return max(matches, key=lambda s: s.version)
def revise_spec(
self, request_id: str, actor_id: str, spec_id: str, **changes
) -> RequestSpec:
req = self.requests.get(request_id)
if req is None:
raise HubError("unknown_request")
if actor_id not in (req.requester_id, req.lead_id):
raise HubError("only_requester_or_lead_may_revise")
prev = self.current_spec(request_id)
nxt = RequestSpec(
id=spec_id,
request_id=request_id,
version=prev.version + 1,
outcome=changes.get("outcome", prev.outcome),
reason=changes.get("reason", prev.reason),
author_id=actor_id,
acceptance_criteria=changes.get("acceptance_criteria", prev.acceptance_criteria),
open_points=changes.get("open_points", prev.open_points),
proposed_parts=changes.get("proposed_parts", prev.proposed_parts),
)
self._validate(nxt)
self.specs[spec_id] = nxt
return nxt
def assign_job(self, job_id: str, request_id: str, spec_id: str) -> Job:
current = self.current_spec(request_id)
if current.id != spec_id:
raise HubError("job_spec_stale")
blocking = [p for p in current.open_points if p.blocking]
if blocking and not any(p.job_id == job_id for p in blocking):
raise HubError("blocking_open_point")
job = Job(id=job_id, request_id=request_id, request_spec_id=spec_id)
self.jobs[job_id] = job
return job
def repin_job(self, job_id: str, actor_id: str, spec_id: str) -> Job:
job = self.jobs.get(job_id)
if job is None:
raise HubError("unknown_job")
req = self.requests.get(job.request_id)
if req is None or req.lead_id != actor_id:
raise HubError("only_lead_may_repin")
if self.current_spec(job.request_id).id != spec_id:
raise HubError("job_spec_stale")
job.request_spec_id = spec_id
return job
def finish_job(self, job_id: str, reported_spec_id: str) -> Job:
job = self.jobs.get(job_id)
if job is None:
raise HubError("unknown_job")
if reported_spec_id != job.request_spec_id:
raise HubError("report_names_wrong_version")
if job.request_spec_id != self.current_spec(job.request_id).id:
raise HubError("job_spec_stale")
job.status = "done"
return job
def _validate(self, spec: RequestSpec) -> None:
if not spec.acceptance_criteria and not spec.open_points:
raise HubError("criteria_or_open_point_required")
for p in spec.open_points:
if p.settle_with == "spike" and not (p.budget_minutes and p.budget_minutes > 0):
raise HubError("spike_budget_required")
# Hub guards for Request Spec (pure functional core)
defmodule SpecHub do
defstruct requests: %{}, specs: %{}, jobs: %{}
def create_request_with_v1(%SpecHub{} = hub, req, spec_v1) do
with true <- (spec_v1.request_id == req.id and spec_v1.version == 1) || {:error, :invalid_initial_spec},
:ok <- validate_spec(spec_v1) do
{:ok, spec_v1,
%{hub | requests: Map.put(hub.requests, req.id, req), specs: Map.put(hub.specs, spec_v1.id, spec_v1)}}
end
end
def current_spec(%SpecHub{specs: specs}, request_id) do
specs
|> Map.values()
|> Enum.filter(&(&1.request_id == request_id))
|> case do
[] -> {:error, :unknown_request}
list -> {:ok, Enum.max_by(list, & &1.version)}
end
end
def revise_spec(%SpecHub{} = hub, request_id, actor_id, spec_id, changes) do
with {:ok, req} <- Map.fetch(hub.requests, request_id) |> or_err(:unknown_request),
true <- actor_id in [req.requester_id, req.lead_id] || {:error, :only_requester_or_lead_may_revise},
{:ok, prev} <- current_spec(hub, request_id),
next = Map.merge(prev, Map.merge(changes, %{id: spec_id, version: prev.version + 1, author_id: actor_id, confirmed_parts: []})),
:ok <- validate_spec(next) do
{:ok, next, %{hub | specs: Map.put(hub.specs, spec_id, next)}}
end
end
def assign_job(%SpecHub{} = hub, job_id, request_id, spec_id) do
with {:ok, current} <- current_spec(hub, request_id),
true <- current.id == spec_id || {:error, :job_spec_stale},
:ok <- check_blocking_points(current, job_id) do
job = %{id: job_id, request_id: request_id, request_spec_id: spec_id, status: :open}
{:ok, job, %{hub | jobs: Map.put(hub.jobs, job_id, job)}}
end
end
def repin_job(%SpecHub{} = hub, job_id, actor_id, spec_id) do
with {:ok, job} <- Map.fetch(hub.jobs, job_id) |> or_err(:unknown_job),
{:ok, req} <- Map.fetch(hub.requests, job.request_id) |> or_err(:unknown_request),
true <- req.lead_id == actor_id || {:error, :only_lead_may_repin},
{:ok, current} <- current_spec(hub, job.request_id),
true <- current.id == spec_id || {:error, :job_spec_stale} do
repinned = %{job | request_spec_id: spec_id}
{:ok, repinned, %{hub | jobs: Map.put(hub.jobs, job_id, repinned)}}
end
end
def finish_job(%SpecHub{} = hub, job_id, reported_spec_id) do
with {:ok, job} <- Map.fetch(hub.jobs, job_id) |> or_err(:unknown_job),
true <- reported_spec_id == job.request_spec_id || {:error, :report_names_wrong_version},
{:ok, current} <- current_spec(hub, job.request_id),
true <- job.request_spec_id == current.id || {:error, :job_spec_stale} do
done = %{job | status: :done}
{:ok, done, %{hub | jobs: Map.put(hub.jobs, job_id, done)}}
end
end
defp check_blocking_points(spec, job_id) do
blocking = Enum.filter(spec.open_points, & &1.blocking)
if blocking == [] or Enum.any?(blocking, &(&1.job_id == job_id)),
do: :ok,
else: {:error, :blocking_open_point}
end
defp validate_spec(spec) do
cond do
spec.acceptance_criteria == [] and spec.open_points == [] ->
{:error, :criteria_or_open_point_required}
Enum.any?(spec.open_points, &(&1.settle_with == :spike and not (is_integer(&1.budget_minutes) and &1.budget_minutes > 0))) ->
{:error, :spike_budget_required}
true ->
:ok
end
end
defp or_err({:ok, val}, _err), do: {:ok, val}
defp or_err(:error, err), do: {:error, err}
end
Spike and stale-version trace
Walking Example 2 (customer bulk-import concurrency cap) through these
guards shows how the hub blocks premature building during an open point and rejects stale
close-out with job_spec_stale after a mid-flight change:
1. hub.createRequestWithV1(req_imports, spec_v1)
// spec_v1 has 2 proposed criteria + 1 blocking open point (spike: job_spike_paths, 30m)
-> ok (version = 1; current spec is spec_v1)
2. hub.assignJob(job_build_cap, req_imports.id, spec_v1.id)
-> error: blocking_open_point (only linked spike job_spike_paths may run)
3. hub.assignJob(job_spike_paths, req_imports.id, spec_v1.id)
hub.finishJob(job_spike_paths, spec_v1.id)
-> ok (spike finds bulk uploads enter via background queue)
4. hub.reviseSpec(req_imports.id, lead_1, spec_v2.id,
{ acceptanceCriteria: [c1, c2, c3_upload_and_queue], openPoints: [], proposedParts: ["criterion:3"] })
hub.assignJob(job_build_cap, req_imports.id, spec_v2.id)
-> ok (version = 2; no blocking open points; job_build_cap pinned to spec_v2)
5. hub.reviseSpec(req_imports.id, lead_1, spec_v3.id,
{ outcome: "Max 5 imports per customer, or 2 on the free plan" })
hub.finishJob(job_build_cap, spec_v2.id)
-> error: job_spec_stale (job pins spec_v2; current version is 3)
6. hub.repinJob(job_build_cap, lead_1, spec_v3.id)
hub.finishJob(job_build_cap, spec_v3.id)
-> ok (worker_2 added free-plan cap; job closed against current version 3)
Tradeoffs and practical guidance
Request Spec trades a small upfront authoring cost for durable alignment across every downstream worker and checker. Weigh three practical tradeoffs before adopting it:
- Authoring overhead on tiny tasks: writing and reading a versioned record adds latency that only pays back when work crosses sessions, needs independent checking, or carries real rework cost.
- False confidence from weak criteria: a worker can satisfy every numbered criterion and still miss the spirit if the criteria were poorly written or if lead proposals went unread by the requester.
- Reconciliation work on frequent edits: every change of meaning creates a new version that in-flight jobs must catch up to — which is honest friction, not a bug, because silent drift is far more expensive.
Practical implementation notes
- Keep every spec to one screen: capture outcome, reason, observable criteria, and open points — leave design plans and task breakdowns on jobs.
- Keep progress completely separate from meaning: never store checked boxes inside the spec row, or routine progress ticks will mask real requirement changes.
- Store each version whole and immutable: a worker resuming against version 2 must read the exact words that were current when its job was scoped.
- Time-box every spike with a clear decision: every spike needs one question, a hard minute budget, and a decision that depends on the answer ("do nothing" is a valid outcome).
- Compare versions in the hub, not in the agent: a worker mid-task cannot reliably know whether a newer version was published; enforce version checks at assignment and close-out inside the hub.
Known uses and related patterns
-
Kubernetes object spec & generation: separates desired state
(
spec) from observed progress (status) and incrementsmetadata.generationonly when desired spec changes — Request Spec extends that separation with the requester's reason and explicit open points. - GitHub Spec Kit: provides structured feature specification templates that mark unresolved ambiguities and require measurable success criteria before coding agents implement.
- Kiro specs: separates requirements from design and execution tasks for coding agents; Request Spec keeps the versioned intent record in the hub and pins each job to a specific version ID.
- Volgenic: versions work-item intent separately from execution runs so downstream workers and reviewers can detect when requirements move mid-flight.
- Unmesh Joshi's Versioned Value: from Patterns of Distributed Systems — stores every update under a new version number so historical values remain readable; Request Spec applies the same immutability to agent instructions.
Related patterns
- Context Handoff — most easily confused with Request Spec; Request Spec is the versioned record of intent, while Context Handoff delivers that spec alongside facts, policies, and checkpoints into each worker's briefing.
- Change Propagation — begins where Request Spec ends, proactively locating every in-flight job, wait, and review affected when a new version is published.
- Orchestrator-Workers — supplies the lead agent that authors spec versions and decomposes work against them.
- Durable Job — defines the
Jobrecord whoserequest_spec_idpins each job to one version. - Policy Gate & Evidence-Backed Completion — read the spec's criteria and
required_claimsto verify completion claims before closing work.