Connect the stages in one controller, close timing gaps with dated evidence, enforce run-wide limits, and resume safely after an interruption.

By Youssef Hosni

Published: 2026-11-12

URL: https://todatabeyond.substack.com/p/building-a-deep-search-agent-with-2dc


In Part 2, we built a planner, an evidence validator, a profile merger, and a gap assessor, and ran each of them as a separate command. Part 3 connects them in one Python controller that runs the research from the first plan to a final report.

The controller saves a checkpoint at every stage boundary, shares one deadline and one spending record across all rounds, decides whether another round is justified, and can resume after the process exits without paying twice for the same work.

We finish with a live run on the Andrew Ng example. It used two rounds and four assignments in 192 seconds, at an estimated cost of $0.067 with Claude Haiku, and returned six role claims backed by ten citations. Timing is still unresolved for all six, and the report says why.

The complete code for this series is available in the Build-Deep-Search-Agent-with-Claude-Agent-SDK repository. The files used in this article are in its final/ folder.

Table of Contents:

  1. Define the Run Contract
  2. Wire the Stages into One Controller
  3. Close a Timing Gap with Dated Evidence
  4. Enforce Limits and Return Partial Results
  5. Checkpoint and Resume After Interruption
  6. Run the Agent and Inspect the Report

Build 3 projects with Jev and System One models: AI cost routing, Playwright exploratory testing, and a hybrid agent.

In this workshop, you’ll stop guessing and start measuring. You’ll build three working projects that show where System One decisions save money and time, where an LLM is still the right tool, and how to combine them in production.

Get a 35% discount using my referral link 👇


1. Define the run contract

In Part 2, we ran the planner, collector, validator, merger, and gap assessor separately. Once a controller runs those stages in sequence, it needs a record that ties their outputs to the same request.

It also needs to know how many assignments have started, what they have cost, and which completed work it can reuse after an interruption. We start by defining that record and saving the first checkpoint.

A. Separate the request from the run

The research request fixes the subject, identity anchors, scope, reference date, and execution limits. For the Andrew Ng example, October 31, 2026 is the date against which we assess whether a role was current or historical. That date stays the same even if we execute the agent later. We save the validated request inside the checkpoint so edits to the original request file cannot silently change an existing run.

The run state changes as the controller works. It records the current phase, round number, assignments started, estimated spend, and whether cost accounting is complete. It also points to the artifacts each stage produces. A collection reference identifies the round and assignment that produced it; the evidence itself stays in the collection artifact. When the controller stops, it records the reason in the run state.

Save the original request with the run, and keep stage outputs in separate files so they can be inspected and reused.

\Figure 1.The checkpoint preserves the original request and tracks the run’s progress. Its artifact references let readers inspect the outputs of individual stages.\

B. Initialize the checkpoint

We reuse ResearchRequest and ResearchState from Part 2. A small, versioned wrapper adds two timestamps. The created\_at records when we initialize the run directory.

The started\_at stays empty until the controller is ready to dispatch its first stage, so preparing a run in advance does not consume its execution window. When we add budget enforcement, the deadline will come from the saved start time and the original time limit. Restarting the process will use the same deadline.


class RunCheckpoint(Contract):
checkpoint_version: Literal[”1”] = “1”
created_at: AwareDatetime
started_at: AwareDatetime | None = None
research: ResearchStateThe initializer validates the request, allocates a unique run ID, and writes artifacts/<run_id>/state.json. It refuses to overwrite an existing run directory. As we connect the stages, the controller will save their outputs under that directory and update the checkpoint with references to the completed work.

C. Create the first run

Place init\run.py beside contracts.py and research\request.json in your Part 2project. From that directory, run:


python init_run.py --request research_request.json

The command prints the path to the new state.json and makes no model calls. Here is an excerpt of the file it wrote:


{
“checkpoint_version”: “1”,
“created_at”: “2026-11-07T22:11:10.174542Z”,
“started_at”: null,
“research”: {
“run_id”: “research-2393b9259da3”,
“phase”: “created”,
“round_index”: 0,
“assignments_started”: 0,
“estimated_cost_usd”: 0.0,
“stop_reason”: null
}
}

The command prints the path to state.json and makes no model calls. The checkpoint records when we created the run and leaves started\_at unset. This lets us prepare the run without consuming its five-minute execution window.

The full checkpoint also preserves October 31, 2026 as the research reference date, regardless of when the agent starts. In the next section, the controller will load this checkpoint and use its saved request to dispatch the first planning stage.


2. Wire the stages into one controller

In Section 1, we saved the original research request in state.json. The controller now loads that checkpoint and runs one research round: approve a plan, collect and validate evidence for each assignment, merge the validated claims, and assess what remains open.

We run the assignments sequentially so we can trace a claim from the planner’s question to its citation in the merged profile.

A. Make each handoff explicit

The approved plan gives each assignment an ID, a question, and evidence requirements. The controller creates a collection directory named for the round and assignment, such as round-01/r01-official\_roles/.

The collector writes the evidence records and source snapshots there. The validator reads that archive and saves its decisions separately. The merger receives both the archive and its validation file so it can check each citation against the saved passage.

A collection that completes without evidence stays visible in the checkpoint and skips validation. An incomplete collection stops this version of the controller and leaves its manifest on disk for inspection.

Once all assignments finish, the controller writes the merged profile and passes it to the gap assessor. The assessor writes follow-up questions without starting another search.

A merged claim should trace back to the assignment that found it, the decision that accepted it, and the saved passage that supports it.

\Figure 2.The merger reads the evidence archive alongside its validation decisions. The gap assessor uses the resulting profile to identify what the evidence still cannot answer.\

B. Save progress at the stage boundaries

The controller sets started\at just before dispatching the planner and uses one deadline for the round. Before starting a collection, it increments assignments\started and saves the checkpoint.

When the collector returns, it records the collection reference and reported cost. The planner and validator already record their costs through their shared runner, so the controller adds only the collector’s cost. It passes the remaining time and estimated budget to the collector before dispatch; the spending threshold is an estimate, and a call can report a cost above it.

The controller also saves the checkpoint after each validation result, the merged profile, and the gap assessment. A successful first round ends with phase: assessing, a saved gap assessment, and stop\_reason: null. The command has finished, but the research run has reached a decision point: the controller has enough information to consider a follow-up. This version accepts a fresh checkpoint; resuming interrupted work comes later.

C. Verify the first round

With the Part 2 dependencies installed, run the controlled example first. It uses simulated model responses and a synthetic source passage to exercise the actual file handoffs without calling an API.


python verify_controller.py

The local check produced:


{
“mode”: “offline_fixture”,
“phase”: “assessing”,
“round_index”: 1,
“assignments_started”: 1,
“merged_claims”: 1,
“open_gaps”: 1,
“stop_reason”: null
}

To run against live sources, configure your API key as in Part 2 and pass the fresh checkpoint from Section 1. This command makes paid model calls:


python controller.py --state artifacts/research-2393b9259da3/state.json

The live run stopped before collecting evidence. The planner produced an initial draft and one revision, but the reviewer requested changes to both, including clearer rules for source limits and roles whose timing could not be verified.

All four model calls completed successfully, at an estimated total cost of $0.00888. The controller still refused to dispatch any assignments because neither plan passed review. The files under round-01/planning/ preserve both drafts and their review decisions, so we can see why the run stopped.


3. Close a timing gap with dated evidence

The live controller run in Section 2 stopped at plan review, before any evidence was collected. To demonstrate the follow-up, we’ll start from the gap assessment we saved in Part 2.

Its first entry concerns Andrew Ng’s role at Baidu. The original passage supports the role and describes it in the past tense, but it gives no dates. That gives us a specific question for the next round: what evidence would establish when he held the role?

A. Turn the gap into one assignment

The gap already records the role, the reference date, the original evidence reference (E6), and the source we’ve used. We keep the gap ID as the assignment ID so we can trace the follow-up back to the question that prompted it.

The assignment asks for a dated primary passage tied to the same person and appointment. It names the source we’ve already cited so the collector knows that finding the same undated biography again would leave the gap open.

Run this with the gap\_assessment.json you saved in Part 2:


python resolve_timing.py assignment \
--request research_request.json \
--gaps gap_assessment.json \
--gap-id timing_9031f24fef52fa5e \
--out baidu_followup.json

The command writes an assignment you can inspect. It makes no API calls and does not dispatch the search. In the controller, a follow-up still goes through plan review.

B. Define what closes the gap

A source can establish that someone held a role on a particular day while leaving their status on the reference date unknown. This implementation uses two narrow rules.

An explicit end date before the reference date supports historical\as\of\reference for that appointment. A passage that explicitly places the person in the role on the reference date supports current\as\of\reference. An earlier observation, a start date by itself, or a retrieval timestamp leaves the gap open.

A human reviewer records the fact type, the normalized date, the date as written, the quoted passage, and the evidence reference. The code checks that the evidence is already cited for the same role, reopens the saved snapshot, and verifies that the passage appears there and contains the date text. It then applies the date rule. The reviewer is responsible for interpreting what the passage says about the appointment. Conflicting timing signals keep the gap open.

A follow-up closes a timing gap only when the reviewed passage supports the appointment’s status on the reference date.

\Figure 3.A follow-up can add evidence without resolving the original question. The timing field changes only when the reviewed passage meets the reference-date rule.\

C. Reassess the merged profile

We merge the original and follow-up collections together, apply the timing review to the merged profile, and run gap assessment again. In the controlled example, the first source says that Jordan Lee served as Director at Example Lab.

A fictional follow-up notice says that Lee’s term ended on May 12, 2020. Because that end date precedes the October 31, 2026 reference date, the code marks the appointment as historical and preserves both citations.


python verify_timing.py

The offline check produced:


{
“mode”: “offline_fixture”,
“open_timing_gaps_before_review”: 1,
“open_timing_gaps_after_review”: 0,
“timing”: “historical_as_of_reference”,
“citations_retained”: 2
}

The check also confirmed that an earlier observation leaves the gap open and that date text absent from the cited passage is rejected. The Baidu assignment remains a proposed follow-up; this example does not establish Ng’s dates. In the next section, the controller will use the change in open gap IDs, alongside its remaining budget, to decide whether another round is justified.


4. Enforce limits and return partial results

Section 2 stopped after the first gap assessment. We can now run the controller in a loop: assess the cumulative profile, decide whether to stop, and pass the selected gaps to the planner if another round is justified. Every round shares the same deadline and spending record. If the run ends before it answers the full request, the report preserves the claims and citations it has already validated.

A. Give the controller one budget for the run

The controller sets the deadline before the first planning call. Before starting another paid stage, it checks the remaining time and estimated spend.

In Section 2’s live run, the reviewer mistook the $0.25 cap for a single planning or review call for the $3.00 budget for the whole run, and asked the plans to restate rules that the code already enforces. The planner.py in the repository addresses this in the prompts.

A SHARED\_POLICY block, added to both the planner and reviewer prompts, lists what the application already enforces: the per-assignment source and record caps, how dates are recorded, deduplication in the merger, and the elapsed-time and cost limits, which plans must not estimate.

The reviewer may block a plan only for five defined problems: missing scope, two assignments asking the same question, a question that presupposes a finding, a requirement that cannot be checked against a source passage, or more sources than the per-assignment cap.

Every other comment goes into a separate advisories list. Python enforces the budget; the reviewer checks whether the proposed work fits the evidence and source constraints.

B. Measure progress by which gaps closed

After each round, the controller merges the collections and validation decisions saved so far, then writes a fresh gap assessment. It compares gap IDs across rounds.

A new citation can strengthen the evidence for a role while leaving its timing unresolved. If a follow-up closes none of the previous gaps, the controller stops for no\_progress, unless it has already reached an execution limit. Section 3’s human timing review remains a separate step: the loop does not promote an unreviewed timing signal into a dated claim.

Check the budget before starting more work. Measure progress by which open questions the new evidence answers.

\Figure 4.The controller checks the open questions and remaining budget before starting another round. The report preserves validated findings even when the run stops with gaps.\

C. Return what the run validated

With — until-stop, the controller saves each round’s decision and writes run\_report.json at the end. If a later stage hits a limit or fails, it can rebuild the report from the collection-and-validation pairs already recorded in the checkpoint.

Evidence that has not passed validation does not contribute to claims. If the controller stops before any assessment is available, open\_gaps is null. An empty list means the assessment ran and found no open gaps under its rules.

Run the controlled check first. It uses simulated model responses and makes no API calls:


python verify_run_limits.py

To run against live sources, create a fresh checkpoint. This command makes paid model calls, and collection still requires an approved plan.


STATE_PATH=$(python init_run.py --request research_request.json) &&
python controller.py --state “$STATE_PATH” --until-stop

The report handles a run the controller had time to stop. In the next section, we’ll handle a different case: the process exits before it can save a stop reason, and we need to decide which work is safe to reuse.


5. Checkpoint and resume after interruption

In Section 4, the controller had time to record why the run stopped and write a report. If the process exits during a model call, it may leave no record of whether the call completed or what it cost. A restart needs to distinguish work the controller can safely reuse from work it cannot account for.

A. Record the intent before dispatch

Before planning, collecting, or validating, the controller saves a pending\_call marker in state.json. It records the stage, round, and assignment ID when one applies.

Once the stage finishes and writes its artifacts, the controller saves the result references and recorded cost in the same checkpoint update that clears the marker. It writes the new checkpoint to a temporary file and then replaces the previous one.

For example, while collecting evidence for the second assignment, the checkpoint can contain:


{
“pending_call”: {
“stage”: “collecting”,
“round_number”: 1,
“assignment_id”: “prior_roles”
}
}

The marker records the intent to dispatch. The process could exit before sending the request or after receiving a result but before saving the completed checkpoint. An output file alone does not show that the controller saved both the result and its cost.

Reuse a paid stage only after its result is committed. If the pending marker survives a restart, preserve earlier results and stop before retrying the call.

\Figure 5 — A committed stage can be reused after a restart. A pending marker leaves the outcome and cost uncertain, so the controller reports earlier validated evidence without retrying the call.\

B. Resume with the original budget

The controller keeps the original start time, assignment counters, and estimated spend. Downtime counts against the same execution window. If there is no pending call, the controller reuses the committed collections and validations and continues from the next unfinished stage if the budget allows. If the deadline has passed, it can still rebuild a report from the validated evidence already on disk.

If a pending call remains, the controller records interrupted\call, sets cost\accounting\_complete to false, and leaves the marker in the checkpoint for inspection.

It then writes a partial report from the results it had already committed. This local implementation uses a file lock on macOS and Linux to prevent two controllers from writing to the same run at once.

C. Verify the restart paths

Run the offline fixture to simulate interruptions without making API requests:


python verify_resume.py

In the first case, the two new calls collect and validate the second assignment. The controller reuses both stages from the first assignment. In the second and third cases, the report retains the first citation without starting any more paid work. Only the interrupted call leaves cost accounting incomplete.

For a run started with this version of the controller, resume it after the original process exits:


python controller.py --state “artifacts/<run-id>/state.json” --resume

Replace <run-id> with the actual directory name. The controller restores the saved execution mode and can make paid calls if it can safely continue within the original budget. Runs already started under the Section 4 controller require a fresh checkpoint because they did not record pending calls.


6. Run the agent and inspect the report

A research report should tell us why the controller stopped, what the evidence supports, and which questions remain open. Start with the report, then trace one claim back to the decision that accepted it and the source passage that supports it. The same inspection works whether the run finishes uninterrupted or resumes from a checkpoint.

A. Start a fresh run

Use the latest code bundle and the same Python environment as the previous sections. With your API key configured, create a fresh checkpoint and pass it to the controller. This command makes paid model calls.


STATE_PATH=$(python init_run.py --request research_request.json) &&
python controller.py --state “$STATE_PATH” --until-stop

The controller prints STOP\REASON and the path to run\report.json. If it stops during planning, inspect the drafts and review decisions under round-01/planning/.

We ran this on November 8, 2026 with Claude Haiku and the same research request. This time both plans were approved at the first draft: the reviewer found no blocking issues and recorded five advisories in round 1 and four in round 2. The run used both rounds and all four assignments, collected 12 evidence records, and stopped after 192 seconds. The summary of its run\_report.json:


run_id research-fdbf28a17f30
reference_date 2026-10-31
stop_reason execution_limit
round_index 2
assignments_started 4
estimated_cost_usd 0.0668996
cost_accounting_complete true
claims 6 (10 citations)
open_gaps 6
review_queue 2

The stop reason is execution\_limit because the request allows two rounds and four assignments, and the run used both. Cost accounting is complete, so the $0.0669 estimate covers every call the run made.

The report contains six role claims. Round 1 collected the subject’s own pages and looked for organization pages that confirm the roles. Round 2 took two of the open timing gaps, AI Fund and Baidu, as its assignments:


Managing General Partner, AI Fund 3 citations 2 URLs
VP & Chief Scientist, Baidu 2 citations 1 URL
Chairman and Co-Founder, Coursera 1 citation 1 URL
Founder, DeepLearning.AI 1 citation 1 URL
Executive Chairman, LandingAI 1 citation 1 URL
Adjunct Professor, Stanford University 2 citations 2 URLs

All six claims still have unknown timing, so all six timing gaps remain open. The Baidu follow-up found a VentureBeat article that dates Ng’s departure to March 21, 2017. The validator sent that record to the review queue instead of accepting it, because a news outlet is a secondary source for the role. The date is a useful lead for the human timing review in Section 3, but it does not close the gap on its own.

B. Trace one claim back to its source

We will follow the AI Fund claim. Its third citation comes from a page AI Fund published itself, and reads:


{
“evidence”: {
“collection_id”: “r02-ai_fund_managing_general_partner_timing”,
“evidence_id”: “E2”
},
“source_snapshot”: “sources/b14c9adb40024212926ad47683bf7ae0.json”,
“source_url”: “https://aifund.ai/mediakit/”,
“retrieved_at”: “2026-11-08T05:21:25.744309+00:00”,
“role_excerpt”: “Andrew Ng is Managing General Partner at AI Fund, founder of DeepLearning.AI, and co-founder of Coursera.”,
“validator_timing”: “unknown”
}

Read its collection\id and evidence\id together: the collection tells you which archive to open, and the evidence ID tells you which record to find in evidence.jsonl.

The validation file for that collection holds the decision that accepted the record, and the snapshot holds the saved response the decision was checked against. Replace the run ID with your own:


RUN=artifacts/research-fdbf28a17f30
C=$RUN/round-02/r02-ai_fund_managing_general_partner_timing
grep ‘”id”: “E2”’ $C/evidence.jsonl
python -m json.tool $RUN/round-02/validation/r02-ai_fund_managing_general_partner_timing/validation.json
grep -c “Andrew Ng is Managing General Partner at AI Fund” $C/sources/b14c9adb40024212926ad47683bf7ae0.json

The evidence record shows that the collector found the passage on the AI Fund media kit, an official company page with no publication or update date.

The validation decision accepted the role and left its timing unknown: the only date on the page is a 2023 mention unrelated to the role, and the 2026 in the footer is a copyright year. The last command prints 1, confirming that the cited passage is in the saved snapshot.

Read the stop reason and the open gaps together. A run can return validated claims and still leave part of the request unanswered.

\Figure 6.The report’s evidence reference links a claim to the decision that accepted it and the saved passage that supports it.\

The result is a usable partial report. It names the roles the evidence supports, ties each one to a saved passage, and lists the six timing questions the run could not answer within its limits.


Conclusion

The controller turns the separate stages from Part 2 into one research run with a single budget. It saves a checkpoint at every stage boundary, measures progress by which gaps close rather than by how much evidence it collects, and records why it stopped.

The live run shows what that looks like in practice. The agent found six roles and supported each with saved passages, but no page it read established when those roles were held, so the report keeps timing unresolved and lists the open questions. A follow-up run, or a human timing review of the Baidu lead, can start from those gap records and the existing citations instead of starting over.