← Study Guide
DOMAIN 127% of exam

Agentic Architecture & Orchestration

The largest domain. Covers the agentic loop, multi-agent coordinator/subagent patterns, subagent spawning and context passing, enforcement vs. prompt-based guidance, hooks, task decomposition, and session/resume/fork management.

Key Takeaways

  • 1.Loop control flow is driven by stop_reason — continue on tool_use, stop on end_turn. Never parse natural-language text to decide when to stop.
  • 2.Subagents have isolated context; they do NOT inherit the coordinator's history. Pass everything they need explicitly in the prompt.
  • 3.When compliance must be guaranteed (money, identity), use programmatic enforcement (hooks/prerequisite gates), not prompt instructions.
  • 4.allowedTools must include Task for a coordinator to spawn subagents. Emit multiple Task calls in one response for parallelism.

Task Statements (7)

▶ click any point to expand details, examples & exam tips

1.1

Design and implement agentic loops for autonomous task execution

Knowledge of

  • The agentic loop lifecycle: send request → inspect stop_reason → execute requested tools → append results → iterate.

    An agent is a loop, not a single call. You send messages to Claude, it responds, and you inspect why it stopped. If it asked for a tool, you run the tool, append the result to the message history, and call again. You keep looping until Claude signals it is finished. The model — not your code — decides what happens next each iteration.

    ایجنٹ ایک لوپ ہے، ایک ہی کال نہیں۔ آپ Claude کو پیغام بھیجتے ہیں، وہ جواب دیتا ہے، اور آپ دیکھتے ہیں وہ کیوں رُکا۔ اگر اس نے ٹول مانگا تو ٹول چلائیں، نتیجہ پیغاموں میں شامل کریں، اور دوبارہ کال کریں۔ یہی چکر تب تک چلتا ہے جب تک Claude مکمل ہونے کا اشارہ نہ دے۔ ہر بار اگلا قدم ماڈل طے کرتا ہے، آپ کا کوڈ نہیں۔

    messages = [ {role: user, content: task} ]
    while True:
        resp = client.messages.create(model, messages, tools)
        messages.append({role: 'assistant', content: resp.content})
        if resp.stop_reason == 'tool_use':
            results = run_tools(resp.content)   # execute requested tools
            messages.append({role: 'user', content: results})
            continue                            # loop again
        else:  # 'end_turn'
            break                               # done
    Exam tip: The loop is driven by stop_reason, not by counting turns or reading the assistant's prose.
  • stop_reason values that matter: tool_use (Claude wants a tool run) vs end_turn (Claude is done).

    tool_use means the response contains one or more tool_use blocks the model wants you to execute and return. end_turn means the model finished its turn with a normal answer and is not requesting a tool. Other values exist (e.g. max_tokens, stop_sequence) but the two that drive loop control are these.

    tool_use کا مطلب ہے جواب میں ایک یا زیادہ tool_use بلاک ہیں جنہیں ماڈل چاہتا ہے آپ چلا کر واپس دیں۔ end_turn کا مطلب ہے ماڈل نے عام جواب کے ساتھ اپنی باری مکمل کر لی اور کوئی ٹول نہیں مانگ رہا۔ اور قدریں بھی ہیں (جیسے max_tokens، stop_sequence) مگر لوپ چلانے والی یہی دو ہیں۔

    stop_reasonMeaningWhat your loop does
    tool_useModel requested a toolRun the tool(s), append results, loop again
    end_turnModel finished normallyStop; present the final answer
    max_tokensHit the token limit mid-responseContinue/resend or raise max_tokens
    Exam tip: If a scenario asks how to know when to stop calling tools, the answer is 'check stop_reason == end_turn'.
  • Tool results are appended to conversation history so the model can reason about the next action.

    Each tool result goes back into the messages array as a tool_result block tied to its tool_use id. This is how new information (an order status, a search result) becomes visible to the model on the next iteration. If you don't append results, the model is blind to what the tool returned.

    ہر ٹول کا نتیجہ اپنے tool_use id سے جڑے tool_result بلاک کے طور پر پیغاموں میں واپس جاتا ہے۔ اسی طرح نئی معلومات (آرڈر کی حالت، کھوج کا نتیجہ) اگلی باری میں ماڈل کو نظر آتی ہے۔ اگر آپ نتائج شامل نہ کریں تو ماڈل کو پتا ہی نہیں چلتا کہ ٹول نے کیا لوٹایا۔

    // after running a tool, feed the result back:
    { role: 'user', content: [
      { type: 'tool_result',
        tool_use_id: 'toolu_01A...',
        content: '{"order_id":12345,"status":"shipped"}' }
    ]}
  • Model-driven decision-making (Claude picks the next tool from context) vs pre-configured decision trees / fixed tool sequences.

    In an agentic loop, the model chooses which tool to call next based on the current context — it adapts to what it learns. This is different from a hard-coded pipeline where step 1 always calls tool A, then tool B. Model-driven flow handles ambiguity and branching that a fixed tree cannot.

    ایجنٹ لوپ میں ماڈل موجودہ سیاق کی بنیاد پر اگلا ٹول خود چنتا ہے — جو سیکھتا ہے اسی کے مطابق ڈھلتا ہے۔ یہ اُس بندھی ترتیب سے مختلف ہے جہاں پہلا قدم ہمیشہ ٹول A، پھر ٹول B چلاتا ہے۔ ماڈل والا بہاؤ وہ الجھن اور شاخ بندی سنبھالتا ہے جو ایک طے شدہ ترتیب نہیں سنبھال سکتی۔

    ApproachWho decides next stepBest for
    Model-driven loopClaude, from contextAmbiguous / branching tasks
    Fixed sequence / decision treeYour code, predeterminedPredictable, uniform workflows

Skills in

  • Loop that continues while stop_reason == 'tool_use' and terminates when stop_reason == 'end_turn'.

    The correct control structure keys entirely off stop_reason. A safety cap on iterations is fine as a backstop, but it must not be the PRIMARY stopping condition — that would truncate legitimate long tasks and mask bugs.

    درست کنٹرول پورا stop_reason پر چلتا ہے۔ چکروں پر حفاظتی حد ٹھیک ہے مگر یہ رُکنے کی بنیادی شرط نہ ہو — ورنہ لمبے سچے کام بیچ میں کٹ جائیں گے اور خرابیاں چھپ جائیں گی۔

    while resp.stop_reason == 'tool_use':     # PRIMARY stop condition
        results = run_tools(resp.content)
        messages.append({role: 'user', content: results})
        resp = client.messages.create(model, messages, tools)
        iterations += 1
        if iterations > 50: raise RuntimeError('runaway loop')  # safety CEILING only
    # fell out of loop => stop_reason == 'end_turn' => done
    Exam tip: An iteration cap as the *main* stop mechanism is an anti-pattern; use it only as a safety ceiling.
  • Add each tool result back into context between iterations so new information informs reasoning.

    Forgetting to append results is the classic beginner bug: the model re-requests the same tool because it never 'saw' the answer. Always append the tool_result before the next create() call.

    نتائج شامل کرنا بھول جانا نئے لوگوں کی عام غلطی ہے: ماڈل وہی ٹول دوبارہ مانگتا ہے کیونکہ اس نے جواب 'دیکھا' ہی نہیں۔ اگلی create() کال سے پہلے ہمیشہ tool_result شامل کریں۔

    resp = create(messages, tools)
    messages.append({role: 'assistant', content: resp.content})
    results = run_tools(resp.content)
    messages.append({role: 'user', content: results})   # <-- MUST append the result
    // skip this line and the model re-requests the same tool forever,
    // because the answer never entered its context

Edge Cases & Traps

  • ANTI-PATTERN: parsing assistant natural-language text to decide the loop is 'done' — use stop_reason, not text.
  • ANTI-PATTERN: using an arbitrary iteration cap as the PRIMARY stopping mechanism (a safety ceiling is fine, but not the main signal).
  • ANTI-PATTERN: treating the presence of assistant text content as a completion indicator.
1.2

Orchestrate multi-agent systems with coordinator–subagent patterns

Knowledge of

  • Hub-and-spoke: the coordinator manages all inter-subagent communication, error handling, and routing.

    In a hub-and-spoke design, subagents never talk to each other directly. Everything flows through the coordinator (the hub), which routes information, handles errors consistently, and keeps the whole run observable. This centralization is what makes the system debuggable and controllable.

    hub-and-spoke ڈیزائن میں چھوٹے ایجنٹ آپس میں براہِ راست بات نہیں کرتے۔ سب کچھ بڑے ایجنٹ (hub) کے ذریعے جاتا ہے، جو معلومات صحیح جگہ بھیجتا ہے، خرابیاں ایک ہی طریقے سے سنبھالتا ہے، اور پورا کام نظر میں رکھتا ہے۔ یہی مرکزیت نظام کو جانچنے اور قابو کرنے کے قابل بناتی ہے۔

    Exam tip: Route ALL subagent communication through the coordinator — it buys observability and consistent error handling.
  • Subagents run with isolated context — no automatic inheritance of the coordinator's conversation history.

    Each subagent starts fresh. It does not see the coordinator's messages or other subagents' outputs unless you explicitly put that information into its prompt. Assuming shared memory is a top cause of 'the subagent ignored the earlier findings' bugs.

    ہر چھوٹا ایجنٹ نئے سرے سے شروع ہوتا ہے۔ وہ بڑے ایجنٹ کے پیغام یا دوسرے ایجنٹوں کے نتائج نہیں دیکھتا جب تک آپ وہ معلومات خود اس کے پرامپٹ میں نہ ڈالیں۔ مشترکہ یادداشت مان لینا 'ایجنٹ نے پہلے کے نتائج نظر انداز کر دیے' والی خرابی کی سب سے بڑی وجہ ہے۔

    Exam tip: If a subagent 'forgot' context, the fix is to pass it explicitly — not to expect inheritance.
  • Coordinator role: task decomposition, delegation, result aggregation, and deciding WHICH subagents to invoke based on query complexity.

    A good coordinator analyzes the request, breaks it into the right subtasks, picks only the subagents that are actually needed, and merges their outputs. A simple query might use one subagent; a broad one might fan out to several in parallel.

    اچھا بڑا ایجنٹ درخواست کا تجزیہ کرتا ہے، اسے صحیح ذیلی کاموں میں بانٹتا ہے، صرف ضروری چھوٹے ایجنٹ چنتا ہے، اور ان کے نتائج ملاتا ہے۔ آسان سوال کے لیے ایک ایجنٹ کافی؛ وسیع سوال کے لیے کئی ایک ساتھ چل سکتے ہیں۔

  • Risk: overly narrow task decomposition leads to incomplete coverage of broad topics.

    If the coordinator decomposes 'creative industries' into only 'digital art, graphic design, photography', the report will miss music, writing, and film — even though every subagent 'succeeded'. The failure is in the decomposition, upstream of the subagents.

    اگر بڑا ایجنٹ 'تخلیقی صنعتوں' کو صرف 'ڈیجیٹل آرٹ، گرافک ڈیزائن، فوٹوگرافی' میں بانٹے، تو رپورٹ موسیقی، تحریر اور فلم چھوڑ دے گی — چاہے ہر چھوٹا ایجنٹ 'کامیاب' ہوا ہو۔ خرابی تقسیم میں ہے، جو ایجنٹوں سے پہلے کا مرحلہ ہے۔

    Exam tip: When output misses whole subtopics but all subagents succeeded, suspect the coordinator's decomposition first.

Skills in

  • Coordinators that analyze the query and dynamically select subagents instead of always running the full pipeline.

    Hard-wiring every query through search→analyze→synthesize wastes cost and latency on simple requests and can dilute focus. A dynamic coordinator invokes only what the query needs.

    ہر سوال کو زبردستی search→analyze→synthesize سے گزارنا آسان درخواستوں پر خرچ اور وقت ضائع کرتا ہے اور توجہ بکھیر دیتا ہے۔ چالاک بڑا ایجنٹ صرف وہی چلاتا ہے جو سوال کو چاہیے۔

    if is_simple(query):
        return Task(search_agent, query)               # one hop, done
    else:
        Task(search_agent, ...); Task(analysis_agent, ...); Task(synthesis_agent, ...)
    // don't force "what's the capital of France?" through the full pipeline
  • Partition scope across subagents to minimize duplication (distinct subtopics / source types per agent).

    Assign each subagent a non-overlapping slice — e.g. one covers academic papers, another news, another industry reports — so they don't all fetch the same sources. Explicit partitioning improves coverage and cuts redundant work.

    ہر چھوٹے ایجنٹ کو بغیر اوورلیپ کا حصہ دیں — مثلاً ایک تحقیقی مقالے، دوسرا خبریں، تیسرا صنعتی رپورٹیں — تاکہ سب ایک ہی ذرائع نہ لائیں۔ صاف تقسیم احاطہ بہتر کرتی اور فالتو کام گھٹاتی ہے۔

    Task(agent_a, "cover ACADEMIC papers on X")
    Task(agent_b, "cover NEWS coverage of X")
    Task(agent_c, "cover INDUSTRY reports on X")
    // non-overlapping slices -> full coverage and no 3x-fetching the same source
  • Iterative refinement loops: coordinator evaluates synthesis for gaps, re-delegates targeted queries, re-invokes synthesis until coverage is sufficient.

    Rather than one pass, the coordinator inspects the synthesized draft, identifies missing areas, sends targeted follow-up queries to search/analysis subagents, then re-synthesizes. This loop continues until coverage meets the quality bar.

    ایک ہی بار کے بجائے بڑا ایجنٹ تیار مسودہ دیکھتا ہے، کمی والے حصے پہچانتا ہے، search/analysis ایجنٹوں کو مخصوص سوال بھیجتا ہے، پھر دوبارہ ملاتا ہے۔ یہ چکر تب تک چلتا ہے جب تک احاطہ معیار پر نہ آئے۔

    draft = Task(synthesis, findings)
    gaps  = coordinator.find_gaps(draft)      # e.g. "no data on the music industry"
    while gaps:
        more  = Task(search, targeted_query(gaps))
        draft = Task(synthesis, findings + more)
        gaps  = coordinator.find_gaps(draft)  # loop until coverage is sufficient
  • Route all subagent communication through the coordinator for observability and consistent error handling.

    Don't let a search subagent hand results straight to a synthesis subagent. Send everything back to the coordinator, which logs it, handles failures uniformly, and decides the next hop. Direct subagent-to-subagent wiring hides state and makes failures impossible to trace.

    کھوج کرنے والے ایجنٹ کو نتائج سیدھے ملانے والے ایجنٹ کو نہ دینے دیں۔ سب کچھ بڑے ایجنٹ کو واپس بھیجیں، جو اسے ریکارڈ کرتا ہے، خرابیاں ایک جیسے طریقے سے سنبھالتا ہے، اور اگلا قدم طے کرتا ہے۔ ایجنٹ سے ایجنٹ سیدھا جوڑ حالت چھپا دیتا ہے اور خرابی کا سراغ ناممکن بنا دیتا ہے۔

    GOOD (hub-and-spoke): search -> coordinator -> analysis -> coordinator -> synthesis
    BAD  (no visibility):  search -> analysis -> synthesis   # coordinator can't log/route/recover

Edge Cases & Traps

  • When reports miss whole sub-topics but every subagent 'succeeded', the root cause is usually the coordinator's decomposition — not the downstream agents.
  • Don't blame the search/analysis/synthesis agents for gaps they were never assigned to cover.
1.3

Configure subagent invocation, context passing, and spawning

Knowledge of

  • The Task tool spawns subagents; the coordinator's allowedTools MUST include Task.

    Subagents are launched by the coordinator calling the built-in Task tool. If Task is not in the coordinator's allowedTools, it simply cannot delegate — a silent, easy-to-miss misconfiguration.

    چھوٹے ایجنٹ بڑے ایجنٹ کے بلٹ اِن Task ٹول چلانے سے بنتے ہیں۔ اگر Task بڑے ایجنٹ کے allowedTools میں نہ ہو تو وہ کام سونپ ہی نہیں سکتا — ایک خاموش، آسانی سے نظر انداز ہونے والی غلطی۔

    coordinator = AgentDefinition(
      system_prompt='You orchestrate research subagents...',
      allowedTools=['Task'],   # ← required to spawn subagents
    )
    Exam tip: No delegation happening? Check that Task is in the coordinator's allowedTools.
  • Subagent context must be provided explicitly in the prompt — no shared memory across invocations.

    Because subagents don't inherit history, the coordinator must inline everything the subagent needs: the sub-question, relevant prior findings, and any constraints. Two invocations of the same subagent also don't share memory with each other.

    چونکہ چھوٹے ایجنٹ تاریخ وراثت میں نہیں لیتے، بڑے ایجنٹ کو سب کچھ خود ان کے پرامپٹ میں ڈالنا پڑتا ہے: ذیلی سوال، متعلقہ پہلے کے نتائج، اور کوئی بھی شرط۔ ایک ہی ایجنٹ کی دو بار کالیں بھی آپس میں یادداشت شیئر نہیں کرتیں۔

  • AgentDefinition configuration: descriptions, system prompts, and per-subagent tool restrictions.

    Each subagent type is defined with a description (how/when it's used), a system prompt (its role and quality bar), and a restricted tool set scoped to its job. Scoping tools per subagent prevents cross-specialization misuse.

    ہر چھوٹے ایجنٹ کی قسم تین چیزوں سے بنتی ہے: description (کب/کیسے استعمال ہو)، سسٹم پرامپٹ (اس کا کردار اور معیار)، اور صرف اس کے کام کے محدود ٹول۔ ہر ایجنٹ کے ٹول محدود رکھنا اسے دوسرے کے دائرے میں غلط استعمال سے روکتا ہے۔

  • Fork-based session management for exploring divergent approaches from a shared analysis baseline.

    Forking lets you branch from a common analysis and explore two different directions independently (e.g. two refactor strategies) without one polluting the other. See Task 1.7 for fork_session.

    Forking سے آپ ایک مشترکہ تجزیے سے شاخ بنا کر دو الگ سمتیں آزادی سے آزما سکتے ہیں (مثلاً دو refactor طریقے) بغیر ایک کے دوسرے کو خراب کیے۔ fork_session کے لیے Task 1.7 دیکھیں۔

Skills in

  • Include complete prior-agent findings directly in a subagent's prompt (e.g., pass web search results and document analysis outputs to the synthesis subagent).

    The synthesis subagent can only combine what it can see. The coordinator must paste the actual search results and analysis outputs into the synthesis prompt — not just say 'synthesize the findings'.

    ملانے والا ایجنٹ صرف وہی جوڑ سکتا ہے جو اسے نظر آئے۔ بڑے ایجنٹ کو اصل کھوج کے نتائج اور تجزیے ملانے والے پرامپٹ میں ڈالنے پڑتے ہیں — صرف 'نتائج ملا دو' کہنا کافی نہیں۔

    Task(synthesis_agent, prompt=f'''
    Write a cited report from these findings:
    SEARCH RESULTS: {search_results}      # the actual content, inlined
    ANALYSIS:       {analysis_output}
    ''')
    // "synthesize the findings" with nothing attached -> an empty report
  • Use structured data formats to separate content from metadata (source URLs, document names, page numbers) when passing context to preserve attribution.

    Pass findings as structured records — claim + evidence excerpt + source URL + date — rather than blended prose. This keeps provenance intact through synthesis so citations survive.

    نتائج منظم ریکارڈ کے طور پر بھیجیں — دعویٰ + ثبوت کا ٹکڑا + ذریعے کا لنک + تاریخ — نہ کہ گھلی ملی عبارت۔ اس سے ملانے کے بعد بھی حوالہ سلامت رہتا ہے۔

    { "claim": "Adoption grew 40% in 2024",
      "evidence": "...grew by 40 percent...",
      "source": "https://example.org/report",
      "published": "2024-06" }
  • Spawn parallel subagents by emitting multiple Task calls in a SINGLE response, not across separate turns.

    To run subagents concurrently, the coordinator emits several Task tool_use blocks in one assistant message. Spreading them across turns forces sequential execution and loses the latency win.

    چھوٹے ایجنٹ ایک ساتھ چلانے کے لیے بڑا ایجنٹ ایک ہی پیغام میں کئی Task tool_use بلاک بھیجتا ہے۔ انہیں الگ الگ باریوں میں پھیلانا کام ایک ایک کر کے چلاتا ہے اور وقت کی بچت ختم کر دیتا ہے۔

    # ONE assistant message emitting 3 Task blocks -> they run concurrently:
    [ Task(search, "topic A"),
      Task(search, "topic B"),
      Task(search, "topic C") ]
    # one Task per turn instead -> sequential, ~3x slower
    Exam tip: Parallelism = multiple Task calls in ONE coordinator response.
  • Write coordinator prompts that specify research goals and quality criteria, not step-by-step procedures — this preserves subagent adaptability.

    Tell subagents WHAT good looks like (goals, coverage, citation standards) rather than exact steps. Over-scripting removes the model's ability to adapt to what it discovers.

    چھوٹے ایجنٹوں کو یہ بتائیں کہ اچھا کام کیسا ہوتا ہے (مقصد، احاطہ، حوالوں کے معیار)، نہ کہ عین قدم۔ حد سے زیادہ بندھی ہدایات ماڈل کی وہ صلاحیت چھین لیتی ہیں کہ وہ جو ملے اس کے مطابق ڈھلے۔

    GOOD (goals):  "Produce a cited report covering every major sub-area;
                    each claim needs a source + date."
    BAD  (steps):  "1. search Google  2. open the first 3 links  3. copy text..."
    // hard-coded steps can't adapt when a link 404s or a new sub-area appears

Edge Cases & Traps

  • Forgetting Task in allowedTools silently prevents delegation.
  • Assuming subagents 'remember' earlier context is a common failure — they do not.
1.4

Implement multi-step workflows with enforcement and handoff patterns

Knowledge of

  • Programmatic enforcement (hooks, prerequisite gates) vs prompt-based guidance for ordering.

    Prompt guidance ('always verify the customer first') is a request the model usually follows — but not always. Programmatic enforcement (a gate in code / a hook) makes it impossible to skip. Choose enforcement when 'usually' isn't good enough.

    پرامپٹ کی ہدایت ('پہلے ہمیشہ گاہک کی تصدیق کرو') ایک درخواست ہے جسے ماڈل اکثر مانتا ہے — مگر ہمیشہ نہیں۔ کوڈ کی پابندی (gate/hook) اسے چھوڑنا ناممکن بنا دیتی ہے۔ جہاں 'اکثر' کافی نہ ہو، وہاں پابندی چنیں۔

    MechanismGuaranteeUse when
    Prompt instruction / few-shotProbabilistic (non-zero failure)Guidance, preferences, style
    Hook / prerequisite gateDeterministicMoney, identity, safety, compliance
    Exam tip: 'Must always' + financial/identity consequences ⇒ enforcement (gate/hook), never a prompt tweak.
  • When deterministic compliance is required (identity verification before financial ops), prompt instructions have a NON-ZERO failure rate.

    Even a well-written mandatory instruction fails some fraction of the time. At scale, a small percentage of wrong-account refunds is unacceptable, so the requirement forces a hard gate rather than a persuasive prompt.

    اچھی طرح لکھی لازمی ہدایت بھی کبھی نہ کبھی ناکام ہوتی ہے۔ بڑے پیمانے پر تھوڑے فیصد غلط اکاؤنٹ ریفنڈ بھی قابلِ قبول نہیں، اس لیے یہ تقاضا نرم پرامپٹ کے بجائے سخت gate مانگتا ہے۔

  • Structured handoff protocols for mid-process escalation include customer details, root cause analysis, and recommended actions.

    When escalating to a human who can't see the transcript, hand off a compact structured summary so they can act immediately without re-interviewing the customer.

    جب معاملہ ایسے انسان کو دیں جو گفتگو نہیں دیکھ سکتا، تو ایک مختصر منظم خلاصہ سونپیں تاکہ وہ گاہک سے دوبارہ پوچھے بغیر فوراً کارروائی کر سکے۔

Skills in

  • Block downstream tool calls until prerequisites complete (e.g., block process_refund until get_customer has returned a verified customer ID).

    Implement a gate that checks state: if no verified customer ID exists, reject/redirect lookup_order and process_refund. This makes the ordering physically impossible to violate.

    ایک gate بنائیں جو حالت جانچے: اگر تصدیق شدہ کسٹمر ID نہیں تو lookup_order اور process_refund روک/موڑ دے۔ اس سے ترتیب توڑنا سرے سے ناممکن ہو جاتا ہے۔

    # PreToolUse-style gate
    if tool in ('lookup_order','process_refund') and not state.verified_customer_id:
        return block("get_customer must complete first")
  • Decompose multi-concern requests into distinct items, investigate each in parallel with shared context, then synthesize one unified resolution.

    A message with a missing item + an overcharge + a shipping delay is three tasks. Split them, investigate each (sharing the same customer/case context), then reply once with all three resolved — don't close after the first.

    ایک پیغام جس میں غائب چیز + زیادہ چارج + ترسیل میں تاخیر ہو، وہ تین کام ہیں۔ انہیں الگ کریں، ہر ایک جانچیں (وہی گاہک/کیس سیاق ساتھ رکھ کر)، پھر تینوں حل کر کے ایک بار جواب دیں — پہلے پر ہی بند نہ کریں۔

    msg = "my item never arrived, I was charged twice, AND shipping was late"
    issues = [ missing_item, double_charge, late_shipping ]      # 3 tasks
    for i in issues:
        investigate(i, shared_ctx=customer_case)
    reply_once(resolve_all(issues))   # don't close the case after fixing only issue #1
  • Compile structured handoff summaries (customer ID, root cause, refund amount, recommended action) when escalating to humans who lack the transcript.

    The human picking up the escalation never saw the conversation. Hand them a compact record with everything needed to act — who, what went wrong, the diagnosis, and the recommended fix — so they don't have to re-interview the customer or re-read logs.

    جو انسان معاملہ سنبھالے گا اس نے گفتگو دیکھی ہی نہیں۔ اسے ایک مختصر ریکارڈ دیں جس میں کارروائی کے لیے سب کچھ ہو — کون، کیا غلط ہوا، تشخیص، اور تجویز کردہ حل — تاکہ اسے گاہک سے دوبارہ پوچھنا یا logs پڑھنا نہ پڑے۔

    { "customer_id": "C-8842",
      "root_cause": "double charge on order 12345",
      "refund_amount": 49.99,
      "recommended_action": "issue refund + apology credit" }

Edge Cases & Traps

  • TRAP: 'strengthen the system prompt' / 'add few-shot examples' for a business-critical ordering rule — both are probabilistic and insufficient when money is involved. Use a gate.
  • TRAP: solving a tool-ORDERING problem by changing tool AVAILABILITY (routing classifier) — wrong lever.
1.5

Apply Agent SDK hooks for tool call interception and data normalization

Knowledge of

  • PostToolUse hooks intercept tool RESULTS for transformation before the model processes them.

    A PostToolUse hook runs after a tool returns but before the model sees the result. Use it to reshape or normalize data — e.g. convert every timestamp to ISO 8601 — so the model receives consistent inputs regardless of which backend produced them.

    PostToolUse hook ٹول کے نتیجہ دینے کے بعد مگر ماڈل کے دیکھنے سے پہلے چلتا ہے۔ اسے ڈیٹا کی شکل بدلنے/یکساں کرنے کے لیے استعمال کریں — مثلاً ہر timestamp کو ISO 8601 میں بدلنا — تاکہ ماڈل کو یکساں ان پٹ ملے، چاہے پیچھے کوئی بھی نظام ہو۔

    def post_tool_use(tool_name, result):
        # normalize mixed timestamp formats to ISO 8601
        if 'created_at' in result:
            result['created_at'] = to_iso8601(result['created_at'])
        return result
  • Interception hooks on OUTGOING tool calls enforce compliance rules (e.g., block refunds above a threshold).

    A pre-call interception hook inspects the tool the model wants to run and can block or redirect it. This is how you guarantee a policy like 'refunds over $500 must go to a human' regardless of what the model decides.

    کال سے پہلے والا hook اُس ٹول کو دیکھتا ہے جو ماڈل چلانا چاہتا ہے اور اسے روک یا موڑ سکتا ہے۔ اسی طرح آپ 'خودبخود ۵۰۰ ڈالر سے اوپر ریفنڈ انسان کے پاس جائے' جیسی پالیسی کی ضمانت دیتے ہیں، چاہے ماڈل کچھ بھی طے کرے۔

    def pre_tool_use(tool_name, args):
        if tool_name == 'process_refund' and args['amount'] > 500:
            return redirect('escalate_to_human')  # block + reroute
  • The distinction between using hooks for deterministic guarantees versus relying on prompt instructions for probabilistic compliance.

    Hooks execute in code every time — a guarantee. Prompt instructions are followed most of the time — a tendency. For anything that must never fail, the hook wins.

    Hooks ہر بار کوڈ میں چلتے ہیں — یہ ضمانت ہے۔ پرامپٹ کی ہدایات اکثر مانی جاتی ہیں — یہ رجحان ہے۔ جو چیز کبھی ناکام نہ ہو، اس کے لیے hook جیتتا ہے۔

    Exam tip: Keyword 'guaranteed' in a compliance question ⇒ hook, not prompt.

Skills in

  • PostToolUse hooks that normalize heterogeneous formats (Unix timestamps, ISO 8601, numeric status codes) across MCP tools.

    Different MCP tools return dates/statuses in different shapes. Normalizing them in a PostToolUse hook means the model reasons over one consistent format and downstream logic stays simple.

    مختلف MCP ٹول تاریخیں/حالتیں الگ الگ شکل میں دیتے ہیں۔ انہیں PostToolUse hook میں یکساں کرنے سے ماڈل ایک ہی شکل پر سوچتا ہے اور آگے کا کوڈ سادہ رہتا ہے۔

    def post_tool_use(tool, result):
        # tool A -> 1719878400 (unix), tool B -> "2024-07-02", tool C -> code 200
        result['ts']     = to_iso8601(result['ts'])
        result['status'] = STATUS_MAP.get(result['status'], result['status'])
        return result   # the model now sees ONE consistent shape
  • Interception hooks that block policy-violating actions (e.g., refunds > $500) and redirect to alternative workflows (e.g., human escalation).

    A PreToolUse-style hook inspects the outgoing call and can veto or reroute it before it ever runs. Because it executes in code on every call, a threshold like 'refunds over $500 go to a human' holds no matter what the model decides.

    PreToolUse قسم کا hook باہر جاتی کال کو چلنے سے پہلے دیکھ کر روک یا موڑ سکتا ہے۔ چونکہ یہ ہر کال پر کوڈ میں چلتا ہے، اس لیے '۵۰۰ ڈالر سے اوپر ریفنڈ انسان کو' جیسی حد قائم رہتی ہے، چاہے ماڈل کچھ بھی طے کرے۔

    def pre_tool_use(tool_name, args):
        if tool_name == 'process_refund' and args['amount'] > 500:
            return redirect('escalate_to_human')   # blocked + rerouted
  • Choose hooks over prompts whenever business rules require guaranteed compliance.

    A prompt is a request the model follows most of the time; a hook is code that runs every time. When the rule protects money, identity, or safety, 'most of the time' is a defect — reach for the deterministic mechanism.

    پرامپٹ ایک درخواست ہے جسے ماڈل اکثر مانتا ہے؛ hook وہ کوڈ ہے جو ہر بار چلتا ہے۔ جب اصول پیسے، شناخت یا حفاظت کی حفاظت کرے، تو 'اکثر' ایک خرابی ہے — پکے (deterministic) طریقے کی طرف جائیں۔

    Rule: "refunds over $500 must go to a human."
    prompt: "Please always escalate refunds over $500"  -> obeyed ~most of the time
    hook:   if amount > 500: redirect('human')          -> runs EVERY call (guarantee)
    // money / identity / safety -> pick the hook

Edge Cases & Traps

  • If the requirement is 'guaranteed', the answer is almost always a hook/gate, not a prompt tweak.
1.6

Design task decomposition strategies for complex workflows

Knowledge of

  • Fixed sequential pipelines (prompt chaining) vs dynamic adaptive decomposition based on intermediate findings.

    Prompt chaining is a predetermined sequence of focused steps — good when you know the shape of the work in advance. Dynamic decomposition generates the next subtasks from what was just discovered — good for open-ended investigation where you can't plan every step upfront.

    Prompt chaining پہلے سے طے شدہ مرکوز قدموں کی ترتیب ہے — تب اچھی جب کام کی شکل پہلے سے پتا ہو۔ چالاک تقسیم اگلے ذیلی کام ابھی ملی باتوں سے بناتی ہے — تب اچھی جب کام کھلا ہو اور ہر قدم پہلے سے طے نہ ہو سکے۔

    PatternStructureBest for
    Prompt chainingFixed, sequential stepsPredictable multi-aspect reviews
    Dynamic decompositionSubtasks generated from findingsOpen-ended investigation / exploration
  • Prompt chaining patterns break reviews into sequential steps (analyze each file individually, then run a cross-file integration pass).

    A large review is split into per-file passes (deep, consistent local analysis) followed by a separate pass that examines how the files interact. This avoids the shallow, contradictory output you get from cramming everything into one pass.

    بڑے جائزے کو ہر فائل کے الگ چکروں میں بانٹا جاتا ہے (گہرا، یکساں مقامی جائزہ)، پھر ایک الگ چکر دیکھتا ہے کہ فائلیں آپس میں کیسے جُڑتی ہیں۔ اس سے وہ سطحی اور متضاد نتیجہ نہیں آتا جو سب کچھ ایک چکر میں ٹھونسنے سے ملتا ہے۔

  • The value of adaptive investigation plans that generate subtasks based on what is discovered at each step.

    For 'add comprehensive tests to a legacy codebase', you can't list every subtask upfront. You map the structure, find high-impact areas, then create a prioritized plan that adapts as dependencies surface.

    'پرانے کوڈ میں مکمل ٹیسٹ شامل کرو' جیسے کام میں ہر ذیلی کام پہلے سے نہیں گنا جا سکتا۔ پہلے ڈھانچہ سمجھیں، زیادہ اثر والے حصے ڈھونڈیں، پھر ترجیح والا منصوبہ بنائیں جو جُڑی چیزیں سامنے آنے پر بدلتا رہے۔

Skills in

  • Select prompt chaining for predictable multi-aspect reviews; dynamic decomposition for open-ended investigations.

    If you already know the steps (security pass, then performance pass, then style pass), a fixed chain is simpler and more consistent. If you can't know the steps until you see intermediate findings (exploring an unfamiliar codebase), let the model generate the next subtasks as it learns.

    اگر قدم پہلے سے پتا ہوں (پہلے سیکیورٹی، پھر کارکردگی، پھر انداز)، تو بندھی ترتیب سادہ اور زیادہ یکساں ہے۔ اگر قدم بیچ کے نتائج دیکھے بغیر پتا نہ ہوں (اجنبی کوڈ کی کھوج)، تو ماڈل کو اگلے ذیلی کام سیکھتے ہوئے بنانے دیں۔

    Known shape  -> prompt chaining:      step1 -> step2 -> step3 (fixed)
    Unknown shape -> dynamic decomposition: map -> inspect findings -> plan next steps
  • Split large code reviews into per-file local passes PLUS a separate cross-file integration pass to avoid attention dilution.

    When one pass reviews 14 files, quality varies wildly and feedback contradicts itself. Per-file passes give consistent depth; a dedicated integration pass catches data-flow issues across files.

    جب ایک چکر ۱۴ فائلیں دیکھے تو معیار بہت اوپر نیچے ہوتا ہے اور رائے آپس میں ٹکراتی ہے۔ ہر فائل کے الگ چکر یکساں گہرائی دیتے ہیں؛ اور ایک الگ انضمام چکر فائلوں کے درمیان ڈیٹا کے بہاؤ کے مسئلے پکڑتا ہے۔

    for f in changed_files:            # per-file pass: consistent local depth
        review(f)
    review_integration(changed_files)  # separate pass: cross-file data flow
    // one giant pass over 14 files -> shallow, self-contradicting feedback
    Exam tip: A bigger context window does NOT fix attention dilution — split the work into passes.
  • Decompose open-ended tasks by first mapping structure, identifying high-impact areas, then creating a prioritized plan that adapts as dependencies are discovered.

    For a task like 'add comprehensive tests to a legacy codebase', don't try to enumerate every test upfront. Map the module structure, find the highest-risk/highest-traffic areas, then build a prioritized plan that you revise as hidden dependencies surface.

    'پرانے کوڈ میں مکمل ٹیسٹ شامل کرو' جیسے کام میں ہر ٹیسٹ پہلے سے گننے کی کوشش نہ کریں۔ ماڈیول کا ڈھانچہ سمجھیں، سب سے زیادہ خطرے/زیادہ استعمال والے حصے ڈھونڈیں، پھر ترجیح والا منصوبہ بنائیں جو چھپی جُڑی چیزیں سامنے آنے پر بدلتے رہیں۔

    1. map: list modules, entry points, coverage gaps
    2. rank: which untested areas carry the most risk?
    3. plan: order test work by impact; revise as dependencies appear

Edge Cases & Traps

  • A bigger context window does NOT fix attention dilution across many files — split the work instead.
  • Requiring 'consensus across N runs' suppresses real but intermittently-detected bugs.
1.7

Manage session state, resumption, and forking

Knowledge of

  • --resume <session-name> continues a specific prior conversation.

    In Claude Code, --resume <session-name> reopens a specific named session with its prior conversation history and tool results restored, so you continue exactly where you left off. Use it when you know the exact session you want — e.g. you worked on a feature yesterday, closed the terminal, and want to keep going today with the same context.

    Claude Code میں --resume <session-name> ایک خاص نام والا سیشن اس کی پچھلی گفتگو اور ٹول نتائج سمیت دوبارہ کھولتا ہے، تاکہ آپ بالکل وہیں سے جاری رکھیں۔ اسے تب استعمال کریں جب آپ کو مطلوبہ سیشن کا نام پتا ہو — مثلاً کل کسی feature پر کام کیا، ٹرمینل بند کیا، اور آج اسی سیاق کے ساتھ جاری رکھنا ہے۔

    # yesterday you worked in a session named 'auth-refactor'
    claude --resume auth-refactor
    # → reopens that session and continues from its history
    OptionMeaningUse when
    --resume <name>Continue a specific named sessionYou know the exact session you want
    --continueContinue the most recent sessionYou just want the latest one
    fork_sessionBranch from an existing sessionTry a different approach without touching the original
    New sessionStart freshOld context / tool results are stale
    Exam tip: "Continue exactly where they left off on a specific past task" ⇒ --resume <session-name>.
  • fork_session for creating independent branches from a shared analysis baseline to explore divergent approaches.

    Forking copies a session's state into a new branch so you can explore an alternative direction (a second refactor strategy, a different test approach) without altering the original. Both branches share the analysis you already did.

    Forking سیشن کی حالت ایک نئی شاخ میں نقل کر دیتا ہے تاکہ آپ کوئی الگ سمت آزما سکیں (دوسرا refactor طریقہ، الگ ٹیسٹ انداز) بغیر اصل کو بدلے۔ دونوں شاخیں وہ تجزیہ شیئر کرتی ہیں جو آپ پہلے کر چکے۔

    Exam tip: Compare two approaches from the same starting analysis ⇒ fork_session.
  • The importance of informing the agent about changes to previously analyzed files when resuming sessions after code modifications.

    If files changed since the session was last active, the restored tool results are stale. Tell the agent exactly what changed so it re-analyzes those files instead of trusting outdated reads.

    اگر سیشن کے آخری بار چلنے کے بعد فائلیں بدل گئیں، تو واپس آئے ٹول نتائج باسی ہیں۔ ایجنٹ کو ٹھیک ٹھیک بتائیں کیا بدلا تاکہ وہ پرانے reads پر بھروسے کے بجائے انہی فائلوں کا دوبارہ جائزہ لے۔

  • Why starting a new session with a structured summary is more reliable than resuming with stale tool results.

    When a lot has changed, resuming drags in outdated context that can mislead the model. A fresh session seeded with a clean, structured summary of the current state is often more reliable than reviving stale history.

    جب بہت کچھ بدل چکا ہو تو سیشن دوبارہ کھولنا پرانا سیاق گھسیٹ لاتا ہے جو ماڈل کو گمراہ کر سکتا ہے۔ موجودہ حالت کے صاف، منظم خلاصے سے شروع کیا نیا سیشن اکثر باسی تاریخ زندہ کرنے سے زیادہ بھروسے مند ہوتا ہے۔

Skills in

  • Use --resume with session names to continue named investigation sessions across work sessions.

    Name sessions after the work (auth-refactor, perf-audit) so you can pick the exact one back up days later with its history and tool results intact — instead of re-explaining the task or relying on --continue grabbing the wrong recent session.

    سیشن کا نام کام کے حساب سے رکھیں (auth-refactor، perf-audit) تاکہ کئی دن بعد بھی ٹھیک وہی سیشن اس کی تاریخ اور ٹول نتائج سمیت اٹھا سکیں — کام دوبارہ سمجھانے یا --continue کے غلط حالیہ سیشن اٹھا لینے کے بجائے۔

    claude --resume auth-refactor   # reopens that exact session's history
  • Use fork_session to create parallel exploration branches (e.g., comparing two testing strategies from a shared codebase analysis).

    Do the expensive analysis once, then fork so each branch explores a different approach from that shared baseline without contaminating the other. You compare outcomes that started from identical context.

    مہنگا تجزیہ ایک بار کریں، پھر fork کریں تاکہ ہر شاخ اسی مشترکہ بنیاد سے الگ طریقہ آزمائے بغیر دوسرے کو خراب کیے۔ آپ ایسے نتائج کا موازنہ کرتے ہیں جو ایک جیسے سیاق سے شروع ہوئے۔

    base = analyze_codebase()
    branch_a = fork_session(base)   # strategy: unit-test-first
    branch_b = fork_session(base)   # strategy: integration-test-first
  • Choose between session resumption (prior context mostly valid) and starting fresh with injected summaries (prior tool results stale).

    Resuming replays old tool results as if still true. That's a win when little changed, but a liability after big edits — the model trusts stale reads. When a lot changed, a fresh session seeded with a clean summary of current state is more reliable.

    سیشن دوبارہ کھولنا پرانے ٹول نتائج کو ایسے دہراتا ہے جیسے اب بھی سچ ہوں۔ جب کم بدلا ہو تو یہ فائدہ ہے، مگر بڑی تبدیلیوں کے بعد نقصان — ماڈل باسی reads پر بھروسہ کرتا ہے۔ جب بہت بدلا ہو تو موجودہ حالت کے صاف خلاصے والا نیا سیشن زیادہ بھروسے مند ہے۔

    SituationChoice
    Prior context still mostly validResume the session
    Prior tool results are stale / much changedStart fresh + inject a structured summary
  • Inform a resumed session about specific file changes for targeted re-analysis rather than requiring full re-exploration.

    When you do resume after edits, tell the agent exactly which files changed so it re-reads just those instead of trusting stale results or re-scanning the whole repo. Precise deltas keep the run fast and correct.

    جب تبدیلیوں کے بعد سیشن دوبارہ کھولیں، تو ایجنٹ کو ٹھیک بتائیں کون سی فائلیں بدلیں تاکہ وہ صرف انہی کو دوبارہ پڑھے، باسی نتائج پر بھروسے یا پورا repo دوبارہ سکین کرنے کے بجائے۔ صاف فرق بتانا کام تیز اور درست رکھتا ہے۔

    "Resuming: since last session, auth/token.py and auth/middleware.py changed.
     Re-read those two before continuing; the rest is unchanged."

Edge Cases & Traps

  • Resuming with stale tool outputs can mislead the model — prefer a fresh session with a clean summary when things changed a lot.

🧠 Knowledge Check · 38 questions

Score: 0/38

1.In an agentic loop, what should determine whether your code runs another tool or presents the final answer?

2.A coordinator delegates to a synthesis subagent but it ignores the earlier web-search findings. What's the most likely cause?

3.You need refunds to be impossible to process before a customer's identity is verified. Which approach gives a guarantee?

4.How do you spawn multiple subagents to run in parallel?

5.A research report covers only visual arts and misses music, writing, and film — yet every subagent completed successfully. Where is the root cause?

6.A developer worked in a Claude Code session named billing-refactor yesterday and wants to continue exactly where they left off today. What should they use?

7.You've executed the tools Claude requested and appended their results to the message history. What must the loop do next?

8.A loop stops as soon as any tool returns an empty string. Why is that wrong?

9.A response comes back with stop_reason: "max_tokens". What does it mean?

10.Which statement best describes model-driven decision-making in an agentic loop?

11.Where does a maximum-iteration cap belong in a well-designed agentic loop?

12.In a hub-and-spoke multi-agent system, why route all subagent communication through the coordinator?

13.A synthesis subagent returns a report missing whole subtopics, yet every subagent completed successfully. Where do you look first?

14.In a dynamic multi-agent system, what does the coordinator decide?

15.To minimize duplicated work across research subagents, you should…

16.A coordinator never spawns any subagents. What is the most likely cause?

17.How do you make three subagents run in parallel?

18.Why pass web-search results to a synthesis subagent using a structured format that separates content from metadata (URLs, page numbers)?

19.How should a synthesis subagent obtain the earlier web-search findings?

20.A coordinator prompt spells out exact step-by-step procedures for a research subagent. What is the downside?

21.Refunds must be impossible before a customer's identity is verified. Which approach guarantees it?

22.Why are prompt instructions insufficient for deterministic compliance such as identity-before-refund?

23.When escalating mid-process to a human who lacks the transcript, a good structured handoff includes…

24.A single customer message raises three distinct issues. The best pattern is to…

25.Which hook type intercepts tool RESULTS to transform them before the model processes them?

26.You must guarantee refunds over $500 are blocked. What is the right mechanism?

27.MCP tools return timestamps as Unix, ISO 8601, and numeric codes. How do you normalize them for the model?

28.A large code review suffers from attention dilution. What actually helps?

29.When is fixed prompt chaining preferable to dynamic decomposition?

30.How should you decompose an open-ended investigation of an unfamiliar codebase?

31.A developer wants to continue a specific named session billing-refactor from yesterday. Which command?

32.You want to compare two testing strategies starting from the same codebase analysis. What do you use?

33.You resume a session, but files it previously analyzed were modified since. What is the reliable move?

34.A coordinator is supposed to delegate research to subagents, but no delegation ever happens and there are no errors. What should you check FIRST?

35.Three research subagents each fetch many of the same sources, wasting cost. What's the fix?

36.After one synthesis pass, the report is missing a whole subtopic. What does an iterative-refinement coordinator do?

37.A policy states refunds over $500 must ALWAYS route to a human. Which mechanism guarantees it?

38.You want to compare two refactoring strategies from the SAME expensive codebase analysis, without one contaminating the other. Best tool?