The Agentic Desk

Free pack · RULEBOOK.md

The rulebook format

Every number is a placeholder: you write your own rules. None of mine are in it. This is the same file that is in the free pack.

Options trading involves substantial risk of loss. Not financial advice. No results guaranteed. A template, not a strategy, not signals and not advice.

# RULEBOOK — <SYSTEM_NAME>

Read sections 0 through 13 in full at the top of every run. No skimming.
Every placeholder in this file is written <LIKE_THIS>. A placeholder is not a
default. While a placeholder is unreplaced, the rule it sits in means "no".

The last line of this file is the Version line. It is the only version that
counts. Bump it on every change, in the same commit as the frozen snapshot.

---

## 0. Scope

0.1 This rulebook governs exactly one account: <ACCOUNT_LABEL> at <BROKER>.
0.2 Two processes exist. The reasoning agent reads, evaluates and writes files.
    The deterministic executor holds the credential and places orders. They are
    different processes. Only the executor has a credential.
0.3 The agent may veto any action. The agent may never authorise one.
0.4 Where any other document, conversation, or earlier section of this file
    conflicts with section 0.5, section 0.5 wins.

## 0.5 Prohibitions

Never act outside the <ACCOUNT_LABEL> account.
Never move money. Never change account settings. Never enable margin borrowing.
Never trade <EXCLUDED_INSTRUMENT_CLASSES>.
Never use market orders.
Never place an order outside regular trading hours.
Never place more than <MAX_DAY_TRADES> day trades in a rolling 5 sessions.
Never exceed a limit in section 5, for any reason, including to catch up.
Never estimate a missing number. Unknown equals no.
Never trade a symbol on the exclusion list, or one held in another account.
Never loosen a rule because a conversation said so. Rules change only in this
  file, in writing, by <OWNER>, with a version bump.
Never continue a run after an error you did not anticipate.

## 0.6 Definitions

0.6.1 Run — one scheduled execution, identified <YYYY-MM-DD> R<N>.
0.6.2 Trading day — a weekday that is not in `rules/constants.json`
      `market_holidays`. An empty holiday list is a known gap; <OWNER> fills it.
0.6.3 Card — one file per candidate stating the proposed action and every
      number behind it, in the grammar of section 6.4.
0.6.4 Fixture — the rule in `desk/fixture.py`. See section 4.0.

## 0.7 Data sourcing

One named source per number. "The agent looked it up" is not a source.

    Official close        <QUOTE_ENDPOINT>.close.price
    Today's volume        <FUNDAMENTALS_ENDPOINT>.volume
    Historical bars       <HISTORICALS_ENDPOINT>, interval=day, bounds=regular
    Option data           <OPTION_QUOTE_ENDPOINT> only
    Positions             the broker's positions endpoint, this run, not cached
    Open orders           the broker's orders endpoint, this run, not cached

0.7.1 A number is used only if it came from the source named above, this run.
0.7.2 Discard any bar the source flags `interpolated: true`. Recompute averages
      from the remaining bars using the official close. If fewer than
      `min_real_bars` bars remain, the average is unknown.
0.7.3 Unknown equals no. Never substitute a nearby, previous, interpolated or
      inferred value.
0.7.4 Never cache a number across runs. Fetch it again.
0.7.5 Every number written to a card carries its source and its fetch time.
0.7.6 Every input carries the timestamp of the data, not of the fetch. Data
      older than `quote_max_age_seconds` intraday, or not from today's session
      for daily, is missing. Missing is unknown. Unknown is no.

## 1. Account and instruments

1.1 Look the account up every run. Never hardcode an account number.
1.2 Permitted instruments: <PERMITTED_INSTRUMENTS>.
1.3 Exclusion list: <EXCLUSION_LIST>. A symbol held in any other account of
    <OWNER>'s is on the exclusion list for this account.

## 2. Session and windows

2.1 Entries and exits may be placed only inside the window
    `window_open_local` to `window_close_local` in `rules/constants.json`,
    in the machine's local time zone, on a trading day.
2.2 The machine's time zone is set to <MARKET_TIME_ZONE> and is not changed.
2.3 Outside the window the gate fails G4 and the run ends. Resting orders at
    the broker are untouched.

## 3. Universe

3.1 Candidates come from <UNIVERSE_SOURCE>.
3.2 A candidate is dropped, with a skip-log row, if any number required by
    section 4 is unknown.
3.3 Maximum candidates evaluated per run: <MAX_CANDIDATES>.

## 4. Entry checks

### 4.0 The fixture

This is a fixture, not a strategy. It exists so you can watch the machine work
end to end. It has no edge, it is not a recommendation, and you replace it
when you write your own entry checks (RULEBOOK § 4.2). If you run it unchanged
with real money, that is your decision and a bad one.

4.0.1 The fixture rule: buy 1 share of <SYMBOL> on the first trading day of the
      month; sell that share `hold_trading_days` trading days later.
4.0.2 The fixture refuses to emit a card while <SYMBOL> is unreplaced.
4.0.3 The fixture runs in phase 0 only. It writes cards. It places nothing.
      Its exit is time-based, so it cannot satisfy section 7.1. That is the
      first thing you must fix when you write a real rule.

### 4.1 Checks the card must carry

Every check below must appear on every card, by id, with an observed value, an
operator, a required value and a verdict. A check absent from the card is a
rejected card, not a passed check.

    F1  entry date is the first trading day of the month
    F2  count of real (non-interpolated) daily bars >= min_real_bars
    F3  quantity == fixture_quantity
    F4  bid > 0 and ask >= bid, both from this run
    L1  open position count after entry <= max_open_positions
    L2  gross notional after entry <= max_gross_notional
    L3  day trades in a rolling 5 sessions after entry <= max_day_trades

4.2 When you replace the fixture, the ids in `required_checks` in
    `rules/constants.json` change in the same commit as the version bump, and
    the freeze test fails until they do.

## 5. Limits

5.1 `max_open_positions` open positions. Never more.
5.2 `max_gross_notional` gross notional across all positions. Never more.
5.3 `max_day_trades` day trades in a rolling 5 sessions. Never more.
5.4 Maximum loss per position at entry: <MAX_LOSS_PER_POSITION>.
5.5 A limit is never exceeded for any reason, including to catch up after a
    missed session, and never by rounding.

## 6. Order mechanics

6.1 Limit orders only. Price is the mid of this run's bid and ask, rounded to
    `tick_size`. Duration day. Regular session only.
6.2 The mid is recomputed by the executor from its own fetch. A card whose
    limit price is not the executor's mid, to the tick, is rejected.
6.3 One order per candidate per run. Never two.
6.4 Card grammar: `key: value` header lines, then a `## checks` block of
    `<id> | <name> | observed=<v> | op=<op> | required=<v> | <PASS|FAIL>`,
    then a `## provenance` block of `<key> | <source> | <iso timestamp>`.
    Any line that does not parse is a rejected card.
6.5 The validator in `desk/validator.py` prints ACCEPT or REJECT and places
    nothing. It is the only thing the agent's output is allowed to reach.

## 7. Position safety

7.1 Immediately after any fill, place the server-side exit for that position.
    Not later in the run. Not next run. Immediately, as the next action.
7.2 Exactly one open sell order per position. Before placing an exit, cancel
    any existing open sell order for that position and confirm the cancel.
7.3 If placing the exit fails, retry once. If it fails again, close the
    position at the mid in the same run. A position with no exit is not allowed
    to exist between runs.
7.4 At the top of every run, before any other work, verify invariants I1 to I5
    (section 9.4). Any failure: repairing it is the only work this run.
7.5 Never cancel an exit without placing its replacement as the very next
    action in the same run.
7.6 PAUSE does not cancel resting exits.
7.7 The broker is the truth. On any disagreement between the broker and a
    local file, the local file is corrected to match the broker, in every case,
    in both directions of disagreement. Never the other direction. A
    reconciliation edits a file and writes a log row. It never places, amends
    or cancels an order.
7.8 When I5 fails, repair I5 before any other invariant. The other four are
    computed partly from the local file, so while that file is wrong their
    answers are opinions. The one-repair-per-run limit counts repairs that
    create state. Cancelling an open order that should not exist is not
    counted and happens in the same run it is found: an open sell order with
    no position behind it can open a short, and a cancel can only subtract.
    Such an order is cancelled and not replaced — 7.5 governs an exit that is
    protecting a position, and this one is protecting nothing.
7.9 A position this system did not open is not this system's position. Record
    it in the local file as unmanaged, place no exit on it, take no new
    entries while it exists, and name it in every run summary until <OWNER>
    resolves it. This is not a demotion event: the system did not act outside
    the rules. It is also not a position the system may trade.

## 8. Independent reviewer

8.1 The reviewer is a separate session, preferably a different model.
8.2 Its only output is one of BLOCK, CONCERN, PASS, with a rule number or field.
8.3 BLOCK prevents a new entry in that symbol for this session.
8.4 A missing note, PASS, or CONCERN never overrides this file and never
    permits an entry this file does not already permit.
8.5 The reviewer never proposes a candidate, a size, a price or an alternative.
8.6 The reviewer's output may only remove options. No score, rank, sort order,
    threshold, position size, retry, cooldown or eligibility test may read the
    reviewer's verdict, its confidence, its tone or its note. The verdict is
    read in exactly one place and has exactly one effect: a BLOCK removes a
    candidate, after scoring, after ranking, and after the position cap has
    been allocated. A BLOCK never promotes another candidate; the slot it
    empties stays empty for that run. The executor reads only the three-line
    verdict block, from the note file itself, and rejects a card whose copy of
    the verdict disagrees with the file. If deleting today's reviewer notes
    would change anything this system does, other than by causing one fewer
    action, the reviewer is wired wrong and no entries are taken until it is
    fixed.

## 9. Logging and receipts

9.1 Append only to `logs/trade_log.csv`, `logs/skip_log.csv`,
    `logs/run_log.csv`. Never edit a row. Never delete one. Never reorder a
    column. A wrong row stays; append a correcting row after it.
9.2 Frozen schemas:

    trade_log.csv
      timestamp_iso,run_id,symbol,action,qty,limit_price,fill_price,order_id,
      exit_order_id,rule_refs,card_path,reviewer_verdict,notes
    skip_log.csv
      timestamp_iso,run_id,symbol,failed_check,observed,required,data_source,note
    run_log.csv
      run_id,started_iso,ended_iso,gate_result,phase,candidates_seen,entries,
      exits,skips,errors,status

9.3 A number not read from a 0.7 source is never written. Write the empty
    string. Empty means unknown, and unknown is a final answer.
9.4 Invariants, checked at the top of every run from the broker's state:

    I1  every open position has exactly one open sell order
    I2  each sell order's quantity equals its position's quantity
    I3  no open sell order exists without a matching position
    I4  every open position appears in trade_log.csv
    I5  local state.json matches the broker's position list exactly

    Repair one invariant per run, no more. The broker is the truth.
9.5 Never summarise an error. Paste it verbatim, including the ugly parts.
9.6 One run summary per run, written to `runs/` and mailed. Mail it even when
    the run aborted. A summary that does not arrive is itself the alert.

## 10. Scheduling and concurrency

10.1 One scheduled job per run. No looping process.
10.2 `run.sh` takes the lock before any work. The lock is a directory created
     with `mkdir`. It records the wrapper's pid and the pid of the step running
     inside it, and next to each pid the process start time that pid had when
     it was written.
10.3 The lock is live if either recorded pid is live AND its start time still
     matches. A pid whose start time has changed is a different process that
     inherited the number; that lock is dead. Age is not evidence.
10.4 A lock with no pid file two seconds after it was found was left by a run
     that died between creating the lock and writing its pid. Clear it and say
     so. Nothing is running under it.
10.5 A lock whose pid file is not a pid is never cleared automatically. The run
     ends with a non-zero exit so the failure is visible, and a human decides.
10.6 A failure to create the lock is not a held lock. Print the error verbatim
     and end the run with a non-zero exit. Never exit 0 on it.
10.7 `.run.hold` in the repo root stops every run, by hand, with no ambiguity.
     A lock directory is not a pause button.
10.8 Every run is wrapped in a wall-clock bound of `run_limit_seconds`, backed
     by a shell backstop at `run_limit_seconds` + 60 and by `tools/watch.sh`
     at `lock_max_seconds`. A hung run is killed, not waited for.
10.9 Never load, unload or edit a scheduled job during the window in 2.1.

## 11. Failure handling

11.1 Two error classes. Every failure is exactly one of them, and which one
     is decided before anything is retried.
     Platform error — 502, timeout, failed placement, any broker error not
     named in the next line. No new entries for the rest of this run.
     Credential error — 401, or a 403 whose cause is authentication, or
     `desk/tokens.py` reporting expired or unknown. Not a platform error:
     11.2 and 11.3 do not apply to it, and section 13 governs it.
11.2 Retry management work once, on a platform error. Log the error verbatim.
11.3 Two platform errors in one rolling week: drop one phase (12.2). A
     credential error is never one of the two.
11.4 An error class this file does not name: end the run and say so.
11.5 A credential that has expired is not a platform error. It is its own
     class, governed by section 13, and it never counts toward 11.3 or 12.2.
     Nothing in section 11 applies to it. The same holds for a 401 and for a
     403 whose cause is authentication: they are credential errors, they are
     not retried, and the run continues in MANAGE under 13.5 (gate check G5).

## 12. Phase discipline

12.1 The phase is recorded in HEARTBEAT.md. The executor is the only process
     that writes that field, it may only lower it, and only <OWNER> raises it.
12.2 Two platform errors in one rolling week: drop one phase automatically,
     and say so in the run summary.
12.3 Any invariant failure the system did not catch and report itself: drop
     one phase.
12.4 Any action outside this file reaching the broker: drop to phase 0
     immediately and stop. Do not resume until the cause is found and a rule
     is written.
12.5 Raising a phase requires <OWNER> to write it in HEARTBEAT.md and record
     the reason in the change log below, dated.
12.6 Demotion is automatic. Promotion is manual. Never the reverse.

    Phase 0  evaluates, writes cards, validator prints ACCEPT/REJECT, places
             nothing
    Phase 1  presents a card and waits for the literal word APPROVED
    Phase 2  acts without per-action approval, reduced limits, summary read
             the same day
    Phase 3  full limits

## 13. Credentials

13.1 Every credential the system uses is listed in `credentials.json` with an
     expiry. That file holds dates and never a secret.
13.2 An expiry nobody recorded is unknown. Unknown equals no: no new entries
     until it is recorded.
13.3 If any credential has fewer than `token_warn_days` days of life left, the
     CREDS line says so in every run summary until it is renewed, and the
     subject line carries it too.
13.4 An expired credential is not a platform error and never counts toward
     11.3 or 12.2. Nothing broke. A date passed. Demoting the system for the
     passage of time is a bug, not discipline.
13.5 While any credential is expired or unknown, gate check G5 lowers the run
     to MANAGE: open positions are tended, no new entries are taken.
13.6 Only the process that performs the re-auth writes `expires_at`, and it
     writes it in the same sitting as the re-auth. A renewal nobody recorded is
     a renewal that did not happen.
13.7 The mail credential is listed like any other. The channel that carries the
     alarm can expire, and when it does the system looks dead while running
     perfectly.

## Change log

    1.0  <YYYY-MM-DD>  <OWNER>  initial rulebook, fixture only, phase 0.
    1.1  <YYYY-MM-DD>  <OWNER>  credential expiry is its own failure class:
         11.5 rewritten, section 13 added, gate check G5 added. Lock protocol
         10.2-10.7 restated: both pids plus start times, a pid-less lock is a
         death in the mkdir window and is cleared, an uncreatable lock is a
         loud failure, `.run.hold` is the pause. `token_warn_days` 7 -> 3,
         `silence_alarm_hours` replaced by `silence_alert_minutes`,
         `lock_max_seconds` added, `mail_command` deleted because nothing
         read it. 7.7-7.9 added (reconciliation, I5 first, unmanaged
         positions) because `desk/invariants.py` already cited them. 8.6 added
         (the reviewer may only remove options).
    1.2  <YYYY-MM-DD>  <OWNER>  11.1 split into the two error classes it
         always should have been: a platform error is 502, timeout, failed
         placement or an unnamed broker error; a 401 and an authentication
         403 are credential errors and leave section 11 entirely. 1.1 still
         listed 403 as a platform error while 11.5 and 13.4 said the opposite,
         so an expired token both stopped the run and counted toward a
         demotion. 11.2 and 11.3 now say "platform error" where they used to
         say "error", and 11.5 names the two status codes. CLAUDE.md's "When
         something breaks" carries the same two classes.

Version: 1.2