# Working with agents

## What you want to do

The shop now works with coding agents, which change its steps and, sometimes, its workflow. You want an agent to change a business rule without changing how an order travels through the shop, and to know, without reading every line it wrote, whether the flow changed and how.

## The code

The program is [chapter 30](https://itinera-dev.org/book/typescript/30-testing-a-whole-journey.md)'s module, with its approved paths, so it has none of what chapters 31 to 36 added to the shop. An agent was asked to cap discounts, and changed the pricing step alone:

TypeScript, from the program [`ch43_working_with_agents`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch43_working_with_agents.ts)

```typescript
/**
 * Works out what an order costs: its price, less its discount if it has one,
 * given back as the amount to charge. A discount takes at most half the price
 * off.
 */
@step()
export class Price extends Step {
  constructor(
    @input("price", integer) private readonly price: number,
    @input("discount", optional(integer))
    private readonly discount: Option<number>,
  ) {
    super();
  }

  override run(@contributor() contributor: Contributor): Outcome {
    const discount = Math.min(
      this.discount.unwrapOr(0),
      Math.floor(this.price / 2),
    );
    contributor.contribute("amount", this.price - discount);
    return this.succeed();
  }
}
```

Another agent proposes a change to the flow: a parcel the carrier won't collect should be given up at once, rather than tried again with the backup carrier. Before it replaces the workflow, the shop declares the proposal in its tests, beside the approved workflow of [chapter 23](https://itinera-dev.org/book/typescript/23-undoing-a-charge-when-the-shipping-fails.md), with `ship` and no retry budget, and only the main carrier:

TypeScript, from the program [`ch43_working_with_agents.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch43_working_with_agents.test.ts)

```typescript
/**
 * The shop's workflow as an agent proposes to change it: a parcel the carrier
 * won't collect is given up at once, without trying the backup carrier.
 */
@workflow({ name: "orders", reporters: [Log, Desk], policies: [Notify] })
@withStep(Lookup, { name: "lookup", policies: [AlreadyCompleted] })
@withStep(Price, { name: "price" })
@withStep(Charge, {
  name: "charge",
  rescue: RenewCard,
  policies: [Audit, Outage],
})
@withStep(Ship, { name: "ship", policies: [FailedShipping] })
class Proposed extends Workflow implements Messages, Refunds {
  async tell(customer: string, message: string): Promise<void> {
    console.log(`email to ${customer}: ${message}`);
  }

  async refund(receipt: string, amount: number): Promise<void> {
    console.log(`the bank gives ${String(amount)} back on receipt ${receipt}`);
  }

  /** Names each journey after its order. */
  @idGenerator()
  orderNumber(@dataBag() data: DataBag): string {
    return data.read("order", string).option().expect("the order's number");
  }

  /** Gives the shipping the weight of the order's parcel. */
  @inputAdapter({ steps: ["ship"] })
  parcels(
    @key() key: string,
    @fromWorkflow("parcel", PARCEL) parcel: Parcel,
  ): Supplied {
    if (key !== "weight") return this.fromDataBag();
    return this.supply(parcel.weight);
  }

  /** The order book, which has the orders completed before today. */
  @provider(ORDER_BOOK, { key: "orderBook" })
  ledger(): Provided<OrderBook> {
    return this.provide(new Ledger(["A-13"]));
  }

  /** The bank, as the payment client of the journey. */
  @provider(PAYMENTS, { key: "payments" })
  bank(): Provided<Payments> {
    return this.provide(new Bank(2026));
  }

  /** The main carrier. */
  @provider(CARRIER, { key: "carrier", perAttempt: true })
  carriers(): Provided<Carrier> {
    return this.provide(new MainCarrier());
  }
}
```

The module now exports each piece the proposal names, as it exported what [chapter 30](https://itinera-dev.org/book/typescript/30-testing-a-whole-journey.md)'s tests import. Those pieces are as [chapter 26](https://itinera-dev.org/book/typescript/26-running-async-journeys-while-others-wait.md) shows the charge, `RenewCard`, the shipping, `Notify`, `FailedShipping`, `Payments`, `Carrier`, `Messages` and `Refunds`, [chapter 22](https://itinera-dev.org/book/typescript/22-finishing-a-journey-early.md) the lookup, `AlreadyCompleted`, `OrderBook`, `ORDER_BOOK`, `Ledger` and the log, [chapter 21](https://itinera-dev.org/book/typescript/21-deciding-where-a-steps-data-comes-from.md) `Parcel` and `PARCEL`, [chapter 20](https://itinera-dev.org/book/typescript/20-an-optional-input.md) the audit, [chapter 17](https://itinera-dev.org/book/typescript/17-giving-up-a-step-early.md) `Outage`, [chapter 7](https://itinera-dev.org/book/typescript/07-giving-a-step-the-tools-it-needs.md) the tokens `PAYMENTS` and `CARRIER`, and [chapter 11](https://itinera-dev.org/book/typescript/11-naming-a-journey.md) the desk.

[Chapter 30](https://itinera-dev.org/book/typescript/30-testing-a-whole-journey.md)'s `pathOf` now makes its order with `orderOf`, and `proposedPathOf` runs the same order through the proposal, with the same fakes, `TestBank` and `TestCarrier`, as [chapter 30](https://itinera-dev.org/book/typescript/30-testing-a-whole-journey.md) shows them:

TypeScript, from the program [`ch43_working_with_agents.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch43_working_with_agents.test.ts)

```typescript
/**
 * What the shop knows about one of Ann's orders, of 30, with a parcel of this
 * weight.
 */
function orderOf(order: string, weight: number) {
  return {
    order,
    customer: "Ann",
    price: 30,
    parcel: { weight, size: [20, 15, 5] },
    card: "ann-2028",
    giftCard: false,
  };
}

/**
 * Runs one of Ann's orders, of 30, with a parcel of this weight, through the
 * shop's real steps and policies, with the test's bank and carriers in place
 * of the shop's, and gives back its journey's path.
 */
async function pathOf(
  order: string,
  weight: number,
  bank: TestBank,
  carrier: TestCarrier,
): Promise<readonly string[]> {
  const recorder = new RecordingReporter();
  const instance = Orders.build("email").instance(orderOf(order, weight), {
    reporters: [recorder],
  });
  fakeProvider(instance, "bank", PAYMENTS, (provide) => provide(bank));
  fakeProvider(instance, "carriers", CARRIER, (provide) => provide(carrier));
  await new LocalExecutor().run(instance);
  return recorder.path;
}

/** Runs the same order as `pathOf`, through the proposed workflow. */
async function proposedPathOf(
  order: string,
  weight: number,
  bank: TestBank,
  carrier: TestCarrier,
): Promise<readonly string[]> {
  const recorder = new RecordingReporter();
  const instance = Proposed.build().instance(orderOf(order, weight), {
    reporters: [recorder],
  });
  fakeProvider(instance, "bank", PAYMENTS, (provide) => provide(bank));
  fakeProvider(instance, "carriers", CARRIER, (provide) => provide(carrier));
  await new LocalExecutor().run(instance);
  return recorder.path;
}
```

A test runs each approved order through both, and says which paths the proposal keeps, and what it makes of the others:

TypeScript, from the program [`ch43_working_with_agents.test`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch43_working_with_agents.test.ts)

```typescript
test("the proposed flow keeps two approved paths and changes two", async () => {
  const kept = [
    {
      order: "A-1",
      weight: 2,
      bank: new TestBank("charges"),
      carrier: new TestCarrier("collects all"),
    },
    {
      order: "A-3",
      weight: 2,
      bank: new TestBank("is down"),
      carrier: new TestCarrier("collects all"),
    },
  ];
  for (const { order, weight, bank, carrier } of kept) {
    assert.deepEqual(
      await proposedPathOf(order, weight, bank, carrier),
      await pathOf(order, weight, bank, carrier),
    );
  }
  assert.deepEqual(
    await proposedPathOf(
      "A-2",
      90,
      new TestBank("charges"),
      new TestCarrier("collects all"),
    ),
    [
      "lookup attempt 1 succeeded",
      "price attempt 1 succeeded",
      "charge attempt 1 succeeded",
      "ship attempt 1 failed: over-parcel-limit",
      "ship given up: failure",
      "journey failed at ship: over-parcel-limit",
    ],
  );
  assert.deepEqual(
    await proposedPathOf(
      "A-4",
      60,
      new TestBank("charges"),
      new TestCarrier("collects none"),
    ),
    [
      "lookup attempt 1 succeeded",
      "price attempt 1 succeeded",
      "charge attempt 1 succeeded",
      "ship attempt 1 failed: too-heavy",
      "ship given up: failure",
      "journey failed at ship: too-heavy",
    ],
  );
});
```

`node --test` prints:

What running the tests of `ch43_working_with_agents` prints, recorded in [`ch43_working_with_agents.txt`](https://github.com/itinera-dev/book/blob/main/typescript/tested/ch43_working_with_agents.txt)

```text
✔ an order the bank charges and the carrier takes is shipped (24.939153ms)
✔ a parcel over the limit is given up after its first attempt (12.127179ms)
✔ a charge whose bank is down is given up and never rescued (4.468153ms)
✔ a parcel no carrier collects is tried once more, then given up (9.698609ms)
✔ the proposed flow keeps two approved paths and changes two (28.517247ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 341.112793
```

## How it works

1. **A business rule changes in a step, and the paths hold.** The pricing now caps the discount at half the price, and all four approved paths still pass: the step decides an amount, and the flow around it is the same. To change it, the agent read one step, which names its inputs by key and decides nothing about what comes next.
2. **A flow change shows in the paths it changes.** The proposal changes the path of the parcel no carrier collects, as intended: `ship given up: failure` after one attempt. It also changes the path of the parcel over the limit, which nobody asked for. That order was given up by `failedShipping`, in the hook it runs before a retry; with no retry budget there is no retry, so the hook never runs, and the journey now fails with `over-parcel-limit` instead of `no-carrier-can-take-it`. The test says so before any order takes that path.
3. **A path is the flow a person agreed.** An approved path changes only when a person agrees to the new one. A failing path test is not a test to fix: it is a flow change waiting for that decision, here two of them.
4. **One rule for every change to a step: it decides nothing about the flow.** A step that tries its work again, calls another service when the first fails, or tells anyone anything has taken a decision that belongs elsewhere, as [chapter 40](https://itinera-dev.org/book/typescript/40-recognising-a-decision-in-the-wrong-place.md) showed. A reviewer, a person or an agent, checks every change to a step for that, and every change to a workflow, a policy or a provider against the paths.

The shop gives its agents this paragraph in its `AGENTS.md`:

> Business rules live in steps; the flow lives in the workflows, their policies and their providers. A change to a step never decides anything about the flow: it does not try its work again, fall back to another service or tell anyone, and it reports what happened as an outcome. A change to a workflow, a policy or a provider is a flow change: say so in the pull request, show which approved paths it changes, and never edit an approved path to make a test pass. A person approves every new path.

This is where the book ends, for now. Its workflows run one after the other, from start to end, in one program. Later tiers of Itinera will add moving a journey to another workflow, running a workflow from inside another, and journeys that survive a crash and resume, each with a part of this book of its own.

## Outcomes

We have shown how an agent changes a business rule without touching the flow, and how a proposed change to the flow shows in the paths it changes.

| The usual way                                                                                 | With Itinera                                                                            |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------- |
| Whether a change altered the flow is often found by reading the whole diff, or in production. | A business rule changes in a step, and the approved paths say whether the flow changed. |
| A side effect of a flow change, such as a check that no longer runs, often goes unnoticed.    | The paths it changes are listed by a test, for a person to approve.                     |
