Writing a spec

The short guide to writing a good Stoic spec quickly: the loop, the shape that works for code modules, how many tests to write, and how to change a spec later.

A short guide for whoever turns a task into a spec, person or agent. docs/REFERENCE.md has the whole language; this is what you need to write a good spec quickly. Print it any time with stoic guide.

The loop

stoic spec.stoic          # compile: fix every error before going on
stoic fmt spec.stoic      # tidy
stoic lock spec.stoic     # freeze the tests in stoic.lock
stoic brief spec.stoic    # the exact direction to implement from
# implement it; the tests write results.txt
stoic verify results.txt --strict

The spec is the plan. The compiler is the guard: it refuses a spec whose examples contradict their own rules, whose tests name a field or event that doesn't exist, or whose rejecting input says nothing about what must not happen. Once it compiles and is locked, implement from the brief. It is the whole contract.

What a spec says

Say everything the implementer needs and nothing twice:

  • the file, its export and how it's called;
  • each operation: its arguments, what it returns, its errors in check order, and its side effects;
  • every rule, limit, rounding and ordering, once, where it applies;
  • what is deliberately left open.

Aim for a spec no longer than about twice the task. If it's longer, you're restating rules in several places or writing long setups.

A module, method by method

Nothing is a keyword: tags, field and event names are yours. This shape works well for code modules:

Stoic
<!--! Every method returns { ok: true, … } or exactly { ok: false, error }. A failed call changes nothing. -->

<module!:cart #file="cart.mjs" #export="createCart(catalog)">
  <method:add @call="add(sku, qty = 1): add qty to sku's line, appending a new line at the end"
    #errors="UNKNOWN_SKU, then QTY, then STOCK"
    #qty("an integer", ^"on a fresh cart, call add('apple', value)", >=1, <=99,
      +=1, +=99, -=0, -=100, -=1.5, -"2",
      +=>="{ ok: true }", -=>="{ ok: false, error: 'QTY' }")>
    <!--! QTY also applies when the line's total would pass 99. -->
  </method>
  <method:totals @call="totals(): { subtotal, discount, shipping, tax, total } in integer cents"
    #tax="8% of (subtotal - discount), rounded half up" />
</module>

<test:merge_cap=add ^"apple in the catalog with stock 500" ^"add('apple', 98)"
  @call="'apple', 2" =>="{ ok: false, error: 'QTY' }" =>!"the line changes" />
  • Strict where it matters. <module!:…> makes everything inside strict; use ? on anything that may bend.
  • Rules go on fields. Limits (>=1), quoted rules ("an integer"), a value (#tax="…"), or a note (#qty"whole units"(…)). A value the limits don't cover goes after |: #cycles(>=1, |null) reads "must be at least 1, or null", so +=null is a valid example, not prose.
  • Behaviour goes in the handler. @call="…" is passed to the implementer verbatim, so write it as you would say it.
  • Guidance goes in kept comments. <!--! … --> reaches the implementer on the element it's in or before, or at file level when it stands alone. Ordinary <!-- … --> comments are private.

Tests

Every test is locked, and each is something the implementer must build and pass. Write the fewest that pin the behaviour down:

  • One test per rule, and one per boundary on each side: 99 accepted and 100 rejected, a balance of 499 allowed and 500 blocked. Not every value in between. On a field with examples the compiler checks it: a limit needs a rejected example just past its bound (-=100 for <=99, -"ad" for a length >=3), !" " a rejected one containing a space, |null an accepted +=null; untested-rule: …; add -=100 names the one missing.
  • Check order only where two errors can apply at once. Test the pairs that can really collide, not every adjacent pair.
  • Field examples are the cheap tests. +=1, -=100, -"2" on a field, with one ^"…" step saying how each is tried. Bare values are values and quoted ones are text, so -=1.5 and -"2" are different tests. Say what accepting and rejecting one shows, +=>="{ ok: true }" and -=>="{ ok: false, error: 'QTY' }", so each example reports what the code returned and verify, not the test, decides; an example may say its own (-=1.5=>="…").
  • Examples are single values or text. A bare example is a number, true, false, null, NaN or Infinity; +"[1]" is the text [1], not an array. An array or object input goes in a test element's action instead: <test:no_weights=split @call="100, []" =>="…" />.
  • Test elements are for behaviour across calls: <test:name=target ^"step" … #input="v" @action="args" =>label="…" =>!"…">. The target is a named element, the inputs are its fields, and the action is one of its events. A test in another file binds to it there (=cart.add): define each name once per lock, or stoic lock refuses the second.
  • Keep setups short. Define shorthand once in a file-level kept comment (<!--! "on day N": now() returns N. "m1 borrowed b1": addMember('m1', 'standard'), addBook('b1', 1), borrow('m1', 'b1'). -->), then write ^"m1 borrowed b1 on day 0".
  • Every test checks a value. Words can't be verified, so a test with only =>"…" can quietly assert something else and still pass (its summary says (not checked), and compiling warns). =>="{ ok: false, error: 'QTY' }" makes the test report what it observed (pass ID = …), and verify fails it unless that equals the locked value. To check several, label each: =>total="1800" =>cycles="1". Work every number out before you lock. A value compares whole, so when the code returns more than the spec states ({ ok: true, line } for +=>="{ ok: true }"), say in the step or a kept comment what the test reports (report { ok } alone), or check only what matters with a label (=>ok="true"). stoic verify --strict fails a test without one.
  • Values compare as Stoic values: numbers by value (1.0 is 1), strings in either quote, objects by key set, so {"ok":false} matches { ok: false }. Quote text (=>="'QTY'"): a bare word isn't a value, so it is compared as text, whitespace between symbols aside. stoic harness --lang node|python|sh prints the reporter the tests write these lines with. Save the node one outside test/ and *.test.* names (next to the spec), or node --test runs it as a test. It appends, so a run starts from a clean results file only once you delete it (stoic verify --run does).
  • Say what must not happen (=>!"…") when an input breaks a rule. The compiler insists.

Leaving things open

If the task doesn't decide something, don't invent a rule and don't test it. Say so once, in a file-level kept comment:

Stoic
<!--! Left open: whether coupon codes are trimmed. Your choice; say which in a code comment. -->

Changing a spec later

Edit the spec in place, then before relocking see exactly what your edit did:

stoic check spec                      # compile, formatting and what changed since the lock
stoic verify /dev/null --no-against   # every locked test's state against the edited spec

It lists tests added, removed and changed. A test whose own steps and expectations changed is a real edit, so make sure each one is intended. A test that changed only because the element it tests changed should still hold as written; check that it does. Then stoic lock, which lists the same split: edited tests one per line, the rest as one line per target, and each checked value it changed (value fee500: 44 -> 45 (spec/fees.stoic:5)): say which in your report. A test whose behaviour the change removes is deleted, and its replacement gets a new name that says what it now checks.

Several agents on one spec

Give each agent a segment in stoic.segments, beside the lock:

billing @agent-a: invoice money
cart @agent-b: cart checkout

A segment lists top-level elements, with what's nested in them and their tests. Keep each file to one segment, and draw segments so few tests reuse (->) another's elements. An agent relocks with stoic lock spec --as agent-b, which refuses any change outside its segments.

Put rules a ticket mustn't change in an owner's segment (rules @product: refund): another agent, on a different ticket in parallel, can't relock them. Blocked by one, an implementer reports dispute ID: why, and the owner settles it with stoic review --as product.

Before you lock

  • stoic spec.stoic compiles with no errors.
  • Every rule in the task is stated once, and has a test or an example at each of its boundaries.
  • Every expected number was worked out, not guessed.
  • Shorthand used in steps is defined in a kept comment.
  • Open points are listed as left open, with no tests.
  • stoic brief spec.stoic reads as a complete instruction: you could build exactly the right thing from it alone.