AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 39

    Multi-Step AI Workflows and Orchestration

    The support tools and the run row were in place.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 39 · AI Agents, Workflow Automation and Integrations

    Lesson Overview

    The support tools and the run row were in place. A prototype then let the model pick the next tool until it said it was done. One stuck-enrollment message produced eleven model calls. The lookup timed out on call four. Call seven drafted "I have resolved ticket TCK-1042 and issued the refund." No pending review existed. A staff retry ran the loop again and opened two review rows, because each loop minted a new idempotency key from the current clock.

    Orchestration in this lesson is a server-owned sequence for one job: stuck enrollment on a single ticket. The model may classify the staff message as lookup, refund_request, or unknown, and it may phrase a draft after a successful lookup. It does not choose the next step, the tenant, or the key. A multi-step workflow is that sequence plus the budgets that stop it: four steps, two model calls, eight seconds. A failed lookup does not continue into a draft that claims a status the store did not return.

    The pieces you already have stay in their packages. Proposals and the allowlist are lesson 36. The registry, the timeout, and the pending review are lesson 37. The run, the revision, and the preface are lesson 38. This lesson calls those functions in an order the code lists. Workflow Orchestration, Sequential Workflows, and AI Workflow Basics name the same idea. A graph library can draw the edges later. The edges that matter this week are the function calls below.

    Lesson 40 will map a fixed sequence and a stateful graph onto library concepts. This lesson does not import a framework and does not construct a vendor agent class. When a document names a chain, read "a fixed sequence of steps." When it names a graph, read "a state machine whose edges your code can list." The allowlist, the timeout, and the approval row stay in your process either way.

    The course home is AI-Powered Full Stack Development.

    Planning assumptions, labeled so they are not a throughput target:

    • Ticket ids in the staff message match TCK- plus 4 to 8 digits. Zero matches is missing_ticket. Two different matches is ambiguous_ticket. The classifier is not asked to pick between them.
    • maxSteps is 4. maxModelCalls is 2. wallClockMs is 8,000. Exceeding any of them returns step_budget or time_budget and does not start another tool.
    • The workflow key is organizationId:ticketId:intent:support-agent-v1. A second call with the same key returns the stored result and does not call the classifier again.
    • refund_request opens open_refund_review through the registry. It does not call a draft model. The console shows the pending review id.
    • lookup may call the classifier once and a drafter once, and only after the registry returns a view.
    • Tests inject ClassifyPort, DraftPort, the tool context, and a result store. No credential and no process.env.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Explain why a stuck-enrollment job is a fixed workflow, and when an open tool loop would still be the wrong default.
    2. Extract at most one ticket id from the staff message with a deterministic pattern.
    3. Classify intent into lookup, refund_request, or unknown through a port that returns a label, not a tool name.
    4. Run steps in code order: validate, classify, lookup, then either draft or open a review.
    5. Stop on lookup timeout or not_found without a draft that states a ticket status.
    6. Open a pending review only for support_lead, and return forbidden_role for an agent without inserting a second kind of refund.
    7. Enforce maxSteps, maxModelCalls, and a wall clock, and count a port call against the model budget.
    8. Reuse an idempotency key so a retry returns the original result and does not call the classifier again.
    9. Record completed step names on failure so the console can say which step stopped.
    10. Commit the outcome onto the lesson 38 run only after the workflow result exists, using that lesson's revision.
    11. Keep settlement, customer email, and lesson progress out of the workflow.
    12. Test the timeout path, the ambiguous id, the idempotent replay, the agent refund refusal, and the model-call cap without a network call.

    Prerequisites

    If an agent loop is already running in production against support tools, put this workflow in front of the refund path before you raise its step limit.

    Detailed Core Concepts

    The server owns the arrows

    An open loop asks the model, "given the tools, what next?" That is useful when the goal is underspecified and every tool is a reversible read. Stuck enrollment is specified. Staff already said which ticket, or they did not. They asked for a lookup, or they asked for a refund, or the message is unclear. The application can branch on those three labels.

    DecisionOwner in this workflow
    Which ticket idA regex on the staff message. Two ids stop the run
    Which intentClassifyPort, parsed as one of three labels
    Whether to read the ticketAlways, after a single id, before any draft or review
    Whether to draftOnly after a lookup view, and only for intent lookup
    Whether to open a reviewIntent refund_request, caller role support_lead, lookup succeeded
    Whether to stopBudget, typed tool error, or a stored result

    The model owns the wording of a draft and the choice among three labels. It does not own the arrows. Planning and Reasoning and Task Decomposition describe how models split work. Use them when you are exploring a problem. For this queue, the split is already written down, which is what makes the timeout path testable: you can assert that draft was not called.

    A graph is still a good picture. The nodes are extract, classify, lookup, draft, review, and stop. The edges are if statements. A library that persists those nodes is optional. Persisting the result under the workflow key is not optional, because that is what makes the retry safe.

    Idempotency is the reply to the double review

    The key is:

    text
    ${organizationId}:${ticketId}:${intent}:${promptVersion}

    promptVersion is support-agent-v1 from lesson 36. A policy change that should not reuse old results bumps the version and therefore the key. The organization is in the key so two tenants with the same ticket id do not share a result.

    The result store's putIfAbsent returns the first result. The listing classifies first, because the intent is part of the key and the message is the only source of that label. A retry therefore spends one classify call, then hits the store and skips lookup, draft, and review. The stored object comes back with replayed: true. The first call still pays for the tools it ran. The retry does not pay for them again. The assignment's message-hash index is how you skip the classify as well.

    Do not put Date.now() in the key. That was the eleven-call prototype's second bug: every retry looked like a new job. Do not put the draft text in the key either. The draft is an output. The key is the job identity.

    Agents and leads who run lookup share a key shape and do not share a row across organizations. A lead's refund_request key differs in the intent segment, so a lookup result is not returned as a review. That split is deliberate. The staff member asked for two different jobs.

    Budgets you can assert

    maxSteps counts extract, classify, lookup, and draft or review. Four is enough for the happy path and too small for a hidden fifth "reflect and try another tool" step. If you need reflection, you are in a different product, and you should raise the constant in review rather than recurse inside draft.

    maxModelCalls counts ClassifyPort and DraftPort only. Registry calls are not model calls. A refund path spends one model call (classify) and zero drafter calls. A lookup path spends two. A replay spends one classify and zero tool calls. A test can assert the counters.

    wallClockMs wraps the whole function. A lookup that consumes the tool timeout still has to leave the workflow inside the wall clock, or the workflow returns time_budget and records the steps it finished. The lab sets the wall clock to 8 seconds and the lookup timeout to 1.5 seconds, so a single hung lookup returns the tool's timeout, which the workflow surfaces as lookup_timeout, with steps ["extract", "classify", "lookup"]. It does not start the drafter.

    Retry Mechanisms belong on idempotent steps when you have measured a transient failure. This workflow does not retry internally. The staff member's second click is the retry, and the key makes it cheap. An internal retry of classify would spend the model budget twice and could disagree with itself.

    Failure is a result with a step list

    text
    lookup_timeout steps: extract, classify, lookup
    lookup_not_found steps: extract, classify, lookup
    ambiguous_ticket steps: extract
    missing_ticket steps: extract
    forbidden_role steps: extract, classify, lookup
    step_budget steps: whatever completed

    The console names the step. It does not fill in a ticket status from memory. A draft is attached only to { ok: true, intent: "lookup" }. The type has no optional draft on the error side, so a template cannot render "resolved" beside lookup_timeout.

    unknown intent returns a successful result whose text is a fixed string: "Which ticket should I look up, and do you need a lookup or a refund review?" That string is a constant in the workflow, not a model sample. Spending a generation to ask a clarifying question is how the budget disappears on messages that were never actionable. Decision Trees is the agentic-track name for this kind of branch. The constant is the leaf.

    Role and registry stay in charge

    The workflow calls executeSupportTool. It does not open a second client to the ticket table. An agent who sends refund_request gets forbidden_role from the registry after the lookup succeeds. The lookup is still useful: the console can show the ticket and tell the agent to hand the refund to a lead. The workflow does not upgrade the agent to a lead to "finish the flow."

    A lead's review uses the registry's idempotency key as well as the workflow key. Replaying the workflow returns the stored workflow result. Replaying the tool inside a first attempt returns the same pending review. Two layers are correct. The workflow key avoids a second classify. The review key avoids a second pending row if the workflow store fails after the review insert and the lead clicks again before the workflow result is saved. Order the writes so the review insert happens before the workflow putIfAbsent of a success. If the process dies between them, the retry classifies once, calls the tool, receives the same review id, and stores the workflow result. It does not create a second review.

    What the workflow does not prove

    A green test proves the arrows, the budgets, and the replay. It does not prove the classifier's label matches staff intent on real traffic. Log the label, the ticket id, the organization, and the prompt version. Score the label on a fixed set of staff messages with lesson 18's harness. A wrong label that still passes the shell is a model-quality bug. A draft that appears after lookup_timeout is a workflow bug. Keep those bugs in different queues.

    Customer email is still unsent. Lesson 20 sends it after approval, through the executor, with its own idempotency key. This workflow's success type for refund_request carries reviewId and status: "pending_review". It does not carry emailed: true.

    Architecture and Request Flow

    The browser posts the staff message and the run id. The API builds SupportCaller, loads the run through lesson 38, and starts the workflow. Ticket ids inside the message are candidates for the regex. They are not an organization.

    flowchart TB
      subgraph browser [Browser]
        Box[Staff message on a run]
      end
    
      subgraph api [TechLearningPro API]
        Auth[Session caller]
        Wf[runStuckEnrollment]
        Steps[extract classify lookup branch]
      end
    
      subgraph deps [Ports and registry]
        Cls[ClassifyPort]
        Draft[DraftPort]
        Tools[executeSupportTool]
        Saved[Workflow result store]
      end
    
      Box --> Auth
      Auth --> Wf
      Wf --> Saved
      Wf --> Steps
      Steps --> Cls
      Steps --> Tools
      Steps --> Draft
      Tools --> Saved
      Draft --> Saved
      Saved --> Box

    Draft is reached only from the lookup branch. Tools for open_refund_review is reached only from the refund branch. Settlement is not in the diagram.

    flowchart LR
      E[Extract one ticket id] --> C[Classify]
      C -->|unknown| Q[Ask with a constant]
      C -->|lookup or refund| L[lookup_ticket]
      L -->|error| Stop[typed failure plus steps]
      L -->|view and lookup| D[Draft within budget]
      L -->|view and refund| R{Role is lead}
      R -->|yes| P[pending review]
      R -->|no| F[forbidden_role]

    Failure points: no ticket id, two ticket ids, classifier timeout, unknown label, lookup timeout, lookup miss, agent attempting a review, draft timeout, step budget, wall clock, and a replay that must not be treated as a failure. The replay is a success that returns the stored object.

    Trust boundaries:

    • The staff message is untrusted. The regex takes ids from it. The classifier sees it as data.
    • The classifier output is untrusted until Zod accepts one of three labels.
    • The registry remains the trust boundary for rows.
    • The workflow store is tenant-scoped by the key's organization segment and by a row column you set from caller.organizationId. A key alone, if you ever forget the column, is not the whole isolation story. Write both. Test both.

    Step-by-step Implementation

    The slice lives in packages/support-agent/src/workflow.ts and compiles with strict. It calls executeSupportTool from lesson 37. Ports are interfaces you can fake.

    Step 1: Ports, budgets, and results

    typescript
    import { z } from "zod";
    import { executeSupportTool, type ToolContext } from "./tools.js";
    import { PROMPT_VERSION } from "./propose.js";
    import type { SupportCaller } from "./types.js";
    export const MAX_STEPS = 4;
    export const MAX_MODEL_CALLS = 2;
    export const WALL_CLOCK_MS = 8_000;
    const TicketPattern = /\bTCK-\d{4,8}\b/g;
    const IntentSchema = z.enum(["lookup", "refund_request", "unknown"]);
    export type WorkflowIntent = z.infer<typeof IntentSchema>;
    export interface ClassifyPort {
    classify(input: {
    caller: SupportCaller;
    staffMessage: string;
    ticketId: string;
    timeoutMs: number;
    }): Promise<{ ok: true; intent: unknown } | { ok: false; reason: "timeout" | "unavailable" | "unparseable" }>;
    }
    export interface DraftPort {
    draft(input: {
    caller: SupportCaller;
    ticketId: string;
    status: string;
    subject: string;
    timeoutMs: number;
    }): Promise<{ ok: true; text: string } | { ok: false; reason: "timeout" | "unavailable" | "unparseable" }>;
    }
    export interface WorkflowRecord {
    key: string;
    organizationId: string;
    result: WorkflowSuccess;
    }
    export interface WorkflowStore {
    get(key: string, organizationId: string): Promise<WorkflowRecord | null>;
    putIfAbsent(record: WorkflowRecord): Promise<WorkflowRecord>;
    }
    export interface WorkflowSuccess {
    intent: WorkflowIntent;
    ticketId: string | null;
    replayed: boolean;
    reviewId?: string;
    draftText?: string;
    steps: string[];
    }
    export type WorkflowFailure =
    | "missing_ticket"
    | "ambiguous_ticket"
    | "classify_failed"
    | "lookup_timeout"
    | "lookup_not_found"
    | "lookup_failed"
    | "forbidden_role"
    | "draft_failed"
    | "step_budget"
    | "time_budget";
    export type WorkflowResult =
    | { ok: true; value: WorkflowSuccess }
    | { ok: false; reason: WorkflowFailure; steps: string[] };

    DraftPort receives status and subject from the lookup view. It does not receive a free-form tool list. There is nothing for it to call. The draft text is stored on the success value and labeled by the console as a draft, using the same rule as lesson 36.

    Step 2: The sequence

    typescript
    const UNKNOWN_TEXT = "Which ticket should I look up, and do you need a lookup or a refund review?";
    function extractTicketId(message: string): { ok: true; ticketId: string } | { ok: false; reason: "missing_ticket" | "ambiguous_ticket" } {
    const found = new Set(message.match(TicketPattern) ?? []);
    if (found.size === 0) return { ok: false, reason: "missing_ticket" };
    if (found.size > 1) return { ok: false, reason: "ambiguous_ticket" };
    return { ok: true, ticketId: [...found][0] };
    }
    function workflowKey(caller: SupportCaller, ticketId: string, intent: WorkflowIntent): string {
    return [caller.organizationId, ticketId, intent, PROMPT_VERSION].join(":");
    }
    export interface WorkflowInput {
    caller: SupportCaller;
    staffMessage: string;
    now: () => number;
    }
    export async function runStuckEnrollment(
    classify: ClassifyPort,
    draft: DraftPort,
    tools: ToolContext,
    store: WorkflowStore,
    input: WorkflowInput,
    ): Promise<WorkflowResult> {
    const started = input.now();
    const steps: string[] = [];
    let modelCalls = 0;
    const expired = () => input.now() - started > WALL_CLOCK_MS;
    const bump = (step: string): WorkflowResult | null => {
    if (steps.length >= MAX_STEPS) return { ok: false, reason: "step_budget", steps: steps.slice() };
    steps.push(step);
    if (expired()) return { ok: false, reason: "time_budget", steps: steps.slice() };
    return null;
    };
    const extracted = extractTicketId(input.staffMessage);
    const stop = bump("extract");
    if (stop) return stop;
    if (!extracted.ok) return { ok: false, reason: extracted.reason, steps };
    const ticketId = extracted.ticketId;
    if (modelCalls >= MAX_MODEL_CALLS) return { ok: false, reason: "step_budget", steps };
    modelCalls += 1;
    const classified = await classify.classify({
    caller: input.caller,
    staffMessage: input.staffMessage,
    ticketId,
    timeoutMs: 2_000,
    });
    const afterClass = bump("classify");
    if (afterClass) return afterClass;
    if (!classified.ok) return { ok: false, reason: "classify_failed", steps };
    const intentParsed = IntentSchema.safeParse(classified.intent);
    if (!intentParsed.success) return { ok: false, reason: "classify_failed", steps };
    const intent = intentParsed.data;
    if (intent !== "unknown") {
    const key = workflowKey(input.caller, ticketId, intent);
    const existing = await store.get(key, input.caller.organizationId);
    if (existing) return { ok: true, value: { ...existing.result, replayed: true } };
    }
    if (intent === "unknown") {
    return {
    ok: true,
    value: { intent, ticketId, replayed: false, draftText: UNKNOWN_TEXT, steps },
    };
    }
    const lookup = await executeSupportTool(tools, "lookup_ticket", { ticketId });
    const afterLookup = bump("lookup");
    if (afterLookup) return afterLookup;
    if (!lookup.ok) {
    if (lookup.reason === "timeout") return { ok: false, reason: "lookup_timeout", steps };
    if (lookup.reason === "not_found") return { ok: false, reason: "lookup_not_found", steps };
    return { ok: false, reason: "lookup_failed", steps };
    }
    if (lookup.effect !== "read") return { ok: false, reason: "lookup_failed", steps };
    if (intent === "refund_request") {
    const review = await executeSupportTool(tools, "open_refund_review", { ticketId });
    if (!review.ok) {
    if (review.reason === "forbidden_role") return { ok: false, reason: "forbidden_role", steps };
    return { ok: false, reason: "lookup_failed", steps };
    }
    if (review.effect !== "write") return { ok: false, reason: "lookup_failed", steps };
    const afterReview = bump("review");
    if (afterReview) return afterReview;
    const value: WorkflowSuccess = {
    intent,
    ticketId,
    replayed: false,
    reviewId: review.review.id,
    steps,
    };
    const key = workflowKey(input.caller, ticketId, intent);
    await store.putIfAbsent({ key, organizationId: input.caller.organizationId, result: value });
    return { ok: true, value };
    }
    if (modelCalls >= MAX_MODEL_CALLS) return { ok: false, reason: "step_budget", steps };
    modelCalls += 1;
    const drafted = await draft.draft({
    caller: input.caller,
    ticketId,
    status: lookup.view.status,
    subject: lookup.view.subject,
    timeoutMs: 3_000,
    });
    const afterDraft = bump("draft");
    if (afterDraft) return afterDraft;
    if (!drafted.ok || drafted.text.trim().length === 0) return { ok: false, reason: "draft_failed", steps };
    const value: WorkflowSuccess = {
    intent,
    ticketId,
    replayed: false,
    draftText: drafted.text.trim(),
    steps,
    };
    const key = workflowKey(input.caller, ticketId, intent);
    await store.putIfAbsent({ key, organizationId: input.caller.organizationId, result: value });
    return { ok: true, value };
    }

    A retry of a finished job spends one classify call, then hits the store and skips lookup and draft. The lead test below checks that the review id is unchanged and that the review map stays at one row.

    If that classify is more than you want to pay, store a second index from the organization id and a hash of the normalized staff message to the workflow key after success, and consult it before classify. The assignment's challenge is that index. Until it exists, replay cost is one classify and zero registry calls.

    unknown is not stored. Two unknown messages should both return the constant. Storing them would pin a typo to a ticket forever under a key that includes unknown.

    After a successful workflow, the API commits a lesson 38 observation or draft with expectedRevision. This function does not increment the revision itself, so a workflow success cannot skip the conflict check. If commit returns revision_conflict, the staff member reloads. The workflow result remains in the store. You do not run the tools again to "match the tab."

    Step 3: How you run the lab

    1. Seed org_01 / TCK-1042 in the lesson 37 store.
    2. Classify port returns lookup. Draft port returns a fixed sentence. Assert steps include draft and the review store is empty.
    3. Classify port returns refund_request. Call as agent. Assert forbidden_role and an empty review map.
    4. Call as lead. Assert one pending review and amountCents from the ticket.
    5. Call the lead path again. Assert the review map is still size 1 and the draft port's counter is 0.
    6. Hang the ticket store. Assert lookup_timeout and a draft counter of 0.
    7. Pass a message with TCK-1042 and TCK-1001. Assert ambiguous_ticket and a classify counter of 0.

    There is nothing to clean up.

    Security

    The workflow adds a budget and a key. It does not add a privilege.

    • Ticket ids come from the regex. The classifier is told the id you extracted. If it returns a different id inside a label, Zod fails the label, because the schema is an enum and has no id field. A model that tries to switch tickets fails classify_failed.
    • Lookup and review go through executeSupportTool. The workflow does not pass caller.organizationId as a tool argument. The tool context already holds the caller.
    • forbidden_role stops the refund branch after a lookup. The lookup view is not written into a review.
    • Replay reads the workflow store with both the key and organizationId. Implement get so a key minted for org_02 is invisible to org_01 even if the key string is pasted. The test for that is in the assignment.
    • Draft text is untrusted display text. The success type does not include an effect flag. The console uses the lesson 36 draft label whenever draftText is present and reviewId is absent.
    • Logs include the key, the steps, the reason, the organization id, and the ticket id. They omit the staff message and the draft body. The message may contain a learner email the regex did not ask for.
    • A wall-clock abort does not cancel a review that already committed. The review's own idempotency key covers the retry. Say that in the runbook so on-call does not delete the pending row as a "partial failure."

    Enterprise Workflow Design on the agentic track is the longer operational frame. The constants at the top of workflow.ts are the frame you can diff in review.

    Error Handling

    ReasonStaff seesDraft portReview row
    missing_ticket, ambiguous_ticketAsk for one ticket idNot calledNo
    classify_failed"The assistant is unavailable"Not calledNo
    lookup_timeout, lookup_not_found, lookup_failedThe lookup status, no resolution claimNot calledNo
    forbidden_role"A lead has to open the refund review"Not calledNo
    draft_failedTicket view from the lookup, no generated paragraphCalled onceNo
    step_budget, time_budget"Stopped at a budget" plus the step listOnly if already calledOnly if already inserted
    Success lookupLabeled draftCalled onceNo
    Success refundPending review idNot calledOne row
    ReplayThe stored success, marked replayedNot calledUnchanged

    draft_failed still leaves the lookup view available to the route if you return the view beside the error. The listing returns the reason and the steps. Extend the error type with an optional ticketStatus copied from the view if the console must show it. Copy it from the registry result you already hold. Do not call the model to describe the failure.

    One staff click is one workflow invocation. A second click is a replay when the key matches. Do not wrap runStuckEnrollment in a retry loop.

    Testing and Evaluation

    packages/support-agent/src/workflow.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { runStuckEnrollment, type ClassifyPort, type DraftPort, type WorkflowRecord, type WorkflowStore } from "./workflow.js";
    import type { PendingReview, TicketRecord, ToolContext } from "./tools.js";
    import type { SupportCaller } from "./types.js";
    function ticket(): TicketRecord {
    return {
    organizationId: "org_01",
    ticketId: "TCK-1042",
    status: "open",
    courseId: "course_01",
    amountCents: 8_000,
    subject: "Enrollment stuck",
    body: "Please refund.",
    };
    }
    function context(caller: SupportCaller, hang: boolean): { tools: ToolContext; reviews: Map<string, PendingReview> } {
    const reviews = new Map<string, PendingReview>();
    const tools: ToolContext = {
    caller,
    now: () => 1,
    tickets: {
    async get(organizationId, ticketId) {
    if (hang) return new Promise(() => undefined);
    if (organizationId === "org_01" && ticketId === "TCK-1042") return ticket();
    return null;
    },
    },
    reviews: {
    async putIfAbsent(review) {
    const existing = reviews.get(review.idempotencyKey);
    if (existing) return existing;
    reviews.set(review.idempotencyKey, review);
    return review;
    },
    },
    };
    return { tools, reviews };
    }
    function store(): WorkflowStore & { records: WorkflowRecord[] } {
    const records: WorkflowRecord[] = [];
    return {
    records,
    async get(key, organizationId) {
    return records.find((row) => row.key === key && row.organizationId === organizationId) ?? null;
    },
    async putIfAbsent(record) {
    const existing = records.find((row) => row.key === record.key && row.organizationId === record.organizationId);
    if (existing) return existing;
    records.push(record);
    return record;
    },
    };
    }
    const agent: SupportCaller = { organizationId: "org_01", userId: "usr_agent", role: "support_agent" };
    const lead: SupportCaller = { organizationId: "org_01", userId: "usr_lead", role: "support_lead" };
    function classify(intent: string, hits: { n: number }): ClassifyPort {
    return {
    async classify() {
    hits.n += 1;
    return { ok: true, intent };
    },
    };
    }
    function drafts(hits: { n: number }): DraftPort {
    return {
    async draft() {
    hits.n += 1;
    return { ok: true, text: "The ticket is open. I have not issued a refund." };
    },
    };
    }
    test("drafts only after a lookup and does not open a review", async () => {
    const model = { n: 0 };
    const drafted = { n: 0 };
    const { tools, reviews } = context(agent, false);
    const result = await runStuckEnrollment(
    classify("lookup", model),
    drafts(drafted),
    tools,
    store(),
    { caller: agent, staffMessage: "Please check TCK-1042", now: () => 0 },
    );
    assert.equal(result.ok, true);
    if (result.ok) {
    assert.equal(result.value.draftText?.includes("have not issued a refund"), true);
    assert.equal(result.value.reviewId, undefined);
    assert.deepEqual(result.value.steps, ["extract", "classify", "lookup", "draft"]);
    }
    assert.equal(model.n, 1);
    assert.equal(drafted.n, 1);
    assert.equal(reviews.size, 0);
    });
    test("does not draft when lookup hangs", async () => {
    const drafted = { n: 0 };
    const { tools } = context(agent, true);
    const result = await runStuckEnrollment(
    classify("lookup", { n: 0 }),
    drafts(drafted),
    tools,
    store(),
    { caller: agent, staffMessage: "Please check TCK-1042", now: () => 0 },
    );
    assert.equal(result.ok, false);
    if (!result.ok) assert.equal(result.reason, "lookup_timeout");
    assert.equal(drafted.n, 0);
    });
    test("refuses an agent refund and lets a lead open one review", async () => {
    const agentTools = context(agent, false);
    const denied = await runStuckEnrollment(
    classify("refund_request", { n: 0 }),
    drafts({ n: 0 }),
    agentTools.tools,
    store(),
    { caller: agent, staffMessage: "Refund TCK-1042", now: () => 0 },
    );
    assert.equal(denied.ok, false);
    if (!denied.ok) assert.equal(denied.reason, "forbidden_role");
    assert.equal(agentTools.reviews.size, 0);
    const leadTools = context(lead, false);
    const memory = store();
    const opened = await runStuckEnrollment(
    classify("refund_request", { n: 0 }),
    drafts({ n: 0 }),
    leadTools.tools,
    memory,
    { caller: lead, staffMessage: "Refund TCK-1042", now: () => 0 },
    );
    const replay = await runStuckEnrollment(
    classify("refund_request", { n: 0 }),
    drafts({ n: 0 }),
    leadTools.tools,
    memory,
    { caller: lead, staffMessage: "Refund TCK-1042", now: () => 0 },
    );
    assert.equal(opened.ok && replay.ok, true);
    if (opened.ok && replay.ok) assert.equal(replay.value.reviewId, opened.value.reviewId);
    assert.equal(leadTools.reviews.size, 1);
    });
    test("stops before classify when two ticket ids are present", async () => {
    const model = { n: 0 };
    const { tools } = context(agent, false);
    const result = await runStuckEnrollment(
    classify("lookup", model),
    drafts({ n: 0 }),
    tools,
    store(),
    { caller: agent, staffMessage: "Compare TCK-1042 and TCK-1001", now: () => 0 },
    );
    assert.deepEqual(result, { ok: false, reason: "ambiguous_ticket", steps: ["extract"] });
    assert.equal(model.n, 0);
    });

    The hang test waits on lesson 37's 1,500 ms lookup timeout. That is acceptable in node:test. If you inject timeouts, keep the assertion that the draft counter stays 0.

    Add two tests before you call the lesson done. A message with no ticket id returns missing_ticket and does not classify. A workflow store row saved under org_02 is not returned to an org_01 caller who somehow presents the same key string. Also assert unknown returns the constant text and does not call executeSupportTool. You can observe that by hanging the store: an unknown intent must not hang.

    The draft sentence in the fake includes "have not issued a refund" so the test locks the fixture, not a live model. A real drafter can say something else. The shell's claim is that the sentence is absent when lookup times out, and that a review id is absent on the lookup path.

    Performance and Cost

    Two model calls and one indexed lookup are the planned bill for the common path. The eleven-call loop was the unplanned bill.

    • maxModelCalls is 2. Classify is the first. Draft is the second, and only for lookup. Refund work must not spend the draft call "to explain the review." The pending id is the explanation.
    • The wall clock is 8 seconds, aligned with the short-draft budget from lesson 23. Staff still have the ticket screen if the workflow stops.
    • Replay after a stored success skips lookup and draft. Put the store lookup as early as your key allows. The challenge index, keyed by the message hash, skips classify too.
    • Do not parallelize lookup and classify. Classify does not need the ticket body. Lookup does not need the label to know the id. You could run them together and save latency. You would also look up tickets for messages you then classify as unknown, and you would look up before you know the call is a replay. Sequential order keeps the illegal and the duplicate paths cheap. Latency for the happy path is classify plus lookup plus an optional draft. Measure it before you add concurrency.
    • Do not send the ticket body to DraftPort. The listing sends status and subject. The body stays on the ticket screen. That choice drops input tokens and keeps learner text out of the drafter's provider log. If staff need a drafted quote, pass a capped body in a later version and bump PROMPT_VERSION, which changes the workflow key.
    • Illustrative, not a quote: a lookup job bills one classify, one ticket read, and one short draft. A refund job bills one classify, one ticket read, and one review insert. A replay bills one classify until you add the message-hash index, then zero. A hung lookup bills one classify and zero drafts.

    AI Cost Optimization is the survey. The counters in the tests are the control.

    Knowledge Check

    1. What problem does this capability solve?

    It walks one stuck-enrollment message through a fixed sequence: one ticket id, one intent label, one scoped lookup, then either a draft or a pending review. The open loop spent eleven model calls and claimed a refund after a timeout. The workflow stops when the lookup fails, and a retry returns the stored result instead of a second review.

    2. What alternatives exist, and when would you choose each?

    Use a single lookup button when staff already selected the ticket on screen. Use lesson 36's one-shot proposal when you only need a draft or a suggestion to look up. Use an open tool loop when the next read is genuinely conditional and every tool is reversible, with a step cap you are willing to defend. Use this workflow when the job is stuck enrollment and the branches fit on one diagram. Use a graph library when you need to persist those same branches across workers. The library does not replace the key, the role check, or the registry.

    3. Which data, identity, and trust boundaries matter?

    The session supplies the caller. The regex supplies at most one ticket id. The classifier supplies an enum. The registry supplies the row and the pending review. The workflow store supplies the replay, scoped by organization. The run revision in lesson 38 supplies the tab lock after the result exists. The executor supplies settlement, later, outside this function.

    4. What can fail, and how should the system respond?

    Missing and ambiguous ids stop before the classifier. Classifier and draft failures stop as typed reasons. Lookup timeout and miss stop without a draft. Agents asking for a refund receive forbidden_role. Budgets stop the function with the step list. A second click on a finished job returns the stored success. A timeout after a review insert is repaired by the review key, not by deleting the row.

    5. How would you test quality, security, performance, and cost?

    Tests cover a lookup draft with an empty review map, a hung lookup with a draft counter of zero, an agent refund refusal, a lead replay with one review id, and two ticket ids that never classify. Security review checks the organization column on the workflow store. Performance review checks the step cap and the sequential order. Cost review checks model-call counts: one plus one for lookup, one plus zero for refund, and no draft on failure. Label quality is a separate eval on frozen messages.

    Hands-on Assignment

    Lab note. Use the fakes from this lesson. Do not create a provider account, a billing credential, or a framework project.

    Problem. Ship the stuck-enrollment workflow: one ticket, three intents, registry calls only, budgets, and an idempotent result.

    Tasks.

    1. Draw the diagram with your step names. Mark the executor as unwired.
    2. Implement extractTicketId, runStuckEnrollment, and the workflow store.
    3. Add the tests in this lesson plus missing_ticket, the unknown intent that does not touch the ticket store, and the cross-organization store miss.
    4. Write six rows: control, owner, evidence. Include the regex, the intent enum, the registry call, the model-call cap, the workflow key, and the absence of a draft after lookup_timeout.
    5. State the staff-visible copy for ambiguous_ticket, lookup_timeout, forbidden_role, and a pending review.
    6. After a success, commit the draft or the review id through lesson 38's commit using expectedRevision. Show the revision_conflict path without running the tools a second time.

    Deliverable. Diagram, source with no secrets, test output, the six-row control table, and a short note on why the workflow key includes the prompt version.

    Challenge. Add a message-hash index so a replay does not call ClassifyPort. The hash covers organization id, ticket id, intent is unknown at that moment, so hash organization id plus the normalized staff message. Show that a changed message misses the index and classifies again, and that org_02 cannot read org_01's index entry.

    Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.

    Common Mistakes

    1. Letting the model pick the next tool. Symptom: a timeout is followed by a draft that says the ticket was resolved. Cause: the loop treated any completion as permission to continue. Fix: the draft call sits after a successful lookup in code, not after "the model thought it should."
    2. Minting a new idempotency key per click. Symptom: two pending reviews for one lead action. Cause: the key included the clock. Fix: organization, ticket id, intent, and prompt version. Keep the review key from lesson 37 as the second layer.
    3. Asking the model to choose among two ticket ids. Symptom: the workflow reads the ticket the model preferred, which belonged to a different learner mentioned in the paste. Cause: extract was "helpful." Fix: ambiguous_ticket and zero tool calls.
    4. Drafting the refund. Symptom: the model bill includes a long email, and someone pastes it to the learner before approval. Cause: the refund branch called DraftPort. Fix: return the review id. The executor sends mail after approval.
    5. Retrying the whole function in a loop on timeout. Symptom: classify runs three times and the wall clock triples during an incident. Cause: lookup_timeout was treated as a thrown exception from a generic runner. Fix: it is a result. The staff member retries, and the key collapses duplicate successes.
    6. Writing the run without a revision. Symptom: the workflow succeeds and a stale tab's commit replaces the slot. Cause: the route saved the run document directly. Fix: lesson 38's commit with expectedRevision, and do not re-run tools on conflict.
    7. Importing a graph library and moving the allowlist into a prompt. Symptom: the diagram looks complete and refund_course is back as a node the model can enter. Cause: the library example registered every function in the process. Fix: the nodes call executeSupportTool and the classifier returns an enum. A picture of a node is not a role grant.

    Summary

    Stuck enrollment is a short state machine the server owns. One ticket id, one of three intents, one registry lookup, then a draft or a pending review. Budgets stop a fifth step and a third model call. A failed lookup has no draft. A retry returns the stored result and the original review id. The model phrases labels and lookup drafts. It does not choose the tenant, the amount, or the next arrow. The next lesson maps this kind of sequence onto library concepts without moving the allowlist into a prompt.

    Next Lesson Preview

    LangChain Fundamentals for Full-Stack Developers names chains and graphs the way library documentation does. Read a chain as a fixed sequence like this workflow, and a graph as a state machine whose edges you can still list in review. The lesson keeps the support registry as the executor. It does not replace executeSupportTool with a generated agent class.

    Further Reading

    Ready to mark this lesson complete?Track your journey across the entire course.