Complete the capstone / Lesson 23 of 24

Build HarborDesk

Implement a complete, privacy-aware, reversible ticket-routing system around typed judgments.

After this moduleYou can deliver the state, questions, policy, operations, evaluation, and explanations for a safe Jev feature.

Define HarborDesk's safe product boundary

The capstone now combines question design, integration, evaluation, and operations in one system. HarborDesk is a fictional SaaS support product, and every ticket below is synthetic. decision contract: the exact state, questions, versions, policy, allowed actions, and evidence retained for one product judgment keeps the work reviewable. HarborDesk routes tickets to billing, technical, account, sales, other, or review; asks independent questions for refund intent, current service impact, and missing facts; and scores frustration on described levels.

Only reversible queue routing can happen automatically. Refunds, authentication changes, account deletion, entitlement changes, and customer messages require deterministic authorization plus human review. Routing must also be idempotent and conditional on the ticket version used for inference.

The state includes the latest customer message, product area, channel, language, computed account facts, and retrieved policy identifiers. It excludes credentials, raw payment data, unrelated history, and internal secrets. Code computes ticket age and count facts. The state builder records a safe keyed hash and retrieval version.

Trace this example from input to result
01

Customer choice

A HarborDesk administrator enables assisted ticket routing.

02

Request or event

A synthetic ticket-created event carries a stable ticket ID and version.

03

Backend behavior

Code builds minimal state, Jev returns bounded judgments, and versioned policy chooses a reversible route or review.

04

Customer sees

The support agent sees the ticket in a queue with an evidence status, never an automatic refund or account change.

05

Diagnostic reasoning

Replay the exact synthetic state, questions, requested and returned model, distributions, policy, and conditional write result.

Implement state and questions

The complete downloadable module is harbor-desk.ts, with mock-provider checks in harbor-desk.test.ts. It makes the real Gateway evaluation call from server-side TypeScript:

const result = await evaluate({
  model: gateway.evaluationModel("typesafe-ai/jev"),
  state: buildState(ticket),
  questions,
  maxRetries: 1,
  abortSignal: AbortSignal.timeout(5_000),
  providerOptions: { gateway: { zeroDataRetention: true } },
});

buildState validates the message and timestamp, calculates ageHours in code, and represents incident lookup as true, false, or incomplete null. The full question pack contains a six-option queue Choice, refundIntent, currentServiceImpact, and needsClarification boolean questions, plus a four-level frustration Score. The criteria distinguish a current request from quoted text, current outage from resolved or hypothetical impact, and a missing routing fact from ordinary uncertainty.

Question identifiers are application metadata; complete meaning lives in instructions and criteria. The five questions are independent. The refund answer cannot influence the queue answer during inference, and clarification cannot see current-impact output. Policy combines them afterward. Keeping those dimensions separate lets an evaluator measure queue correctness, refund-intent recall, impact recall, clarification load, and frustration-rung confusion without reducing all errors to one label.

Customer seesApplication doesJev returns
Ticket in a specialist queueChecks no-match, evidence, threshold, and current ticket versionQueue distribution plus confidence
Ticket in urgent reviewApplies impact, clarification, and completeness policyIndependent boolean probabilities
No automatic refundEnforces action allowlist and authorization in codeNo permission or side effect
Applied diagnosis

A billing ticket asks for a refund

queue=billing · refund language present · verifiedAccount=false

Route to billing if policy permits, but do not issue a refund. The route is reversible; the financial action is not. The billing workflow must read ledger truth, verify identity, apply deterministic eligibility, and obtain human approval. This separation remains even if the queue Choice and urgency Noul are highly concentrated.

Compose policy and operations

Use an illustrative, synthetic policy: auto-route only when the winner is not review, its probability is at least 0.82, incident lookup completed with no matching incident, clarification is below 0.5, current service impact is below 0.8, the account is verified, and the ticket version is current. A known incident deterministically requires review rather than waiting for the semantic threshold. Send all other cases to review. These numbers are teaching fixtures, not live outputs or recommended defaults.

async function applyAuthorizedRoute(context, ticket, action) {
  if (action.queue === "human-review") return action;
  if (!context.allowedRouteWrite) {
    return {
      ...action,
      queue: "human-review",
      reason: "route-write-forbidden",
    };
  }
  if ((await context.store.getVersion(ticket.id)) !== action.ticketVersion) {
    return { ...action, queue: "human-review", reason: "stale-ticket" };
  }
  const written = await context.store.compareAndSetRoute(
    ticket.id,
    action.ticketVersion,
    action.queue,
  );
  return written
    ? action
    : { ...action, queue: "human-review", reason: "route-write-conflict" };
}

This is an authorization boundary. chooseAction can produce only an approved route or human-review. applyAuthorizedRoute also requires a trusted context whose allowedRouteWrite capability was established by ordinary server authorization; account verification is an input fact, not permission to mutate. The write checks the stored ticket version and uses compare-and-set. The refund-intent value is retained for a reviewer but never returns money. triage awaits both evaluation and writing, classifies their failures separately, and produces safe review without logging the raw message. The course application never makes an external inference call; learners run the downloadable example in a server project with configured Gateway credentials.

Production wiring needs bounded concurrency, a workflow deadline, deduplication, safe retries, and a degraded general-review queue. Log event ID, state hash, question version, requested and returned model IDs, request ID, usage, distributions, policy version, action, and later correction. Keep raw bodies outside general telemetry.

Run the example from its isolated directory: install the pinned dependencies, set the Gateway credential in the server environment, and execute the provided check script. The tests use AI SDK's mock evaluation model, so they make no paid or external call. They verify deterministic age calculation, the no-refund authorization boundary, missing incident review, and stale-version rejection. Add service-error and threshold fixtures before adapting it to another product.

Dig deeperBuild the evaluation set before enabling writes

Create synthetic fixtures for every queue, no-match, conflicting messages, missing fields, stale state, adversarial text, non-English tickets, threshold edges, alias movement, 429, 529, timeouts, and route-write conflicts. Add approved historical examples only under the data policy. Run in shadow mode, compare reviewer routes, inspect subgroups, select thresholds on development data, and confirm on held-out data. Enable conditional route writes for a small canary and preserve an immediate disable switch.

Deliver the capstone evidence

The implementation is incomplete without two explanations. The product explanation should say: "HarborDesk uses the ticket text and current account facts to suggest a support queue. Clear, low-risk cases may be routed automatically. Unclear cases go to a person. The feature does not approve refunds, change authentication, or send customer messages." This states visible behavior without turning probability into certainty.

The engineering report should list the state schema and prohibited data, exact question definitions, model and question versions, synthetic dataset composition, metrics and subgroup results, illustrative policy, retry/degraded behavior, privacy controls, logging fields, canary plan, and rollback owner. It must distinguish missing evidence, semantic error, policy error, service failure, and conditional-write failure.

A realistic customer explanation after a correction is: "We found that your ticket was placed in the wrong support queue because the routing check did not have the completed incident status. We moved it to account support and added a review step whenever that status is unavailable. The routing feature did not change your account or issue a refund." This gives the observed result, bounded cause, correction, and prevention without exposing probabilities or internal provider details.

The launch checklist should also include a route-correction path. An agent must be able to move a ticket without fighting an automatic worker, and that correction should become an outcome record for later evaluation. Pause further automatic writes after correction until the ticket changes again. This prevents a feedback loop in which the same frozen judgment repeatedly overwrites a human decision. Monitor correction rate by queue and language, but review small slices carefully instead of treating every fluctuation as drift.

Saved locally

Complete HarborDesk's decision contract

Your answers stay in this browser. Write enough that another engineer could continue the investigation.

Knowledge check

Check your understanding

Build HarborDesk as a complete typed-decision workflow in which Jev supplies semantic judgments and code owns data boundaries, thresholds, permissions, writes, fallback, and evidence.

Module quiz

0/4 answered

01Which HarborDesk action may be automatic?
02Why check ticket version before writing the route?
03What should the product explanation include?
04What must happen before enabling queue writes?
Sources and verification notes 7
Building with System Onepublic-contract

State, independent judgments and code-owned composition, thresholds and actions.

Choicepublic-contract

Relative selection, labels, descriptions, full probabilities and confidence.

Noulpublic-contract

Probability for the stated binary condition, optional true/false criteria and no separate confidence field.

Scorepublic-contract

Ordered rubric, weighted expected index, legend, probabilities and confidence; numerical calibration has documented limitations.

Probability and confidencepublic-contract

Distribution concentration is distinct from empirical correctness. The exact native confidence formula is not published.

HTTP APIpublic-contract

POST /v1/systemone and authenticated GET /v1/models, request/response fields and errors. Prose and schema differ on omitted instructions, null state and one-level Score; course uses conservative valid requests.

Gateway evaluation contractpublic-contract

AI SDK evaluation entry point, boolean/probability normalization and confidence metadata; not an OpenAI-compatible chat REST route.

Further learning

Optional references

These resources provide public documentation and examples for readers who want them.

DocsHow to build with System One