Examples: 7 Verified Applications (01–07), flow-patterns & 08-job-scout
AGBoss provides three complementary repositories of runnable, CI-verified examples so you can prove compile-time and runtime guarantees in seconds for $0 and inspect production-grade reference architectures.
- 7 Standalone Verified Examples (
agbossjs/agboss-examples): Seven self-contained applications (01-hello-agbossthrough07-langgraph-migration) following thePromise → Failure Injection → Reproducible Proofdiscipline — each with its ownpackage.json, canonical1 class = 1 filecomponent subfolder layout, symmetric Spring-styletests/mirroringsrc/,.claude/skills/agboss/,npx agboss check, and$0offline test & demo suites. - Distributed Agent Recovery Showcase (
agbossjs/distributed-agent-recovery· Architectural Walkthrough →): A multi-process distributed AI release pipeline (“Ghost in the Machine: The Zombie AI Worker”) provingChildPlacement.AnyInstancecross-process load balancing, LIFOcompensateWithsaga rollback, liveopenai/gpt-4o-minirecovery planning, same-task checkpoint takeover after 30s lease expiration, and two-layer zombie worker lease fencing across 8 automated invariants. examples/flow-patternsinagbossjs/agbossand08-job-scoutinagbossjs/agboss-examples:examples/flow-patternsverifies loops, code/model routers, parallel waves, andThisWorkflowrecursion in< 5 secondsfor$0;08-job-scoutis the interactive career assistant.
The 7 Verified Examples in agbossjs/agboss-examples
Section titled “The 7 Verified Examples in agbossjs/agboss-examples”| Example | Architectural Proof & Capabilities Demonstrated | Key Primitives & CLI Commands |
|---|---|---|
01-hello-agboss |
First-run, real HTTP service DI, web server & CLI scaffolding: Demonstrates PricingCatalogService (async onInit(), fetch with ExecutionContext.signal + step.idempotencyKey), src/http/server.ts (multi-tenant headers, 202 Accepted on pauses, /api/pauses/:pauseId/resume, /health/live, /health/ready), and canonical 1 class = 1 file + symmetric tests/ layout. |
@Application, @Workflow, @Agent, @Router, @Tool, @Injectable, testWith, mockOf |
02-path-scope-proof |
Compile-time Path Scope vs raw LangGraph: Proves 4 structural graph bug classes (01-missing-input, 02-outdated-data, 03-parallel-invalidation, 04-uncompensated-action) that pass tsc --noEmit in raw LangGraph Annotation.Root (langgraph-broken/) and are caught before runtime by agboss check (agboss-broken/ vs agboss-fixed/). |
[input.missing-on-path], [input.outdated-on-path], [launch.branch-outdates-sibling], [flow.uncompensated-action] |
03-support-refund-desk |
PII roundtrip, tool interception, in-memory BM25 RAG, compaction & 5-layer evals: Reversible HMAC @PiiPolicy (replaceWithToken, revealPii: true, PiiRefusedError), @ToolInterceptor (replyToModel, block), @InputGuardrail (DecidedBy.Code), @OutputGuardrail, InMemoryKnowledgeIndexService + RefundPolicyRetriever (@Rag), PolicyAwareCompaction, and @EvalSuite with compact git-tracked eval/baseline/main-baseline.json and agboss eval calibrate (Cohen’s $\kappa$). |
@PiiPolicy, @ToolInterceptor, @InputGuardrail, @OutputGuardrail, @Rag, @Compaction, @EvalSuite, agboss eval |
04-travel-booking-saga |
Transactional LIFO sagas, idempotency, quorums, closed approval messages & HTTP server: Reverse-order LIFO compensation across payment-saga, budget-saga, quorum-saga (.joinQuorum({ min: 2, max: 2 })), and hitl-hold-saga (onPauseClosed(), PauseClosedError), idempotent external ledgers (step.idempotencyKey), SQLite WAL crash recovery, and src/http/server.ts. |
@Action({ compensateWith, committedBy }), .toParallelAgents().acceptedBy().joinQuorum(), @ChannelRole, @Channel |
05-cluster-work-stealing |
Distributed scheduling, 30s leases, fencing & backpressure: Parent CoordinatorWorkflow fans out ChunkWorkerWorkflow with ChildPlacement.AnyInstance over SqliteChildExecutionQueueRepository, runs bounded recursive ThisWorkflow (maxDepth: 2), enforces 30s SQLite leases & fencing (ExecutionLeaseLostError), maxConcurrentSteps: 2 backpressure (HealthComponentKind.StepSlots), @HealthCheck, and IncompatibleResumeError. |
ChildPlacement.AnyInstance, SqliteChildExecutionQueueRepository, ThisWorkflow, @HealthCheck, SqliteExecutionLeaseRepository |
06-enterprise-agent-mesh |
3-service A2A + MCP mesh, Ed25519 envelopes, loop guard & federation Blast Radius: Connects apps/1-order-gateway, apps/2-billing-a2a (@A2AExpose), and apps/3-catalog-mcp (@McpExpose) with Ed25519-signed mesh envelopes, MeshLoopDetectedError / HopsLimitExceededError, MCP _meta.callId deduplication (SqliteMeshRequestRepository), and agboss check --federation (federation/). |
@A2AExpose, @A2AAgent, @McpExpose, @McpTool, SqliteMeshRequestRepository, agboss check --federation, agboss hub |
07-langgraph-migration |
Side-by-side comparison (before-langgraph/ vs after-agboss/): Compares a raw 15-field LangGraph Annotation.Root God State (before-langgraph/support.graph.ts) with the migrated AGBoss implementation (after-agboss/src/ + after-agboss/tests/) using 10 narrow @Dtos, DecidedBy.Model & DecidedBy.Code @Routers, bounded .toParallelAgents(), idempotent @Action, typed @Channel, and co-located .prompt.md files. |
@Dto, @Router, .switch(caseOf()), .toParallelAgents(), @Action, @Channel, 13-migrating-from-langgraph.md |
Canonical Project Layout (1 class = 1 file & Symmetric tests/)
Section titled “Canonical Project Layout (1 class = 1 file & Symmetric tests/)”Every project in agbossjs/agboss-examples enforces a clean, navigable folder convention:
- 1 class per file with kind-suffixed filenames (
*.application.ts,*.workflow.ts,*.workflow-start.ts,*.workflow-finish.ts,*.agent.ts,*.router.ts,*.action.ts,*.tool.ts,*.service.ts,*.dto.ts). - Component subfolders grouping each workflow (
src/workflows/<name>/with its workflow, start, and finishes) and each model-driven component (src/agents/<name>/andsrc/routers/<name>/co-locating the.tsclass with its immutable.prompt.mdfile). - Symmetric Spring-style
tests/directory mirroringsrc/1-to-1 (tests/services/,tests/tools/,tests/actions/,tests/routers/,tests/guardrails/,tests/interceptors/,tests/http/,tests/workflows/<name>/) so coding agents and engineers know immediately where unit and workflow tests belong.
Spotlight: 02-path-scope-proof (4 Graph Bugs Caught Before Runtime)
Section titled “Spotlight: 02-path-scope-proof (4 Graph Bugs Caught Before Runtime)”In 02-path-scope-proof, four structural bug cases (cases/01-missing-input, cases/02-outdated-data, cases/03-parallel-invalidation, cases/04-uncompensated-action) are each implemented in three variants — langgraph-broken/ (compiles with tsc --noEmit yet fails or corrupts state at runtime), agboss-broken/ (rejected before runtime by agboss check --json with an exact rule code and witness path), and agboss-fixed/ (passes agboss check and executes cleanly):
- Missing input on a conditional route (
01-missing-input→[input.missing-on-path]): Thefast-trackbranch of a router skipsComplianceReview(ComplianceApprovalDto), yetPublishContractrequiresapproval. Raw LangGraph silently receivesundefinedat runtime;agboss checkhalts at compile time. - Stale data after a revision cycle (
02-outdated-data→[input.outdated-on-path]):QualityRevieweremitsRevisionRequested({ about: ContractDraftDto }) andRevisionWriterreplacesContractDraftDto, making the earlierLegalSignoffDtostale. SkippingLegalCheckon the second pass is rejected byagboss check. - Parallel sibling invalidation (
03-parallel-invalidation→[launch.branch-outdates-sibling]): Inside a parallel launch,PricingRewriterreplacesQuoteSheetDtowhile its siblingTaxAuditconcurrently audits the pre-launchQuoteSheetDto.agboss checkrejects the race condition statically. - Uncompensated side effect on an error path (
04-uncompensated-action→[flow.uncompensated-action]):ReserveInventory(compensateWith: ReleaseInventory) is followed byChargeCard, whose.onError(...)path reachesOrderFailedFinishwithout invokingReleaseInventory.agboss checkrefuses to compile the uncompensated path.
Detailed Guide to All 7 Standalone Examples (01–07)
Section titled “Detailed Guide to All 7 Standalone Examples (01–07)”Setup (
v0.1.0):@agboss/core@0.1.0and@agboss/cli@0.1.0are published onregistry.npmjs.org. Runnpm installinside any example directory (ornode ./scripts/install-published.mjs --live-registry --version 0.1.0from theagbossjs/agboss-examplesrepository root) before running per-project commands.
1. 01-hello-agboss — Starter, Constructor DI, Budgets & HTTP Server (P0)
Section titled “1. 01-hello-agboss — Starter, Constructor DI, Budgets & HTTP Server (P0)”- Problem statement: First-time multi-agent setups often mix business logic, HTTP transport calls, and prompt strings inside untyped node functions without budget ceilings or cancellation signals.
- Architecture overview:
HelloAgbossWorkflowstarts atHelloWorkflowStart(HelloQuestionDto), routes viaIntentRouter(DecidedBy.Model) to eitherSupportSpecialistAgentorQuoteAdvisorAgent(which invokesCalculateTierQuoteToolbacked byPricingCatalogService), and finishes atHelloWorkflowFinish(HelloAnswerDto). - Main mechanisms demonstrated:
@Application,@Workflow,@Router,@Agent,@Tool,@Injectable(PricingCatalogServicewithasync onInit(),ExecutionContext.signal, andstep.idempotencyKey),@Budget(Application,Tenant, andExecutionscopes),SqliteCostLedgerRepository, andsrc/http/server.ts. - Representative code:
start(HelloWorkflowStart).returns(HelloQuestionDto).toRouter(IntentRouter).chooseOne(route("support").toAgent(SupportSpecialistAgent).toFinish(HelloWorkflowFinish), route("pricing").toAgent(QuoteAdvisorAgent).toFinish(HelloWorkflowFinish)) - Quickstart commands:
Terminal window cd 01-hello-agbossnpm run check && npm test && npx tsx src/demo.ts - Expected proof output:
npx tsx src/demo.tsexecutes both"support"and"pricing"routes offline against the local pricing HTTP stub server and prints JSON confirmingsupportBranch.status: "finished",pricingBranch.status: "finished", andpricingApiRequestsCount: 1. - Failure scenario tested:
tests/workflows/hello-agboss/hello-agboss.workflow.test.tsinjects a low execution budget ceiling and verifiesBudgetExceededErroraborts execution before overspending. - Guarantee boundary:
- Verified: Static workflow assembly, constructor DI lifecycle (
onInit), tool schema validation, budget enforcement, and deterministic offline execution. - Not verified by default offline run: Live OpenRouter model quality or network latency (requires
npx tsx src/demo.ts --livewithOPENROUTER_API_KEY).
- Verified: Static workflow assembly, constructor DI lifecycle (
- Repository directory:
agbossjs/agboss-examples/01-hello-agboss
2. 02-path-scope-proof — Static Graph Safety & Provenance (P0)
Section titled “2. 02-path-scope-proof — Static Graph Safety & Provenance (P0)”- Problem statement: In shared-state graph libraries (
Annotation.Root), conditional branches that skip required producers, revision loops that leave stale approvals active, parallel branches that overwrite shared slots, and error handlers that bypass compensation all compile undertsc --noEmitand fail only at runtime. - Architecture overview: Four self-contained case directories (
cases/01-missing-input,02-outdated-data,03-parallel-invalidation,04-uncompensated-action), each containinglanggraph-broken/,agboss-broken/, andagboss-fixed/. - Main mechanisms demonstrated:
agboss check --jsonstatic dominance analysis ([input.missing-on-path],[input.outdated-on-path],[launch.branch-outdates-sibling],[flow.uncompensated-action]),.agboss/types.d.tsProduced<Dto, Producer>narrowing,{ about }provenance invalidation, andcompensateWith. - Representative code:
caseOf(ChangesRequestedDto, { about: ContractDraftDto }).toAgent(RevisionWriterAgent).returns(ContractDraftDto).toAgent(LegalCheckAgent) - Quickstart commands:
Terminal window cd 02-path-scope-proofnpm run check && npm test && npx tsx src/demo.ts - Expected proof output:
npx tsx src/demo.tsruns all 4 cases and outputs JSON proving thatlanggraph-brokenpassestsc(passedTsc: true) and fails at runtime,agboss-brokenis rejected before runtime with the exact diagnostic code, andagboss-fixedfinishes cleanly. - Failure scenario tested: All four
agboss-broken/*.workflow.tsfixtures are intentionally broken workflows verified to failagboss check --jsonwith exit code1and exact witness paths. - Guarantee boundary:
- Verified: Static path-dominance of declared
@Dtoslots,{ about }invalidation along cyclic/parallel paths, and presence ofcompensateWithalong declared error paths. - Not verified: Arbitrary imperative mutations inside custom
@Injectableservices or external databases outside AGBoss DTO handoffs.
- Verified: Static path-dominance of declared
- Repository directory:
agbossjs/agboss-examples/02-path-scope-proof
3. 03-support-refund-desk — PII Masking, Guardrails, RAG, Compaction & Evals (P0)
Section titled “3. 03-support-refund-desk — PII Masking, Guardrails, RAG, Compaction & Evals (P0)”- Problem statement: Customer support agents handle sensitive PII (emails, phone numbers, payment cards), face prompt-injection and policy-violation risks, suffer context drift over multi-turn conversations, and require reproducible regression gating.
- Architecture overview:
SupportRefundWorkflowwrapsRefundSupportAgentwithCustomerContactPiiPolicy+SupportTicketIdPiiPolicy,PromptInjectionGuardrail(@InputGuardrail) +UnauthorizedPayoutGuardrail(@OutputGuardrail),RefundPolicyToolInterceptor+AuditTrailToolInterceptor,RefundPolicyRetriever(@Rag),PolicyAwareCompaction(@Compaction), andRefundDeskEvalSuite(@EvalSuite). - Main mechanisms demonstrated: Reversible HMAC
@PiiPolicy(replaceWithToken,revealPii: trueonIssueRefundTool,PiiRefusedErroron card numbers, masked OTel/Langfuse spans),@InputGuardrail,@OutputGuardrail,@ToolInterceptor(ToolCallDecision.replyToModel&block),@Rag,@Compaction, and@EvalSuite(pass@k,pass^k,--baseline, Cohen’s $\kappa$ calibration,--chaos,--metamorphic, incident-to-eval drafting). - Representative code:
@PiiPolicy({ name: "customer-contact-pii-policy", match: [PiiKind.Email, PiiKind.Phone], action: PiiAction.ReplaceWithToken }) - Quickstart commands:
Terminal window cd 03-support-refund-desknpm run check && npm test && npx tsx src/demo.ts - Expected proof output:
npx tsx src/demo.tsprints JSON verifyingpii.modelSawMaskedEmailToken: true,pii.modelSawRawEmail: false,pii.toolReceivedRealEmail: "alice.synth@example.com",pii.langfuseOtelSpansMaskedPii: true,policy.overCapFinalDecision: "escalated",memoryDrift.preservedOrderFact: true, andevals.calibration.kappaJudgeAnna: 1. - Failure scenarios tested: Raw credit card refusal (
PiiRefusedError), over-cap refund interception (ToolCallDecision.replyToModel), cross-tenant tool block, prompt-injection input guardrail block, unauthorized settlement output guardrail block, and baseline regression detection (pass^kdrop under--chaos). - Guarantee boundary:
- Verified: Deterministic regex/field PII pseudonymization, tool interceptor policy gates, compaction fact retention, and offline
@EvalSuitestatistical calculations (pass@k,pass^k, Cohen’s $\kappa$). - Not verified by default offline run: Open-ended adversarial jailbreak resilience on live frontier models (requires live model evaluation runs).
- Verified: Deterministic regex/field PII pseudonymization, tool interceptor policy gates, compaction fact retention, and offline
- Repository directory:
agbossjs/agboss-examples/03-support-refund-desk
4. 04-travel-booking-saga — Transactional LIFO Sagas, Quorums, HITL & Crash Recovery (P0)
Section titled “4. 04-travel-booking-saga — Transactional LIFO Sagas, Quorums, HITL & Crash Recovery (P0)”- Problem statement: Multi-step workflows that reserve flights, book hotels, and charge cards leave orphaned reservations when a downstream step fails, a budget limit triggers, a user cancels a paused approval, or a process crashes mid-flight.
- Architecture overview: Four workflows in
TravelBookingSagaApplication(PaymentSagaWorkflow,BudgetSagaWorkflow,HitlHoldSagaWorkflow, andQuorumSagaWorkflow) backed bySqliteCheckpointSaver,SqlitePausedExecutionRepository, andSqliteExecutionLeaseRepository. - Main mechanisms demonstrated:
@Action({ compensateWith, committedBy }),step.idempotencyKeydeduplication, automatic reverse-order (LIFO) compensation on step failure /BudgetExceededError/app.cancel(), two-phase@ChannelRole+@Channel(onPauseClosedon cancel,PauseClosedErroron late resume),.toParallelAgents().acceptedBy(QuorumVoteArbiter).joinQuorum({ min: 2, max: 2 }), and SQLite crash recovery. - Representative code:
@Action({ name: "reserve-flight-action", input: TravelRequestDto, output: FlightReservationDto, compensateWith: ReleaseFlightAction, committedBy: IssueFinalItineraryAction }) - Quickstart commands:
Terminal window cd 04-travel-booking-saganpm run check && npm test && npx tsx src/demo.ts - Expected proof output:
npx tsx src/demo.tsoutputs JSON confirmingscenarioA_PaymentDeclined.compensationOrder: ["release-hotel-action", "release-flight-action"],scenarioB_BudgetExceeded.flightState: "RELEASED",scenarioC_CancelAndRollback.closedReason: "cancelled",scenarioD_RollbackCrashAndSqliteRecovery.sqliteResumedOutputStatus: "CONFIRMED", andscenarioE_QuorumApproval.outcomeStatus: "CONFIRMED_BY_QUORUM". - Failure scenarios tested: Payment gateway decline (
PaymentGatewayDeclinedError), mid-flightBudgetExceededError, concurrentapp.cancel()vsapp.resume()race, crash inside a compensation handler (CompensationFailedError) followed by idempotent recovery replay, and rejected branch inside a 2-of-3 quorum. - Guarantee boundary:
- Verified: Single-node SQLite WAL durability, deterministic LIFO compensation ordering, idempotent
step.idempotencyKeypropagation to external ledgers, and lease-fenced recovery within the configured SQLite store. - Not verified: Multi-datacenter distributed consensus or compensation when an external third-party API permanently rejects its own refund/release endpoint without an idempotency contract.
- Verified: Single-node SQLite WAL durability, deterministic LIFO compensation ordering, idempotent
- Repository directory:
agbossjs/agboss-examples/04-travel-booking-saga
5. 05-cluster-work-stealing — Distributed Child Work-Stealing, Leases & Backpressure (P1)
Section titled “5. 05-cluster-work-stealing — Distributed Child Work-Stealing, Leases & Backpressure (P1)”- Problem statement: Fan-out and recursive workflows executing on a single Node.js instance bottleneck CPU/concurrency and lose progress if a worker crashes mid-batch.
- Architecture overview:
CoordinatorWorkflowfans outChunkWorkerWorkflowacross cluster instances via.toParallelWorkflows(ChunkWorkerWorkflow, { placement: ChildPlacement.AnyInstance }), alongsideRecursiveDecomposerWorkflow(ThisWorkflow,maxDepth: 2), coordinated through shared SQLite WAL repositories (SqliteChildExecutionQueueRepository,SqliteExecutionLeaseRepository,SqliteExecutionTreeRepository,SqliteRateLimitRepository). - Main mechanisms demonstrated:
ChildPlacement.AnyInstancework-stealing, parent lease yielding while waiting for children, 30s lease heartbeat & stale-lease reclamation (recoverApp),ExecutionLeaseLostErrorsplit-brain fencing,maxConcurrentSteps: 2backpressure (HealthComponentKind.StepSlots),@HealthCheck(checkLiveness,checkReadiness), andIncompatibleResumeError. - Representative code:
.toParallelWorkflows(ChunkWorkerWorkflow, { placement: ChildPlacement.AnyInstance, maxItems: 8, onBranchError: ParallelErrorPolicy.CollectAll }) - Quickstart commands:
Terminal window cd 05-cluster-work-stealingnpm run check && npm test && npx tsx src/demo.ts - Expected proof output:
npx tsx src/demo.tsruns a 2-instance cluster over shared SQLite and prints JSON withworkStealing.batchSummary.succeededCount: 4,committedChunkEffects: 4,recursiveStatus: "finished", andhealth.readinessStatus: "healthy". - Failure scenarios tested: Worker crash mid-batch with 30s lease expiry and takeover by a surviving instance, zombie worker split-brain write fenced by
ExecutionLeaseLostError,maxConcurrentStepssaturation flipping readiness tounhealthywhile liveness stayshealthy, andIncompatibleResumeErroron workflow version drift. - Guarantee boundary:
- Verified: Multi-instance coordination over shared SQLite WAL storage (single host or shared POSIX/local disk), lease fencing, and step-slot backpressure.
- Not verified: Distributed network database backends (PostgreSQL/Redis adapters are on the roadmap and not shipped in
0.1.0).
- Repository directory:
agbossjs/agboss-examples/05-cluster-work-stealing
6. 06-enterprise-agent-mesh — Multi-Service A2A + MCP Mesh & Federation Check (P1)
Section titled “6. 06-enterprise-agent-mesh — Multi-Service A2A + MCP Mesh & Federation Check (P1)”- Problem statement: When independent microservices expose agents (
A2A) and tools (MCP), untyped payloads, missing authentication, circular cross-service loops, duplicate retries, and breaking schema changes cause cascading outages. - Architecture overview: Three separate AGBoss applications in one workspace —
apps/1-order-gateway(TriageGatewayApplication),apps/2-billing-a2a(BillingApplicationexposing@A2AExpose), andapps/3-catalog-mcp(CatalogApplicationexposing@McpExpose). - Main mechanisms demonstrated:
@A2AExpose+a2aHttpListener(app, { expose, callerResolver }),@A2AAgent,@McpExpose+@McpServer+@McpTool, Ed25519-signed mesh envelope propagation (origin,budget.remaining,deadline.remaining,callChain),MeshLoopDetectedError/HopsLimitExceededError,SqliteMeshRequestRepositoryidempotency deduplication,agboss check --federation, andagboss hub. - Representative code:
@A2AAgent({ name: "remote-billing-agent", description: "Calls Billing service over A2A", target: "billing-application/billing-workflow", url: "billingA2aUrl", input: BillingInquiryDto, output: BillingResolutionDto, price: usd(0.05) }) - Quickstart commands:
Terminal window cd 06-enterprise-agent-meshnpm run check && npm test && npx tsx apps/1-order-gateway/src/demo.ts - Expected proof output:
npx tsx apps/1-order-gateway/src/demo.tsboots the A2A + MCP services on loopback HTTP ports and prints JSON confirminga2aResolution.creditedUsd: 45,federationProof.compatibleOk: true,federationProof.breakingExitCode: 3, andfederationProof.breakingCodes: ["federation.incompatible-schema", "federation.missing-target"]. - Failure scenarios tested: Unauthenticated A2A caller rejection (
A2ACallerRejectedError), cross-service call-chain cycle (MeshLoopDetectedError), hop limit exhaustion (HopsLimitExceededError), and breaking cross-service contract drift caught byagboss check --federation. - Guarantee boundary:
- Verified: Cross-service contract verification (
agboss check --federation), Ed25519 JWS mesh envelope verification, loop/hop guards, and MCP/A2A request deduplication. - Not verified: External service mesh mTLS/ingress infrastructure or non-AGBoss third-party A2A implementations.
- Verified: Cross-service contract verification (
- Repository directory:
agbossjs/agboss-examples/06-enterprise-agent-mesh
7. 07-langgraph-migration — Deterministic Reference Migration (before-langgraph/ vs after-agboss/) (P0)
Section titled “7. 07-langgraph-migration — Deterministic Reference Migration (before-langgraph/ vs after-agboss/) (P0)”- Problem statement: Raw LangGraph workflows often accumulate a 15+ field mutable
Annotation.RootGod State where optional fields are read before they are initialized, stale loop critiques persist across iterations, and side effects lack idempotency keys. - Architecture overview: Side-by-side implementation of the same customer support & refund workflow in
before-langgraph/(raw@langchain/langgraphStateGraphwith a 15-fieldAnnotation.Root) andafter-agboss/(canonical AGBoss application with 10 narrow@Dtoclasses,@Router,@Agent,@Action, and@Channel). - Main mechanisms demonstrated: Migrating
Annotation.Rootto narrow@Dtohandoffs, replacing conditional edges with.toRouter().chooseOne()and.switch(caseOf(..., { about })), replacing parallel node fan-out with.toParallelAgents(), and addingstep.idempotencyKeyto@Action. - Representative code:
agent(ReplyReviewerAgent).returns(oneOf(ReplyApprovedDto, CritiqueNotesDto)).switch(caseOf(ReplyApprovedDto, { about: DraftReplyDto }).toRouter(RefundSizeRouter), caseOf(CritiqueNotesDto, { about: DraftReplyDto }).toAgent(ReplyWriterAgent)) - Quickstart commands:
Terminal window cd 07-langgraph-migrationnpm run check && npm test && npx tsx after-agboss/src/demo.ts - Expected proof output:
npx tsx after-agboss/src/demo.tsruns bothbefore-langgraphandafter-agbossdeterministically and outputs JSON comparingbeforeLangGraph.godStateFieldsCount: 15,firstWriteSawUndefinedDraft: true, andunusedFieldPersistedInState: trueagainstafterAgboss.status: "finished"andafterAgboss.path. - Failure scenario tested:
tests/migration-comparison.test.tsproves that the raw LangGraph state exposes uninitializedundefinedfields on first pass and retains dead state fields, whereas the AGBoss workflow enforces strict Path Scope provenance andmaxVisitsbounds. - Guarantee boundary:
- Verified: Deterministic structural comparison between a representative shared-state
StateGraphand its narrow-DTO AGBoss counterpart. - Not verified: This is a deterministic reference migration, not a universal benchmark across all possible LangGraph coding styles.
- Verified: Deterministic structural comparison between a representative shared-state
- Repository directory:
agbossjs/agboss-examples/07-langgraph-migration
How the 08-job-scout application works
Section titled “How the 08-job-scout application works”08-job-scout reads a candidate’s resume from disk, proposes a structured search brief, fetches live openings from public Greenhouse boards, ranks every match using the Jev decision model (JobFitJudge), explains why top matches fit using a SQLite FTS5 @Rag knowledge base (company_notes), and saves selected jobs through the official filesystem @McpServer after pausing for user approval (TerminalUserChannel):
import { Workflow, route, start } from "@agboss/core";import { WorkflowStartTextDto } from "@agboss/core/dto";
@Workflow({ name: "job-scout-workflow", version: "1.0.0", flow: [ start(ChatWorkflowStart) .returns(WorkflowStartTextDto) .toRouter(MainRouter) .chooseOne( route(ProfilerAgent) .toFinish(ChatWorkflowFinish), route(ScoutAgent) .toFinish(ChatWorkflowFinish), route(ShortlistAgent) .toFinish(ChatWorkflowFinish), ), ], defaults: { models: { temperature: 0 }, router: { model: "typesafe/jev-1.13" }, tools: { maxToolCalls: 8 }, }, providers: [JobFitJudge],})export class JobScout {}import { Agent, DecidedBy, Injectable, Router, WorkflowFinish, WorkflowStart } from "@agboss/core";import { WorkflowFinishTextDto, WorkflowStartTextDto } from "@agboss/core/dto";
@WorkflowStart({ name: "chat-workflow-start", description: "A message", input: WorkflowStartTextDto })export class ChatWorkflowStart {}
@WorkflowFinish({ name: "chat-workflow-finish", description: "The answer", output: WorkflowFinishTextDto })export class ChatWorkflowFinish {}
@Agent({ name: "profiler-agent", description: "Reads the resume", prompt: "Read the resume.", model: "moonshotai/kimi-k2.6" })export class ProfilerAgent {}
@Agent({ name: "scout-agent", description: "Finds jobs", prompt: "Find jobs.", model: "moonshotai/kimi-k2.6" })export class ScoutAgent {}
@Agent({ name: "shortlist-agent", description: "Saves jobs", prompt: "Save shortlist.", model: "moonshotai/kimi-k2.6" })export class ShortlistAgent {}
@Router({ name: "main-router", description: "Sends the message to the agent that answers it", decidedBy: DecidedBy.Model, prompt: "Pick the agent that answers the message.", input: { message: WorkflowStartTextDto }, routes: [ { prompt: "Reading the resume", target: ProfilerAgent }, { prompt: "Finding jobs", target: ScoutAgent }, { prompt: "Managing the shortlist", target: ShortlistAgent }, ],})export class MainRouter {}
@Injectable()export class JobFitJudge {}import { Application, EmptyEnvironment } from "@agboss/core";import { expect } from "vitest";import { replyWith, routeTo, testWith } from "@agboss/core/testing";import { JobScout } from "./job-scout.workflow.js";import { ChatWorkflowFinish, ChatWorkflowStart, MainRouter, ScoutAgent,} from "./job-scout.components.js";
@Application({ name: "job-scout-example-app", version: "1.0.0", environment: EmptyEnvironment, workflows: [JobScout], budgets: [JsExAppBudget, JsExTenantBudget, JsExExecBudget],})export class JobScoutExampleApp {}
const test = testWith(JobScoutExampleApp);
test("routes job search queries through MainRouter to ScoutAgent", async ({ app, mockLlm,}) => { mockLlm(MainRouter).thenReturn(routeTo(ScoutAgent)); mockLlm(ScoutAgent).thenReturn( replyWith("Found 2 matching Staff TypeScript roles."), );
const result = await app.execute(ChatWorkflowStart, { text: "Find Staff TypeScript roles", }); expect(result.finish).toBe(ChatWorkflowFinish); expect(result.output).toEqual({ text: "Found 2 matching Staff TypeScript roles.", });});Run 08-job-scout from a clone of agbossjs/agboss-examples:
cd agboss-examples/08-job-scoutnpm installnpx agboss chatnpx agboss describeWhat patterns are demonstrated in examples/flow-patterns?
Section titled “What patterns are demonstrated in examples/flow-patterns?”examples/flow-patterns (src/flow-patterns.application.ts) demonstrates four advanced AGBoss workflow patterns tested 100% offline with testWith and agboss check:
src/offer/(Review loop with{ about }):draft-agent→reviewer-agentreturningoneOf(ChangesRequestedDto, DraftApprovedDto). When changes are requested,caseOf(ChangesRequestedDto, { about: OfferDraftDto })routes toeditor-agent(maxVisits: 2), with.onError(VisitsLimitExceededError, ...)handling exhausted review cycles.src/credit/(Code router beside model router): Combines a Jev model router withcredit-limit-router(DecidedBy.Code), routing small orders tocharge-card-actionand larger orders toapproval-agent.src/review/(Parallel launches in waves): Runs a reviewer per document section via.toParallelAgents(...), joins their outputs, and launches a second wave with a critic alongside parallel fact-checker copies.src/topic/(RecursiveThisWorkflow): Researches broad topics by launching.toParallelWorkflows(ThisWorkflow, { maxItems })with@Workflow({ maxDepth: 3 }).
Inspect the pattern application directly with the CLI:
cd examples/flow-patternsnpx agboss describe --application src/flow-patterns.application.tsnpm test