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

    Project 3: AI Agent for Business Operations

    A Northwind support lead types, "Priya is stalled on pgvector.

    Course progress0%
    Focus
    24 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    AI-Powered Full Stack Development · Lesson 66 · Production AI Products, Capstones and Career Readiness

    Lesson Overview

    A Northwind support lead types, "Priya is stalled on pgvector. Draft a reminder." The agent may look up stalled learners and may propose messaging.email.send. It may not send. A second sentence, "and refund her," may propose billing.refund.create only if that is the one write for the run. It may not do both writes. It may not put a Contoso learner id on the ticket. It may not keep calling tools after the proposal. When the lead has not approved, a resume returns awaiting_approval.

    This capstone is ops-agent-v1. Lesson 47 was a fixed reminder workflow. This project is a bounded agent that chooses among an allow-list and still stops at a human for every write. The handbook assistant from Lesson 65 remains a read. The workspace from Lesson 64 remains the note editor. Neither is imported here.

    Planning assumptions:

    • Reads allowed: enrollment.lookup, billing.invoice.read.
    • Writes allowed as proposals only: messaging.email.send, billing.refund.create.
    • At most one write proposal per run. At most 4 steps, 2 model calls, and 3 tool calls.
    • The model does not supply workspaceId. A workspaceId field on a tool call is invalid_tool_args.
    • Recipient ids and invoice ids come from the read tool's result for the session workspace.
    • Idempotency key is idem_${runId} on the proposal.
    • Fixtures use lrn_priya and lrn_contoso. No live payment or SMTP credential.
    • Approval execution stays in Lesson 45. This agent calls propose and, on a later resume, executeApproved.

    Learning Objectives

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

    1. Draw the ops agent as a short loop over an allow-list, not an open planner.
    2. Separate read tools that execute from write tools that only propose.
    3. Stop the loop when a write is proposed.
    4. Refuse a second write in the same run.
    5. Reject unknown tool names before any port call.
    6. Reject a model-supplied workspace id.
    7. Copy lookup ids into the proposal instead of model-supplied recipient lists.
    8. Resume without a second proposal when approval is still pending.
    9. Execute an approved ticket once through the approval port.
    10. Keep a disabled flag from starting new tool calls.
    11. Trace tool names and counts, not prompts or invoice bodies.
    12. Phase the build from read-only to propose to resume.
    13. Name the security and test gates that block a merge.
    14. Pass readiness-v1 with idempotent writes and degrade.
    15. Explain why this agent is not the reminder workflow and not the handbook assistant.

    Prerequisites

    The tests use scripted model turns. You do not need a payment processor or an inbox.

    What is the AI Agent for Business Operations?

    The ops agent is a loop that may call a small catalog of business tools for one workspace. Reads run immediately and return data to the next model turn. Writes become approval tickets and end the run in awaiting_approval. The capstone is runOpsAgent, the phase plan, and the tests that fail if the agent sends mail, refunds twice, or crosses a tenant.

    The purpose is an operations product that is more flexible than Lesson 47's single template flow and stricter than a framework demo that executes every tool the model names. Support leads can ask for a lookup or a proposal in one box. The money and the mail still wait.

    The industry name is "agent," and the failure mode is an agent that is a shell. Banks require a second person for a refund. Hospitals require a signed order. Amazon-style seller support and Microsoft 365 admin actions separate "the copilot drafted it" from "the admin committed it." TechLearningPro's version is one proposal per run, ids from the read, and Lesson 45 as the only executor.

    TermMeaning in this lesson
    RunOne lead request, one runId
    StepOne model turn plus at most one tool
    Read toolExecutes and returns JSON to the model
    Write toolpropose only, then stop
    Allow-listFour tool names
    ProposalA Lesson 45 ticket with idem_${runId}
    ResumeSame run, no second propose
    Budget4 steps, 2 model calls, 3 tool calls

    Why Do We Need It?

    text
    The model picks any tool and the SDK executes it
    |
    v
    Cross-tenant ids, unapproved refunds, and loops that never stop
    |
    v
    Allow-list, server-side ids, one proposal, step budget
    |
    v
    A paused ticket or a read the audit can name

    Benefits:

    • A new tool requires a catalog change and a test, not a prompt edit.
    • Writes have a person in the loop.
    • The run cannot propose a refund and an email together.
    • Duplicate clicks do not create a second ticket.
    • The handbook assistant and the workspace stay out of this process.

    Real World Example

    The lead's session workspace is northwind. The first model turn calls enrollment.lookup with { "lessonKey": "pgvector" }. The port returns ["lrn_priya"] and drops lrn_contoso because the adapter filters by workspace. The second turn calls messaging.email.send with a template id. The agent proposes a ticket whose learner ids are the lookup result, not a list the model added. The status is awaiting_approval. A later resume with ticketApproved: false does not propose again. After Lesson 45 shows the ticket approved, resume calls executeApproved once and stores the effect id.

    If the model calls billing.refund.create and messaging.email.send in one payload, the result is invalid_tool_args and the propose count stays 0. If the model calls shell.exec, the result is tool_denied. If the model puts workspaceId: "contoso" on the lookup, the result is invalid_tool_args before the port.

    A card-dispute desk, a marketplace refund desk, and an IT help desk that resets a token only after approval are the same shape. The agent can gather. A person releases the side effect. TechLearningPro gathers enrollment or an invoice and proposes one of two writes.

    Internal Working

    1. If featureEnabled is false, return disabled. Do not call the model. If a checkpoint already exists, leave it.
    2. Empty workspace or user, or a role other than support_lead, returns unauthorized.
    3. A terminal checkpoint returns the stored result.
    4. A paused checkpoint with ticketApproved === false returns awaiting_approval and does not call the model.
    5. A paused checkpoint with ticketApproved === true calls executeApproved for that ticket. Success stores the effect id. execution_unknown stays paused on the same ticket.
    6. Start the loop with the user text. Each iteration calls the model unless the budgets are spent.
    7. Budgets: more than 2 model calls or more than 4 steps returns budget_exceeded. More than 3 tool calls returns budget_exceeded before the extra call.
    8. Parse one tool call. Unknown names are tool_denied. A workspaceId argument is invalid_tool_args. Two tool names in one object are invalid_tool_args.
    9. Read tools execute with the session workspace and the allowed argument (lessonKey or invoiceId that the server will reload). The result is appended for the next turn. The model does not receive rows from another workspace.
    10. Write tools require a prior successful read in this run. messaging.email.send copies learner ids from the last lookup. billing.refund.create copies the invoice id from the last invoice read. A model-supplied id list is invalid_tool_args.
    11. Propose once with idem_${runId} and stop in awaiting_approval. A second write name in a later turn cannot happen because the loop already stopped. A payload that names two writes never proposes.
    12. Traces store workspaceId, runId, reason, toolNames, modelCalls, and ticketId. They omit the user text, email addresses, and invoice amounts.

    Architecture

    sequenceDiagram
      participant Lead as Support lead
      participant Agent as runOpsAgent
      participant Model as Model port
      participant Read as Read tools
      participant Appr as Approval port
    
      Lead->>Agent: session workspace, run id, text
      Agent->>Model: turn 1
      Model-->>Agent: enrollment.lookup
      Agent->>Read: lookup for northwind
      Read-->>Agent: lrn_priya
      Agent->>Model: turn 2 with lookup ids
      Model-->>Agent: messaging.email.send
      Agent->>Appr: propose idem_run id
      Appr-->>Lead: awaiting_approval
      Lead->>Agent: resume after approval
      Agent->>Appr: executeApproved once
    text
    Flag, role, checkpoint
    |
    +--> disabled / unauthorized --> stop
    +--> paused --> wait or executeApproved
    |
    v
    Loop until budget, read result, or one proposal
    |
    +--> unknown tool --> tool_denied
    +--> workspaceId arg --> invalid_tool_args
    +--> two writes --> invalid_tool_args
    +--> write without a prior read --> invalid_tool_args
    |
    v
    propose idem_${runId} --> awaiting_approval
    flowchart TB
      Lead[Support lead]
      Agent[runOpsAgent]
      Catalog[Allow-list]
      Enroll[enrollment.lookup]
      Invoice[billing.invoice.read]
      Propose[propose write]
      Audit[Lesson 45 audit]
      Lead --> Agent
      Agent --> Catalog
      Catalog --> Enroll
      Catalog --> Invoice
      Catalog --> Propose
      Propose --> Audit

    Request flow executes reads only for the session workspace. Response flow to the lead is the agent result. The model does not talk to SMTP or the payment API.

    Deep Dive

    Catalog

    ToolClassArguments the server acceptsEffect
    enrollment.lookupreadlessonKey string, length 1..64Returns learner ids for the session workspace
    billing.invoice.readreadinvoiceId string matching inv_[a-z0-9]+Returns status for that id if it is in the workspace
    messaging.email.sendwritetemplateId must be cohort_reminder_v1Proposes a send to the last lookup ids
    billing.refund.createwritereason must be goodwill or duplicateProposes a refund of the last invoice id

    No other key is accepted. workspaceId, learnerIds, amount, and to are rejected. The template and the refund reason are constants so the ticket a human reads is boring on purpose. Lesson 47 already owns the template body. This agent does not invent a new email.

    Product scope and non-goals

    The agent can look up a lesson's stalled learners, read one invoice, and propose one of the two writes. It can resume after approval.

    It does not answer handbook questions. Call Lesson 65 for that. It does not edit notes. It does not choose a refund amount. The amount lives on the invoice the read tool loaded, and Lesson 45's executor uses that stored amount. It does not run more than one write per runId. A lead who needs both a reminder and a refund starts a second run after the first ticket is understood.

    Phased build plan

    PhaseBuildExit gate
    0Package, catalog types, CI, secret scanCatalog has exactly four names
    1Role check, flag, checkpoint loadLearner role and disabled flag do no tool I/O
    2Read loop with budgetsLookup is workspace-scoped, step cap fires
    3Propose one write from server-side idsModel learnerIds do not reach propose
    4Resume and executeApprovedDouble resume does not propose twice; execute once
    5Traces, readiness profile ops-agent-api, runbook lineProfile ready, flag versus approval route documented

    Phase 2 is safe to demo to a lead because it cannot propose. Do not skip to phase 3 because the model "usually" only reads.

    Acceptance criteria

    IdBehaviorTest name
    C1Role other than support_lead is unauthorized and does not call the modellead_role_required
    C2Disabled flag performs no model or tool callflag_stops_new_work
    C3shell.exec is tool_denied and does not proposeunknown_tool_denied
    C4workspaceId on a tool call is invalid_tool_argsmodel_cannot_set_workspace
    C5Lookup result omits lrn_contosolookup_is_workspace_scoped
    C6Email proposal uses lookup ids, not model idsrecipients_from_lookup
    C7A payload with two write names does not proposeone_write_per_payload
    C8A write without a prior read is invalid_tool_argswrite_requires_read
    C9After propose, a second entry returns awaiting_approval and propose count stays 1resume_does_not_repropose
    C10Approved resume executes once; a third call returns the effectexecute_once
    C11The third model call returns budget_exceededmodel_budget
    C12Trace has tool names and no user texttrace_omits_prompt
    C13Readiness profile passesops_profile_ready

    C3, C4, C6, C7, and C9 are the merge blockers. They are the incidents: arbitrary tools, cross-tenant arguments, forged recipients, double actions, and double tickets.

    Security gates

    • Allow-list is code, next to the parser.
    • Writes never execute inside the loop.
    • One write proposal per run.
    • Ids on the ticket come from the read port's last result.
    • Session workspace is the only workspace the ports receive.
    • ticketApproved is set by the route after it loads an approved ticket. The browser boolean is not evidence. The lab passes the flag so tests can simulate the lead.
    • Idempotency key is stable for the run.
    • The feature flag stops this function. Lesson 45 can still execute a ticket a person already approved. The runbook's first line says that, as in Lesson 47.
    • Traces omit prompts and amounts.
    • No payment or SMTP secret in the agent package. Those stay in the Lesson 45 adapters.

    Test gates

    • Unit tests C1–C13 with scripted model turns and in-memory ports.
    • A test lookup fixture includes lrn_contoso and asserts propose never sees it.
    • A test model turn that returns both write names asserts proposeCount === 0.
    • A replay test calls runOpsAgent three times: propose, not approved, approved, then approved again. Propose count is 1. Execute count is 1.
    • Cost test: unauthorized, disabled, and tool_denied show zero model calls where the spec says they stop first. tool_denied may happen after a model call; the test asserts zero proposes.
    • CI runs readiness and the secret scan.
    • Playwright later: the panel shows "Waiting for approval" and does not render a Send button that calls SMTP.

    Budgets and degrade

    The step counter increments for each model turn. Tool calls increment a second counter. When the model returns a write, the loop ends even if budget remains. Ending early is the point. budget_exceeded is for a model that only reads and never stops. The lead sees a stopped run, not a partial refund.

    Provider timeout during a turn is model_unavailable. Reads that already happened stay in the checkpoint as context so a retry of the same run can continue if you store them. This lab treats timeout before a proposal as terminal model_unavailable to keep the state machine small. A later version may resume the read context. It must still propose with the original runId key.

    What the agent will not do

    It will not send mail inside runOpsAgent. It will not set a refund amount. It will not call the knowledge assistant and paste the answer into the template. It will not run a fifth tool because the prompt said "be thorough." It will not look up Contoso because the user text named Contoso. The lookup port receives northwind from the session.

    Code Examples

    Place the package in packages/ops-agent/src/.

    Simple example: catalog and parser

    packages/ops-agent/src/catalog.ts

    typescript
    export const OPS_AGENT_VERSION = "ops-agent-v1";
    export const MAX_STEPS = 4;
    export const MAX_MODEL_CALLS = 2;
    export const MAX_TOOL_CALLS = 3;
    export const TEMPLATE_ID = "cohort_reminder_v1";
    export const READ_TOOLS = ["enrollment.lookup", "billing.invoice.read"] as const;
    export const WRITE_TOOLS = ["messaging.email.send", "billing.refund.create"] as const;
    export const ALLOWED_TOOLS = [...READ_TOOLS, ...WRITE_TOOLS] as const;
    export type ToolName = (typeof ALLOWED_TOOLS)[number];
    export type ParsedCall =
    | { ok: true; kind: "read"; name: "enrollment.lookup"; lessonKey: string }
    | { ok: true; kind: "read"; name: "billing.invoice.read"; invoiceId: string }
    | { ok: true; kind: "write"; name: "messaging.email.send"; templateId: typeof TEMPLATE_ID }
    | { ok: true; kind: "write"; name: "billing.refund.create"; reason: "goodwill" | "duplicate" }
    | { ok: false; reason: "tool_denied" | "invalid_tool_args" };
    const KEYS: Record<ToolName, readonly string[]> = {
    "enrollment.lookup": ["tool", "lessonKey"],
    "billing.invoice.read": ["tool", "invoiceId"],
    "messaging.email.send": ["tool", "templateId"],
    "billing.refund.create": ["tool", "reason"],
    };
    function exactKeys(record: Record<string, unknown>, name: ToolName): boolean {
    const keys = Object.keys(record).sort();
    const expected = [...KEYS[name]].sort();
    return keys.length === expected.length && keys.every((key, index) => key === expected[index]);
    }
    /**
    * One tool object and its exact keys.
    * workspaceId, learnerIds, amount, and a second tool fail closed.
    */
    export function parseToolCall(text: string): ParsedCall {
    let value: unknown;
    try {
    value = JSON.parse(text);
    } catch {
    return { ok: false, reason: "invalid_tool_args" };
    }
    if (!value || typeof value !== "object" || Array.isArray(value)) return { ok: false, reason: "invalid_tool_args" };
    const record = value as Record<string, unknown>;
    const name = record.tool;
    if (typeof name !== "string") return { ok: false, reason: "invalid_tool_args" };
    if (!ALLOWED_TOOLS.includes(name as ToolName)) return { ok: false, reason: "tool_denied" };
    const toolName = name as ToolName;
    if (!exactKeys(record, toolName)) return { ok: false, reason: "invalid_tool_args" };
    if (toolName === "enrollment.lookup" && typeof record.lessonKey === "string" && record.lessonKey.length >= 1 && record.lessonKey.length <= 64) {
    return { ok: true, kind: "read", name: toolName, lessonKey: record.lessonKey };
    }
    if (toolName === "billing.invoice.read" && typeof record.invoiceId === "string" && /^inv_[a-z0-9]+$/.test(record.invoiceId)) {
    return { ok: true, kind: "read", name: toolName, invoiceId: record.invoiceId };
    }
    if (toolName === "messaging.email.send" && record.templateId === TEMPLATE_ID) {
    return { ok: true, kind: "write", name: toolName, templateId: TEMPLATE_ID };
    }
    if (toolName === "billing.refund.create" && (record.reason === "goodwill" || record.reason === "duplicate")) {
    return { ok: true, kind: "write", name: toolName, reason: record.reason };
    }
    return { ok: false, reason: "invalid_tool_args" };
    }

    ALLOWED_TOOLS.includes is the deny path for shell.exec. Extra dangerous keys fail even when the tool name is allowed.

    Intermediate example: ports

    packages/ops-agent/src/ports.ts

    typescript
    export interface OpsScope {
    workspaceId: string;
    userId: string;
    role: "learner" | "instructor" | "support" | "support_lead" | "admin";
    }
    export type OpsReason =
    | "awaiting_approval"
    | "executed"
    | "answered_read"
    | "disabled"
    | "unauthorized"
    | "tool_denied"
    | "invalid_tool_args"
    | "budget_exceeded"
    | "model_unavailable"
    | "propose_failed"
    | "not_approved"
    | "execution_unknown";
    export interface OpsCheckpoint {
    runId: string;
    workspaceId: string;
    status: "paused" | "terminal";
    reason: OpsReason;
    ticketId?: string;
    effectId?: string;
    toolNames: string[];
    modelCalls: number;
    lastLearnerIds?: string[];
    lastInvoiceId?: string;
    }
    export interface OpsTrace {
    workspaceId: string;
    runId: string;
    reason: string;
    toolNames: string[];
    modelCalls: number;
    ticketId?: string;
    }
    export interface OpsPorts {
    lookup(workspaceId: string, lessonKey: string): Promise<{ learnerIds: string[] }>;
    readInvoice(workspaceId: string, invoiceId: string): Promise<{ ok: true; invoiceId: string } | { ok: false }>;
    model(messages: readonly string[]): Promise<{ text: string } | { error: "timeout" | "unavailable" }>;
    propose(input: { workspaceId: string; tool: string; idempotencyKey: string; learnerIds?: string[]; invoiceId?: string; templateId?: string; reason?: string }): Promise<{ ok: true; ticketId: string } | { ok: false }>;
    executeApproved(workspaceId: string, ticketId: string): Promise<{ ok: true; effectId: string } | { ok: false; reason: "not_approved" | "execution_unknown" }>;
    load(workspaceId: string, runId: string): OpsCheckpoint | undefined;
    save(checkpoint: OpsCheckpoint): void;
    trace(event: OpsTrace): void;
    }

    propose has no free-form body and no amount. The executor loads the invoice amount later, inside Lesson 45.

    Enterprise example: the loop

    packages/ops-agent/src/agent.ts

    typescript
    import { MAX_MODEL_CALLS, MAX_STEPS, parseToolCall } from "./catalog.js";
    import type { OpsCheckpoint, OpsPorts, OpsReason, OpsScope } from "./ports.js";
    export interface AgentInput {
    scope: OpsScope;
    runId: string;
    userText: string;
    featureEnabled: boolean;
    /** True only after the route loads an approved ticket for this workspace. */
    ticketApproved: boolean;
    }
    export type AgentResult =
    | { ok: true; reason: "awaiting_approval" | "executed" | "answered_read"; checkpoint: OpsCheckpoint }
    | { ok: false; reason: OpsReason; checkpoint: OpsCheckpoint };
    const SYSTEM =
    "You are the TechLearningPro ops agent. Return one JSON tool call using enrollment.lookup, " +
    "billing.invoice.read, messaging.email.send, or billing.refund.create. " +
    "Do not include workspaceId, learner ids, amounts, or a second tool.";
    /**
    * Reads execute. One write proposes and stops. Recipients come from the last read.
    */
    export async function runOpsAgent(ports: OpsPorts, input: AgentInput): Promise<AgentResult> {
    const existing = ports.load(input.scope.workspaceId, input.runId);
    if (!input.featureEnabled) {
    const checkpoint = existing ?? blank(input, "disabled", true);
    ports.trace(toTrace({ ...checkpoint, reason: "disabled" }));
    return { ok: false, reason: "disabled", checkpoint };
    }
    if (!input.scope.workspaceId || !input.scope.userId || input.scope.role !== "support_lead") {
    return stop(ports, input, "unauthorized", [], 0, true);
    }
    if (existing?.status === "terminal") return fromCheckpoint(existing);
    if (existing?.status === "paused" && existing.ticketId) return resume(ports, input, existing);
    const messages = [SYSTEM, input.userText];
    let modelCalls = 0;
    let toolNames: string[] = [];
    let lastLearnerIds: string[] | undefined;
    let lastInvoiceId: string | undefined;
    for (let step = 0; step < MAX_STEPS; step += 1) {
    if (modelCalls >= MAX_MODEL_CALLS) return stop(ports, input, "budget_exceeded", toolNames, modelCalls, false);
    const drafted = await ports.model(messages);
    modelCalls += 1;
    if ("error" in drafted) return stop(ports, input, "model_unavailable", toolNames, modelCalls, false);
    const parsed = parseToolCall(drafted.text);
    if (!parsed.ok) return stop(ports, input, parsed.reason, toolNames, modelCalls, false);
    if (toolNames.length >= 3) return stop(ports, input, "budget_exceeded", toolNames, modelCalls, false);
    toolNames = [...toolNames, parsed.name];
    if (parsed.kind === "read" && parsed.name === "enrollment.lookup") {
    const found = await ports.lookup(input.scope.workspaceId, parsed.lessonKey);
    lastLearnerIds = found.learnerIds;
    messages.push(`lookup:${found.learnerIds.join(",")}`);
    continue;
    }
    if (parsed.kind === "read") {
    const invoice = await ports.readInvoice(input.scope.workspaceId, parsed.invoiceId);
    if (!invoice.ok) return stop(ports, input, "invalid_tool_args", toolNames, modelCalls, false);
    lastInvoiceId = invoice.invoiceId;
    messages.push(`invoice:${invoice.invoiceId}`);
    continue;
    }
    if (parsed.name === "messaging.email.send") {
    if (!lastLearnerIds || lastLearnerIds.length === 0) return stop(ports, input, "invalid_tool_args", toolNames, modelCalls, false);
    return propose(ports, input, toolNames, modelCalls, { learnerIds: lastLearnerIds, templateId: parsed.templateId, tool: parsed.name });
    }
    if (!lastInvoiceId) return stop(ports, input, "invalid_tool_args", toolNames, modelCalls, false);
    return propose(ports, input, toolNames, modelCalls, { invoiceId: lastInvoiceId, reason: parsed.reason, tool: parsed.name });
    }
    return stop(ports, input, "budget_exceeded", toolNames, modelCalls, false);
    }
    async function propose(
    ports: OpsPorts,
    input: AgentInput,
    toolNames: string[],
    modelCalls: number,
    args: { tool: string; learnerIds?: string[]; templateId?: string; invoiceId?: string; reason?: string },
    ): Promise<AgentResult> {
    const proposed = await ports.propose({
    workspaceId: input.scope.workspaceId,
    idempotencyKey: `idem_${input.runId}`,
    ...args,
    });
    if (!proposed.ok) return stop(ports, input, "propose_failed", toolNames, modelCalls, false);
    const checkpoint: OpsCheckpoint = {
    ...blank(input, "awaiting_approval", false),
    status: "paused",
    toolNames,
    modelCalls,
    ticketId: proposed.ticketId,
    lastLearnerIds: args.learnerIds,
    lastInvoiceId: args.invoiceId,
    };
    ports.save(checkpoint);
    ports.trace(toTrace(checkpoint));
    return { ok: true, reason: "awaiting_approval", checkpoint };
    }
    async function resume(ports: OpsPorts, input: AgentInput, existing: OpsCheckpoint): Promise<AgentResult> {
    if (!input.ticketApproved || !existing.ticketId) {
    ports.trace(toTrace(existing));
    return { ok: true, reason: "awaiting_approval", checkpoint: existing };
    }
    const executed = await ports.executeApproved(input.scope.workspaceId, existing.ticketId);
    if (!executed.ok && executed.reason === "execution_unknown") {
    const checkpoint = { ...existing, reason: "execution_unknown" as const };
    ports.save(checkpoint);
    ports.trace(toTrace(checkpoint));
    return { ok: false, reason: "execution_unknown", checkpoint };
    }
    if (!executed.ok) return { ok: false, reason: "not_approved", checkpoint: existing };
    const done: OpsCheckpoint = { ...existing, status: "terminal", reason: "executed", effectId: executed.effectId };
    ports.save(done);
    ports.trace(toTrace(done));
    return { ok: true, reason: "executed", checkpoint: done };
    }
    function stop(ports: OpsPorts, input: AgentInput, reason: OpsReason, toolNames: string[], modelCalls: number, skipSave: boolean): AgentResult {
    const checkpoint: OpsCheckpoint = { ...blank(input, reason, true), toolNames, modelCalls };
    if (!skipSave) ports.save(checkpoint);
    ports.trace(toTrace(checkpoint));
    return { ok: false, reason, checkpoint };
    }
    function fromCheckpoint(existing: OpsCheckpoint): AgentResult {
    if (existing.reason === "executed" || existing.reason === "answered_read") return { ok: true, reason: existing.reason, checkpoint: existing };
    return { ok: false, reason: existing.reason, checkpoint: existing };
    }
    function blank(input: AgentInput, reason: OpsReason, terminal: boolean): OpsCheckpoint {
    return {
    runId: input.runId,
    workspaceId: input.scope.workspaceId,
    status: terminal ? "terminal" : "paused",
    reason,
    toolNames: [],
    modelCalls: 0,
    };
    }
    function toTrace(checkpoint: OpsCheckpoint) {
    return {
    workspaceId: checkpoint.workspaceId,
    runId: checkpoint.runId,
    reason: checkpoint.reason,
    toolNames: checkpoint.toolNames,
    modelCalls: checkpoint.modelCalls,
    ticketId: checkpoint.ticketId,
    };
    }

    A read-only run that ends because the model stops is a reasonable later status (answered_read). This loop expects another tool until the budget. Phase 2 can add a { "done": true } parse if product wants a lookup with no follow-up write. Until then, a single lookup followed by a model timeout becomes model_unavailable on the next turn, and the lead can start a new run. Document that in the phase 2 README so you do not silently add a done-flag without a test.

    packages/ops-agent/src/agent.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { runOpsAgent, type AgentInput } from "./agent.js";
    import type { OpsCheckpoint, OpsPorts } from "./ports.js";
    function world(turns: string[]) {
    const checkpoints = new Map<string, OpsCheckpoint>();
    let proposes = 0;
    let executes = 0;
    let cursor = 0;
    const proposedIds: string[][] = [];
    const ports: OpsPorts = {
    async lookup(workspaceId) {
    const learnerIds = workspaceId === "northwind" ? ["lrn_priya"] : [];
    return { learnerIds };
    },
    async readInvoice() {
    return { ok: true, invoiceId: "inv_01" };
    },
    async model() {
    const text = turns[cursor] ?? '{"tool":"shell.exec"}';
    cursor += 1;
    return { text };
    },
    async propose(input) {
    proposes += 1;
    if (input.learnerIds) proposedIds.push(input.learnerIds);
    return { ok: true, ticketId: "tkt_01" };
    },
    async executeApproved() {
    executes += 1;
    return { ok: true, effectId: "eff_01" };
    },
    load(workspaceId, runId) {
    return checkpoints.get(`${workspaceId}:${runId}`);
    },
    save(checkpoint) {
    checkpoints.set(`${checkpoint.workspaceId}:${checkpoint.runId}`, checkpoint);
    },
    trace() {},
    };
    return { ports, proposes: () => proposes, executes: () => executes, proposedIds };
    }
    const lead: AgentInput = {
    scope: { workspaceId: "northwind", userId: "usr_lead", role: "support_lead" },
    runId: "run_01",
    userText: "Remind stalled pgvector learners",
    featureEnabled: true,
    ticketApproved: false,
    };
    test("recipients_from_lookup", async () => {
    const box = world([
    '{"tool":"enrollment.lookup","lessonKey":"pgvector"}',
    '{"tool":"messaging.email.send","templateId":"cohort_reminder_v1"}',
    ]);
    const result = await runOpsAgent(box.ports, lead);
    assert.equal(result.reason, "awaiting_approval");
    assert.deepEqual(box.proposedIds[0], ["lrn_priya"]);
    });
    test("model_cannot_set_workspace", async () => {
    const box = world(['{"tool":"enrollment.lookup","lessonKey":"pgvector","workspaceId":"contoso"}']);
    const result = await runOpsAgent(box.ports, lead);
    assert.equal(result.reason, "invalid_tool_args");
    assert.equal(box.proposes(), 0);
    });
    test("unknown_tool_denied", async () => {
    const box = world(['{"tool":"shell.exec"}']);
    const result = await runOpsAgent(box.ports, lead);
    assert.equal(result.reason, "tool_denied");
    assert.equal(box.proposes(), 0);
    });
    test("resume_does_not_repropose", async () => {
    const box = world([
    '{"tool":"enrollment.lookup","lessonKey":"pgvector"}',
    '{"tool":"messaging.email.send","templateId":"cohort_reminder_v1"}',
    ]);
    await runOpsAgent(box.ports, lead);
    const again = await runOpsAgent(box.ports, lead);
    assert.equal(again.reason, "awaiting_approval");
    assert.equal(box.proposes(), 1);
    assert.equal(box.executes(), 0);
    });

    exactKeys is what makes C4 and C6 structural. A lookup that also carries learnerIds or workspaceId never reaches ports.lookup. The email tool accepts tool and templateId only, so the proposal's learner ids are the array lookup returned for northwind. recipients_from_lookup covers that copy. model_cannot_set_workspace covers the extra key. Add one_write_per_payload by sending a second write field and asserting propose stays at 0, which exactKeys already rejects.

    Architecture Diagram

    text
    Support session
    |
    v
    runOpsAgent
    |
    +--> catalog parse
    +--> read ports (workspace id from session)
    +--> one propose
    |
    v
    Lesson 45 ticket idem_${runId}
    |
    v
    Human approval --> executeApproved once
    text
    Handbook assistant -- read, no import here
    Workspace notes -- no import here
    Lesson player -- no import here

    Real-Time Enterprise Example

    The support panel calls runOpsAgent with a scope built from the session. The enrollment adapter queries stalled learners WHERE workspace_id = northwind. Propose writes a Lesson 45 ticket. The lead approves in the queue UI. The route loads the ticket, checks approved, and calls the agent with ticketApproved: true. The mail adapter sends cohort_reminder_v1 to addresses it loads for lrn_priya. The agent trace shows the tool names. The audit shows the approver and eff_01.

    A scripted probe sends shell.exec and expects zero proposes. Another sends both write names and expects zero proposes. Another includes lrn_contoso in the lookup table and expects the proposal to omit it.

    Challenge: the model is down after a successful lookup, the lead double-clicks, and the flag is turned off after a ticket exists. Timeout returns model_unavailable if no ticket was saved yet. Double-click after propose does not create tkt_02. The flag stops a new run and leaves the existing checkpoint. The Lesson 45 route can still execute the approved ticket. The runbook says so. You do not add shell.exec to the catalog to "finish the refund manually" inside the agent.

    Performance Optimization

    The happy path is two model calls, one read, and one propose. The model sees ids, not a pasted roster of emails. Budgets stop a chatty model from turning one question into a dozen invoice reads. Resume does not repeat the lookup.

    Do not hold the HTTP request open while the lead thinks. Return awaiting_approval. Execute is a later request. Interactive lookups use the provider and connector deadlines from Lesson 63. The agent process stays stateless apart from what the checkpoint store holds, so you can run more replicas without splitting the ticket.

    Queue the execute side if the mail vendor is slow. The agent's request should return after executeApproved accepts the work or returns the effect id. It should not poll SMTP inside the loop. There is no loop on resume.

    Security

    • Authentication. Empty identity fails. Session construction stays in Lesson 48.
    • Authorization. Only support_lead starts a run. Admins do not get a silent bypass in this package. Add them with a test if product requires it.
    • Tenant. Lookup, invoice read, propose, and execute receive the session workspace. A model workspaceId fails the parse.
    • Allow-list. Four names. shell.exec is tool_denied.
    • Arguments. Unexpected keys fail. Recipient ids are the lookup array.
    • Approval. The loop proposes. Lesson 45 executes. One write per run.
    • Idempotency. idem_${runId} for the life of the run, including execution_unknown.
    • Flag. This function stops. It does not delete tickets.
    • Secrets. The agent does not read SMTP_PASSWORD or a payment key. Adapters in Lesson 45 do, from the secret store.
    • OWASP. Broken access control is the role and the workspace. Injection is a tool name or an id in the model JSON. Unrestricted resource consumption is the step budget.

    Common Mistakes

    1. Executing the write in the loop. Symptom: mail leaves before approval. Cause: the write branch called SMTP. Fix: propose and awaiting_approval.
    2. Trusting learnerIds from the model. Symptom: Contoso is on the ticket. Cause: the parser allowed the array. Fix: unexpected keys fail, and propose copies the lookup.
    3. Allowing two writes in one run. Symptom: a refund and a mail from one sentence. Cause: the loop continued after propose. Fix: return on propose, and reject a payload that names two writes.
    4. A second ticket on double-click. Symptom: two approvals. Cause: resume called the model again. Fix: a paused checkpoint returns immediately.
    5. Rotating the idempotency key after execution_unknown. Symptom: two effects. Cause: a new key on retry. Fix: the same ticket and idem_${runId}.
    6. Taking workspaceId from the tool JSON. Symptom: the lookup runs as Contoso. Cause: the port used the argument. Fix: invalid_tool_args, and pass the session id.
    7. Letting an instructor start the run. Symptom: a teacher proposes a refund. Cause: the UI hid the button and the API did not check. Fix: support_lead only.
    8. Adding tools by editing the prompt. Symptom: shell.exec starts working. Cause: the catalog was "whatever the model says." Fix: ALLOWED_TOOLS and tool_denied.
    9. Putting the user text on the trace. Symptom: a learner's story is in the log vendor. Cause: trace(input). Fix: tool names and counts.
    10. Importing the handbook assistant to write the email. Symptom: uncited prose in the template. Cause: scope creep. Fix: template id only.
    11. Raising MAX_STEPS during an incident. Symptom: a runaway bill and a second write. Cause: the budget was treated as a bug. Fix: a new run, not a bigger loop.
    12. Confusing the feature flag with "unsend." Symptom: on-call expects the flag to stop an approved execute on Lesson 45. Cause: the two switches were conflated. Fix: the runbook line from phase 5.

    Best Practices

    1. Keep four tools in the catalog until a review adds a fifth.
    2. Parse with an exact key set per tool.
    3. Deny unknown tool names.
    4. Reject workspaceId, amounts, and recipient lists from the model.
    5. Run reads with the session workspace.
    6. Propose writes. Do not execute them here.
    7. Allow one write per run.
    8. Require a prior read before a write.
    9. Use idem_${runId} for the ticket.
    10. Stop the loop on propose.
    11. Resume from the checkpoint.
    12. Execute through Lesson 45 once.
    13. Keep execution_unknown on the same ticket.
    14. Enforce step, model, and tool budgets.
    15. Restrict the role to support_lead.
    16. Honor the feature flag without deleting tickets.
    17. Trace tool names, not prompts.
    18. Keep payment and SMTP secrets in the executor adapters.
    19. Test Contoso filtering, unknown tools, double writes, and replay.
    20. Ship the read-only phase before propose.
    21. Document the flag versus the approval route.
    22. Pass readiness-v1 for ops-agent-api.
    23. Do not import the workspace or the handbook package.
    24. Do not raise the budget to finish a stuck run.
    25. Keep the lesson player off this endpoint.

    Interview Questions & Answers

    Beginner

    1. What can this agent do by itself?
      It can read enrollment or one invoice for the session workspace. It can propose one email or one refund. It cannot send or refund until a person approves the ticket.

    2. Why is shell.exec denied?
      It is not on ALLOWED_TOOLS. The parser returns tool_denied and does not call propose. Adding a tool is a code change with a test.

    3. What is the idempotency key?
      idem_ plus the run id. Resume uses the same ticket. A second click does not create another key.

    Intermediate

    1. Where do reminder recipients come from?
      From enrollment.lookup for the session workspace. The email tool accepts a template id only. A learnerIds array on the model JSON is invalid_tool_args.

    2. What happens if the model asks for a refund and an email together?
      The parser rejects the payload. Propose count stays 0. The lead starts a second run if both actions are really required.

    3. What does resume do before approval?
      It returns awaiting_approval and does not call the model, lookup, or propose. After the route has seen an approved ticket, resume calls executeApproved once.

    Senior

    1. How do you test this without SMTP or a card processor?
      Script model with JSON strings. Script lookup to return Northwind ids only. Count propose and executeApproved. Assert Contoso never appears in the proposal. Contract-test the real adapters in Lesson 44 and Lesson 45 with fixture ids.

    2. How is this different from Lesson 47?
      Lesson 47 always looks up one lesson and proposes one template. This agent may choose lookup, invoice read, email, or refund, under a budget. The safety properties match: server-side ids, one ticket, human execute, stable idempotency key.

    Architect

    1. How do you add a tool?
      Add the name to the catalog, the allowed keys, the port method, and tests for denial of extra keys and for tenant scope. A write tool proposes and stops. It does not get an execute branch in this file. Review the runbook and the readiness profile. A prompt-only change is a defect.

    2. How do you roll this out?
      Enable phase 2 reads for one support lead at Northwind. Watch tool names and tool_denied. Enable propose with the flag. Keep execute on the Lesson 45 route. The player, the workspace, and the handbook stay on their own deploys so an agent bug does not block reading.

    3. What do you refuse in an incident?
      You refuse to execute inside the loop, to accept model ids, to raise MAX_STEPS so a run can "finish," and to point the lookup at all workspaces because Northwind's query was empty. Empty lookup means there is nothing to propose.

    4. Where should handbook prose live?
      In Project 2, as a cited answer. If a reminder needs a sentence from the guide, that is a new template version a person approves. This agent still sends cohort_reminder_v1 or proposes a refund. It does not paste assistant text into the ticket body.

    Knowledge Check

    1. What problem does this capability solve?

    It lets a support lead gather enrollment or invoice facts and propose one side effect, with an allow-list, a budget, and a human approval, without turning the model into a payment client.

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

    Lesson 47 is enough when the only job is the stalled-learner reminder. A form the lead fills by hand is enough when no model is required. This agent is the right product when the lead's words may map to more than one read and at most one write. The handbook assistant is the right product for policy questions.

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

    The session supplies workspace and the support-lead role. Read ports supply ids. The model supplies a tool name and a small enum or key. Lesson 45 supplies approval and the effect. Traces do not store the prompt.

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

    Disabled, unauthorized, unknown tools, bad arguments, missing prior reads, and budgets stop without a ticket. Propose pauses. Resume waits or executes once. Provider failure before a ticket is model_unavailable.

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

    C1–C13 cover role, flag, tools, tenants, replay, and budget. Security tests assert Contoso ids and shell.exec never propose. A performance test asserts resume does not call the model. A cost test asserts the disabled flag does not call the model.

    Practical Exercise

    Implement packages/ops-agent/src/ and tighten parseToolCall so each tool accepts only its allowed keys. Make recipients_from_lookup, unknown_tool_denied, and resume_does_not_repropose pass. Add one_write_per_payload. Write the runbook sentence that separates this feature flag from the Lesson 45 execute route.

    Deliverable and Rubric

    Submit the sequence diagram, the catalog table, the phase plan, the agent package, the test output, and the readiness profile.

    AreaWeight
    Conceptual accuracy and architecture20%
    Working implementation and code quality25%
    Security, privacy, and responsible AI20%
    Testing, reliability, and observability20%
    Documentation and decision rationale15%

    Production checklist:

    • Only support_lead starts a run.
    • The catalog is four tools.
    • Unknown tools are denied.
    • The model cannot set workspace, recipients, or amount.
    • Reads use the session workspace.
    • One write is proposed and the loop stops.
    • The idempotency key is idem_${runId}.
    • Resume does not propose again.
    • Execute goes through Lesson 45 once.
    • Budgets are enforced.
    • Traces omit prompts and amounts.
    • The flag does not delete tickets.
    • ops-agent-api passes readiness-v1.
    • The player, workspace, and handbook do not import this loop.

    Key Takeaways

    1. ops-agent-v1 is a bounded loop, not an open shell.
    2. Four tools are the catalog.
    3. Reads execute. Writes propose.
    4. One write ends the run.
    5. Ids come from the read ports.
    6. Extra JSON keys fail closed.
    7. shell.exec never proposes.
    8. Only a support lead can start the run.
    9. idem_${runId} stays stable.
    10. Resume waits or executes once.
    11. Budgets stop a chatty model.
    12. The feature flag stops new work and keeps tickets.
    13. Traces store tool names.
    14. Lesson 45 remains the executor.
    15. The handbook and the workspace stay separate products.

    Summary

    Lesson 66 is the business-operations agent as a product with a short allow-list and a hard stop at approval. TechLearningPro support can look up who is stalled or which invoice is in dispute, and can propose one reminder or one refund. The agent does not get a payment credential, a shell, or a second write in the same run. Lesson 47's reminder is still the right tool when the path is fixed. This project is the right tool when the lead's request may be a read or a single proposal. The next capstone leaves operations and opens documents: images and files, with the same habit of tenant scope, explicit side effects, and a readiness gate.

    Next Lesson Preview

    Project 4: Multimodal Document Intelligence Platform takes PDFs and images through an ingest pipeline that extracts text a person can review. You will keep tenant isolation on every file, avoid sending a whole archive to a model in one request, and decide which extractions become handbook chunks for the assistant you just kept on the read path. The ops agent will not gain a file-delete tool in that project.

    Further Reading

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