The Itinera bookJava edition

Part 5: Designing with Itinera, Chapter 43

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's, with its approved paths, and without what chapters 31 to 35 added. An agent was asked to cap discounts, and changed the pricing step alone:

Java, from the program ch43_working_with_agents
/**
 * 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
final class Price implements ItineraStep {
  private final long price;
  private final Optional<Long> discount;

  Price(@Input long price, @Input Optional<Long> discount) {
    this.price = price;
    this.discount = discount;
  }

  public Outcome run(Contributor contributor) {
    long taken = Math.min(discount.orElse(0L), price / 2);
    contributor.contribute("amount", price - taken);
    return 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' file, as Proposed, a class after the test class, beside the approved workflow of chapter 23, with ship and no retry budget, and only the main carrier:

Java, from the program ch43_working_with_agents.test
/**
 * 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.class, Desk.class},
    policies = {Notify.class})
@WithStep(
    step = Lookup.class,
    name = "lookup",
    policies = {AlreadyCompleted.class})
@WithStep(step = Price.class, name = "price")
@WithStep(
    step = Charge.class,
    name = "charge",
    rescue = RenewCard.class,
    policies = {Audit.class, Outage.class})
@WithStep(
    step = Ship.class,
    name = "ship",
    policies = {FailedShipping.class})
final class Proposed implements ItineraWorkflow, Messages, Refunds {
  @Override
  public void tell(String customer, String message) {
    System.out.println("email to " + customer + ": " + message);
  }

  @Override
  public void refund(String receipt, long amount) {
    System.out.println("the bank gives " + amount + " back on receipt " + receipt);
  }

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

  /** The main carrier, for every attempt of a step. */
  @Provider(perAttempt = true, key = "carrier")
  public Provided<Carrier> carriers() {
    return provide(new MainCarrier());
  }

  /**
   * Gives the shipping the weight of the order's parcel, as the warehouse describes it. Every other
   * input of the shipping is read from the data bag.
   */
  @InputAdapter(steps = {"ship"})
  public Supplied parcels(@Key String key, @FromWorkflow Parcel parcel) {
    return key.equals("weight") ? supply(parcel.weight()) : fromDataBag();
  }

  /** Names each journey after its order. */
  @IdGenerator
  public String orderNumber(DataBag data) {
    String order = data.read("order", TypeToken.of(String.class)).orNull();
    if (order == null) throw new IllegalStateException("an order without a number");
    return order;
  }

  /** The order book, which has the orders completed before today. */
  @Provider(key = "orderBook")
  public Provided<OrderBook> ledger() {
    return provide(new Ledger(List.of("A-13")));
  }
}

What it names is as earlier chapters show it: the lookup, AlreadyCompleted, OrderBook and the log in chapter 22, Payments in chapter 14, Carrier in chapter 12, MainCarrier in chapter 13, the charge and the audit in chapter 20, RenewCard in chapter 14, the shipping and Outage in chapter 17, FailedShipping and Refunds in chapter 23, Notify and Messages in chapter 19, the input adapter in chapter 21, the ID generator and the desk in chapter 11.

Chapter 30's pathOf now makes its order with orderOf, and proposedPathOf runs the same order through the proposal, with the same fakes, TestBank and TestCarrier. NewOrder is as chapter 25 shows it, and Parcel as chapter 21 does:

Java, from the program ch43_working_with_agents.test
/** What the shop knows about an order of 30 with a parcel of this weight. */
private static NewOrder orderOf(String order, long weight) {
  return new NewOrder(order, "Ann", 30, new Parcel(weight, List.of(20L, 15L, 5L)), "ann-2028");
}

/**
 * Runs an order 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.
 */
private static List<String> pathOf(String order, long weight, TestBank bank, TestCarrier carrier)
    throws Refusal {
  var recorder = new RecordingReporter();
  var instance =
      TestInstanceBuilder.of(new Orders("email"))
          .initialData(orderOf(order, weight))
          .reporter(recorder)
          .fakeProvider("bank", Payments.class, () -> new Provided.Instance<>(bank))
          .fakeProvider("carriers", Carrier.class, () -> new Provided.Instance<>(carrier))
          .create();
  new LocalExecutor().run(instance);
  return recorder.getPath();
}

/** Runs the same order as {@code pathOf}, through the proposed workflow. */
private static List<String> proposedPathOf(
    String order, long weight, TestBank bank, TestCarrier carrier) throws Refusal {
  var recorder = new RecordingReporter();
  var instance =
      TestInstanceBuilder.of(new Proposed())
          .initialData(orderOf(order, weight))
          .reporter(recorder)
          .fakeProvider("bank", Payments.class, () -> new Provided.Instance<>(bank))
          .fakeProvider("carriers", Carrier.class, () -> new Provided.Instance<>(carrier))
          .create();
  new LocalExecutor().run(instance);
  return recorder.getPath();
}

A test runs each approved order through the proposal, and says which paths it keeps and how the others change:

Java, from the program ch43_working_with_agents.test
@Test
void the_proposed_flow_keeps_two_approved_paths_and_changes_two() throws Refusal {
  assertEquals(
      pathOf("A-1", 2, TestBank.CHARGES, TestCarrier.COLLECTS_ALL),
      proposedPathOf("A-1", 2, TestBank.CHARGES, TestCarrier.COLLECTS_ALL));
  assertEquals(
      pathOf("A-3", 2, TestBank.IS_DOWN, TestCarrier.COLLECTS_ALL),
      proposedPathOf("A-3", 2, TestBank.IS_DOWN, TestCarrier.COLLECTS_ALL));
  assertEquals(
      List.of(
          "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"),
      proposedPathOf("A-2", 90, TestBank.CHARGES, TestCarrier.COLLECTS_ALL));
  assertEquals(
      List.of(
          "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"),
      proposedPathOf("A-4", 60, TestBank.CHARGES, TestCarrier.COLLECTS_NONE));
}

It prints:

What running the tests of ch43_working_with_agents prints, recorded in ch43_working_with_agents.txt
JUnit Jupiter > JourneysTest > a charge whose bank is down is given up and never rescued :: STARTED
JUnit Jupiter > JourneysTest > a charge whose bank is down is given up and never rescued :: SUCCESSFUL
JUnit Jupiter > JourneysTest > a parcel no carrier collects is tried once more then given up :: STARTED
JUnit Jupiter > JourneysTest > a parcel no carrier collects is tried once more then given up :: SUCCESSFUL
JUnit Jupiter > JourneysTest > a parcel over the limit is given up after its first attempt :: STARTED
JUnit Jupiter > JourneysTest > a parcel over the limit is given up after its first attempt :: SUCCESSFUL
JUnit Jupiter > JourneysTest > an order the bank charges and the carrier takes is shipped :: STARTED
JUnit Jupiter > JourneysTest > an order the bank charges and the carrier takes is shipped :: SUCCESSFUL
JUnit Jupiter > JourneysTest > the proposed flow keeps two approved paths and changes two :: STARTED
JUnit Jupiter > JourneysTest > the proposed flow keeps two approved paths and changes two :: SUCCESSFUL

Test run finished after 409 ms
[         2 containers found      ]
[         0 containers skipped    ]
[         2 containers started    ]
[         0 containers aborted    ]
[         2 containers successful ]
[         0 containers failed     ]
[         5 tests found           ]
[         0 tests skipped         ]
[         5 tests started         ]
[         0 tests aborted         ]
[         5 tests successful      ]
[         0 tests failed          ]

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 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.