Skip to content
Back to skills

Backtest Rescue

ASecurity

Use for strategy repair and unfinished first-cycle validation after failed, timed-out or zero-trade backtests, including a terminal wake or a request to explain what happened. Repair pending-entry state through its full lifecycle, not only initialization. For read-only investigation, engine diagnosis, historical-data coverage, or a request not to edit or rerun, use backtest-analysis instead.

  • 2 stars
  • 0 votes
  • 0 copies
  • 0 views
  • Added December 1, 2026
ai-agentspythongosqlreactnodetestingapifrontendbackendperformance

Works with

  • terminal
  • api
  • mcp

Security analysis

A100/100

Pro scans all 2 files and shows the line behind each finding

Scanned December 1, 2026

npx -y skills add Lumiwealth/lumibot-trading-skills --skill backtest-rescue --agent claude-code

Installs into .claude/skills of the current project.

Are you the author of Backtest Rescue?

Add the live security badge to your README. It updates with every re-scan.

Security grade badge for Backtest Rescue
[![Security: A — Skills Directory](https://www.skillsdirectory.com/api/skills/lumiwealth-backtest-rescue/badge)](https://www.skillsdirectory.com/skills/lumiwealth-backtest-rescue)

More formats (shields.io, HTML) on the badges page. Keep it an A: scan every change in CI with Pro.

Download with Pro
SKILL.md
---
name: backtest-rescue
public-name: lumibot-backtesting
visibility: public
title: "Backtest and debug a LumiBot strategy"
description: "Use for strategy repair and unfinished first-cycle validation after failed, timed-out or zero-trade backtests, including a terminal wake or a request to explain what happened. Repair pending-entry state through its full lifecycle, not only initialization. For read-only investigation, engine diagnosis, historical-data coverage, or a request not to edit or rerun, use backtest-analysis instead."
---
> PUBLIC SKILL: served to anyone through the BotSpot MCP. Never add secrets, customer data or internal details.
--------------------------------------------------------------
BACKTEST RESCUE WORKFLOW
--------------------------------------------------------------

If list_backtests returns no owned runs, do not call get_agent_runtime_diagnostics
with a fabricated or all-zero backtestId. Inspect the saved code and the user's
reported failure; repair a demonstrated code defect without claiming run proof.
Only a returned real backtest identity can support run diagnostics.
## Saved-file evidence

Read a known entrypoint such as `main.py` directly. Before reading optional
Rules or helper files whose presence is unknown, use `list_files` on the exact
revision and read only the returned paths. In particular, `rules.json` is
optional; do not probe for it with `get_file`. If the listing shows no Rules
file, skip Rules review and continue diagnosing the runtime from the available
code and logs. Do not create a file merely to make inspection possible.

## Hook Evidence And Queryability

- Treat every backtest hook identifier as opaque. Do not call UUID-only backtest
  tools with a non-UUID hook identifier. If the terminal hook id is not a UUID,
  use its factual terminal evidence and the attached saved revision. Do not
  probe `get_backtest_logs`, `backtest_status`, or artifact tools with that id.

STOP before any plan or backtest reader and validate the hook identifier. A
non-UUID hook label is never a valid argument to `get_backtest_logs`,
`backtest_status`, `get_agent_runtime_diagnostics`, or an artifact reader. Do not call one of those tools to
discover or confirm the expected validation failure. Plan setup may happen,
but the first domain evidence call for an unqueryable hook must be `get_file`.

## Cost choice before starting an expensive AI backtest

Before `start_backtest`, inspect the saved code's AI model and calling cadence.
For an unconfirmed long run on a saved expensive model, warn about its cost,
present the two choices below, and wait for the user's answer. Do not submit
the backtest first and warn afterwards.

A strategy's managed provider calls consume real BotSpot AI credits. They are
separate from how the current chat or an evaluation actor is funded. Explain
that credit consumption alongside the rough cost estimate, not as merely
model-equivalent usage. Compute any token estimate from explicit assumptions:
`calls * (input_tokens_per_call * input_rate_per_million +
output_tokens_per_call * output_rate_per_million) / 1_000_000`. Calculate each
input/output term before multiplying by the call count; do not mix tokens per
call with tokens for the whole run. Count every configured agent invocation and
state that tool output, reasoning tokens, retries and actual cadence can change
the total. Use the catalog's rates and distinguish provider cost from any
separately documented BotSpot credit conversion.

If the user has not yet chosen the saved expensive model/cost for a long test,
present two complete choices before asking:
- Keep the preferred model for the entire requested window.
- First test the requested longer window on the catalog's cheaper bot model,
  THEN test a shorter window on the original preferred model.
Name both models and both phases in the second choice. Identify each model by its exact returned catalog ID in backticks. If also
using a display name, copy it from that same row; do not expand an ID into
a guessed model name or combine providers, versions or variants.
A binary “preferred or cheap for this test?” loses the second phase. A missing runner or other code
problem does not replace this cost comparison; explain that separately.

A model name in saved code is configuration, not a human cost choice. A generic
"run this strategy for a year" request has not selected that expensive model's
cost. The exception applies when the human explicitly selected that model for
this validation (in the current request or a prior confirmed choice). Then
proceed without asking again or silently switching models. Resolve this before
following the run-only instruction to start before normal prose.

The terminal hook is already evidence. A strategy, AI strategy, revision, or
conversation id from the request context is never a backtest identifier. If its backtest identifier is absent,
non-UUID, or absent from a successful backtest inventory, do not call
`get_backtest_logs`, `backtest_status`, or another ID-based reader with it. Use
the hook's exact terminal error/status plus the attached saved file, then make
the authorized intent-preserving repair. A query failure caused only by an
unaddressable fixture/legacy identifier is preventable and is not required
diagnosis.
A `bt-...` label is not a UUID. If the hook supplies that kind of label and no
successful inventory returned an exact persisted match, go directly from plan
setup to `get_file`; never call an ID-based backtest reader first.

When the terminal hook already contains a concrete runtime error and the saved
strategy is attached, do not call `get_backtest_logs` merely to rediscover that
same error—even if the hook identifier happens to look like a UUID. Set up or
reconcile the visible plan, then read the attached saved file and repair the
specific error from the hook.

For catastrophic negative equity, extreme loss, or position explosion, a
duplicate-entry guard alone is not a complete risk repair. When the saved file
contains explicit sizing and concentration parameters such as
`risk_fraction=1.0` or `max_positions=100`, reduce the explicit sizing and
concentration parameters in the saved revision as well as preventing repeated
entries. Read back those reduced values before starting validation.

For a bounded rescue that changes more than one non-contiguous region of one
saved file, use one complete `replace_file` after the fresh `get_file` read.
Do not construct a multi-operation `patch_file` payload for that rescue. The
complete replacement avoids a partially shaped operation and still creates one
immutable revision that must be read back before validation.

Before every first-cycle `start_backtest`, establish the visible plan first. It
must contain the current action and a future validation row. After the start
returns, use `record_external_wait_in_plan` with the exact returned backtest ID,
revision ID, and `externalWaitId`; never create the plan after the run starts.

CRITICAL ACTION CONTRACT:
- Treat every backtest hook identifier as opaque. Do not call UUID-only backtest
  tools with a non-UUID hook identifier. If the terminal hook id is not a UUID,
  use its factual terminal evidence and the attached saved revision. Do not
  probe `get_backtest_logs`, `backtest_status`, or artifact tools with that id.
- After saving and reading back the implementation, finish implementation before starting its backtest: complete the satisfied earlier plan rows and activate the launch row in one serialized plan update. A successful file save or backtest start does not automatically complete those visible rows.
- Copy the exact latest returned revision ID into any plan linkage and backtest request. Never reconstruct or retype opaque IDs. Optional plan revisionId fields can be omitted when they are unnecessary; an invented or shortened identifier is never a substitute for the actual returned ID.
- A failed original run is terminal even while its retry is queued. Describe each run separately: original failed, retry waiting/running/completed as actually returned. Do not append a generic “first backtest is not finished” statement that contradicts the original terminal result.


When a terminal backtest with active Rules failed, had zero filled trades or
rejected orders, inspect its trades, indicator rows and logs, then call
`commit_backtest_rules_review` for that exact run and revision BEFORE editing
code or starting another backtest. Zero trades or an execution latch does not
waive this review.
The review documents the observed run; it does not change the Rules.
A successful review is immutable for that exact run/revision. Retain its
returned receipt, then proceed to the repair or validation step; do not commit
the same review again with rewritten summaries or additional equivalent evidence.
A new backtest result receives its own review; a revised summary of the old run
is not a new backtest.

Copy a domain tool's returned `externalWaitId` verbatim into the plan tool.
It is an opaque token: never reconstruct, retype from memory, or substitute a
backtest/revision ID. Keep the whole returned token unchanged. A plan-link
copy error does not authorize a duplicate queued backtest; correct the token
from the existing successful start response.

### Complete entry-state repairs

A pending-entry flag represents unresolved owned orders, not whether this strategy
has ever submitted an order. A repair is incomplete if it only changes the initial
flag value, or removes the flag without replacing duplicate-order protection.
For recurring flat-position entries, reconcile current owned active orders before
evaluating the entry, and keep the existing position check. For example:

```python
# At each iteration, before the existing entry checks:
owned_active_entries = [
    order for order in self.get_orders()
    if order.asset.symbol == self.symbol and order.is_active()
]
self.entry_submitted = bool(owned_active_entries)
# Keep the existing signal, position, sizing and submission logic below.
```

A failed state read is unknown, not an empty list. Preserve any explicit one-time
or per-session allowance separately; derive the real session key when needed.
For multi-leg strategies, retain their exact-order ownership and reconciliation.
Before saving, trace both states through the complete edited file: (1) an active
owned order prevents a duplicate; (2) after terminal resolution and when flat,
a later qualifying entry is reachable even if the signal has stayed true.
Initialization-only edits fail the second trace; deleting all pending-order
protection fails the first. Neither is a complete repair.
Before recording a no-trade Rules review, read the actual trades, indicators
and logs for that exact backtest. When metadata lists `indicators.csv` or
`indicators.parquet`, retrieve that artifact and inspect its observations with
`query_csv` (or the matching artifact reader), as well as the trade artifact.
A filename in metadata and an empty trade query do not establish which signals
fired. Complete these reads before `commit_backtest_rules_review`, even when a
stuck execution flag is already visible in the source.

### Continue the active rescue workflow

Before starting validation, finish each earlier implementation/review plan row
whose criteria are satisfied by the saved revision and readback. A later
start-validation row cannot be completed while an earlier implementation row
remains in progress. After start returns, bind the exact external wait to the
current start/validation rows. If a plan mutation is rejected, correct that plan
state using its actual rows before yielding; do not start a duplicate backtest.


- A provider-failed model turn is not a failed backtest. When durable retry context says the prior turn failed at the provider, a runnable strategy revision was already saved, the plan marks workspace/code work complete, and the first smoke has not started, continue from that checkpoint. Preserve the saved revision and resume the next incomplete validation step: start the first backtest over the first-test window on the newest saved revision, then record its returned external wait on the existing plan. Do not call `create_strategy`, `patch_file`, or `replace_file` in this checkpoint-continuation path unless a concrete failed backtest, log, saved-code readback, or tool result proves that a code change is needed. Merely rereading valid saved code or noticing that first-cycle validation is still incomplete is not evidence that the code should be rewritten.
- Before calling `record_external_wait_in_plan`, a visible plan must already exist. If the user asks to start a backtest and keep a plan accurate but no plan exists, call `create_plan` before `start_backtest`, then use the returned external wait to update that plan. Never call `record_external_wait_in_plan` first and create the plan only after the helper rejects the wait.
- When diagnosis reveals a repair before the next pending validation, reuse
  that earliest pending item's id: change its label/criteria to repair and start
  validation, then mark it `in_progress`. Preserve the completed diagnosis and
  its evidence. Add a later pending terminal-result review row before starting
  the backtest. Do not append an `in_progress` repair after an earlier pending
  validation row, or parent it under a completed diagnosis. Reuse the existing
  next step rather than skipping it or adding a duplicate repair subtree.
- Plan mutations are serialized. Call `get_active_plan` when the current plan
  and item ids are not already present in structured context, then make one
  mutation and wait for its result before constructing another. Never send
  `update_plan_item`, `update_plan_items`, `replace_plan_items`, or
  `create_plan` together in one assistant action. After `start_backtest`, use
  `record_external_wait_in_plan` as the single normal mutation; do not try the
  generic plan mutations first.
- Every `create_plan.items[]` object must include a non-empty `label`, a
  non-empty `completionCriteria`, and a valid `status`. Check the complete array
  before the call. Do not use a failed `create_plan` call to discover required
  fields.
- For a short placeholder file or a repair that replaces most of the file,
  call `replace_file` directly with the complete content and latest edit handle.
  Never estimate an `endLine` beyond the exact returned file or use
  `patch_file` as line-count discovery. Reserve `patch_file` for a genuinely
  localized edit whose complete line range is visible in the latest readback.
- If the retry context and plan disagree about whether the revision was saved or validation already started, inspect the current plan/revision/backtest facts and continue from the first factually incomplete step. Never replay completed workspace creation or file edits just because the model request is being retried, and never start a duplicate validation backtest.

Use this skill when a newly created or edited strategy has a failed backtest, a timed-out backtest, or a completed backtest with zero filled trades. The goal is not to explain failure and stop. The goal is to use the backtest evidence, create a normal strategy revision when a fix is justified, and rerun until the user has a working result or you can clearly prove that the request is unsupported or needs one concise clarification.

Completed launch rows record that a run was started; they do not promise that
its later result succeeded. Keep those rows completed. On a failed observation,
resolve the existing result-review row with its actual evidence and outcome,
then add linked repair/revalidation work. Never rename a completed launch into
a diagnosis row or reset it to in_progress. Omitting outcome in a patch retains
the saved outcome; it does not clear it. Ordinary handoffs complete the current
row, wait for the successful result, then start the next existing row.

Core rule: keep the rescue inside the normal conversation. The user should see your tool calls, status updates, diagnosis, revision creation, and reruns as ordinary assistant work. Do not describe this as a hidden job or a separate system.

Read-only boundary: the words "failed", "broken", or "not working" do not by
themselves authorize rescue. If the user asks to investigate or explain an
existing run, diagnose the backtest engine or historical-data path, or says not
to change the strategy or start another backtest, load `backtest-analysis`
instead. Do not load this skill merely because an existing run has incomplete
data or skipped iterations.

A passing narrow Rules review does not override a proven execution defect in
an unfinished authorized build. Inspect the actual account mode and accepted
funding contract: do not treat negative cash caused by execution-price movement
or fees as harmless performance commentary when borrowing was never authorized.
Preserve signals and the requested exposure, fix execution-aware affordability
and outstanding reservations, then verify the newest saved revision. A bounded
limit and cash-aware quantity can enforce an accepted cash ceiling; an earlier
quote alone cannot bound an unrestricted market fill. Preserve explicit market,
margin and fractional-unit policies, explaining a real incompatible requirement
instead of silently changing it.

For staged purchases sharing one accepted funding pool, freeze that pool for
its actual position/decision cycle and account for confirmed spend and pending
reservations. A request for half followed by the other half uses two portions
of the same pool, not half of the already-reduced cash balance. If the customer
explicitly chooses a percentage of then-current cash, retain that distinct
policy. Stage completion follows confirmed executions, including partial and
terminal-without-fill outcomes; submission alone is not completion.

A terminal validation wake inside an authorized creation/edit plan must also
repair a proven requirement violation when the engine completed and trades
filled. The defect need not be catastrophic: unintended borrowing in a cash-only
strategy, missing required protection, or a known unreachable accepted exit is
still a failed implementation. Commit the exact run's Rules review first,
repair the demonstrated causal path without weakening intent, and verify the
new saved revision within the existing attempt allowance. A truthful caveat
alone is not the requested working strategy. A modest negative return alone,
missing evidence alone, or an old unfinished plan row is not such a defect;
preserve analysis-only requests and explicit no-auto/stop boundaries.

Server wake/resume rule: BotSpot Node may wake you after a terminal backtest observation with `externalKind="backtest"`, `externalId=<backtestId>`, revision id, terminal status, trade count, current plan, and wait/run state. That wake is evidence only. Node owns durable waiting/retry state, but only your plan tools mutate the visible plan. React is only a display layer and may be closed or stale. On a wake, inspect the current active plan, avoid duplicate waiting rows for the same external event, and use `update_plan_item`, `update_plan_items`, `add_plan_item`, `replace_plan_items`, or `complete_plan` for every visible plan change. Use `update_plan_item` with a required `target` object and a `patch` object; target by id when available, otherwise use `target: { type: "position", position: N }`. `add_plan_item` takes a nested `item` object. Plan id and plan item id are different: omit top-level `planId` in the current conversation unless the wake or `get_active_plan` gave you the actual plan id, and never pass a plan item id as `planId`. If a plan tool says `Active plan not found`, `Plan item not found`, says the id is a plan item id, says `cannot have outcome.status` while the item is still waiting, or otherwise rejects your id/shape, call `get_active_plan` when needed, retry with the correct current `target`/`patch` or nested `item` shape, and keep working. After `get_active_plan` in that recovery path, target the current waiting/active validation item by the id or position in the snapshot and retry the plan mutation before any diagnostic summary. A failed plan-tool call is correction feedback, not a rescue blocker. A wake for terminal `completed_no_trades` on a first-cycle validation backtest is an action turn, not a report-only turn. `outcome.status="unsuccessful"` is plan-item audit evidence, not the external backtest status and not permission to stop. For a no-trade first-cycle result, complete the terminal validation attempt with `outcome.status="unsuccessful"` and source backtest evidence using `update_plan_item`, then before any final assistant answer add or continue explicit rescue items after it with `add_plan_item`, setting `parentItemId` to the unsuccessful validation item id when available, or use `replace_plan_items` to reconcile the whole visible list once. If `add_plan_item` rejects the rescue item because it lacks `parentItemId` or `dependsOnItemIds`, retry the same plan mutation with that explicit reference and then execute the rescue item; do not summarize the rejection as a blocker. If `update_plan_item` returns a warning that the plan has an unsuccessful item with no explicit follow-up, your next model action must be `add_plan_item`, `replace_plan_items`, or a blocker/cancel plan tool, not assistant prose. If a plan tool result says a rescue item is now `in_progress`, your next assistant event must be a tool call for that item, such as `get_code`, `get_file`, a file-edit tool, a docs/artifact tool needed for the edit, or a plan tool marking a real blocker; do not emit status prose first. A successful `add_plan_item` that creates an `in_progress` rescue row is the start of execution, not an allowed stopping point. Set the current rescue item `in_progress`, inspect the saved code and available backtest evidence, create a normal corrected revision when the cause is fixable, call `start_backtest` over the same first-test window (or the correct longer window when the earlier run was too short), and mark that new validation item `waiting_for_external_event`. If a terminal wake says `backtestStatus`/`status` is `completed` and `tradeCountStatus="counted"` with `tradeCount` greater than zero, that satisfies first-cycle filled-trade validation ONLY when the fills also match the user's stated trading intent and are not catastrophic. Treat absurd frequency versus stated daily/position intent, destroyed equity / extreme return collapse, or an `outcomeQuality` failure marker as failed outcome quality: continue repair and start a verification backtest instead of declaring victory. A merely modest negative return does not by itself invalidate an otherwise intent-matching first-cycle smoke. Explicit user performance thresholds such as CAGR, total return, Sharpe, or max drawdown still force continued metric-target repair. Filled trades are necessary, not sufficient. If the current plan still shows a stale `in_progress` rescue/edit item, reconcile it with the delivered successful backtest evidence: mark the relevant rescue/validation item completed with `outcome.status="satisfied"`, then call `complete_plan` before assistant prose. Do not edit files or start another backtest after a completed filled-trade wake solely because the old current plan item is still in progress. Do not use `update_plan_items` to update the same plan item twice in one call. Do not call `complete_plan` while the latest validation attempt has `outcome.status="unsuccessful"` or `outcome.status="partial"` and no later completed follow-up item references it. Never treat `outcome.status="unsuccessful"` as the final rescue state for fixable first-cycle work; it is audit evidence for one failed attempt, and the next action is rescue work unless a real blocker, user stop, or attempt budget applies. A final assistant answer after only reporting the no-trade metrics, after only marking `outcome.status="unsuccessful"`, or after only creating an `in_progress` rescue item is forbidden for active first-cycle rescue.

Avoid preventable discovery failures on terminal wakes. `list_backtests` has no
single-backtest `id` argument: call it with the strategy id and match the exact
returned backtest id, or use `backtest_status` for an exact id. Treat
hook identifiers as opaque. Do not call UUID-only backtest tools with a non-UUID hook identifier. If a hook uses a synthetic or legacy non-UUID identifier and `list_backtests` returns no exact persisted row, use the factual terminal hook evidence and the saved revision instead of probing `get_backtest_logs`, `backtest_status`, or artifact tools with an incompatible id. Treat
optional files according to the saved-file evidence workflow above. When the active
plan snapshot already contains one or more completed unsuccessful or partial
attempts plus later unresolved rows, prefer one `replace_plan_items` call that
preserves existing ids, resolves the current row, and adds the fully linked
follow-up. Do not probe `add_plan_item` with one parent id at a time when the
snapshot already shows the complete dependency set and progression order.
Never set the current item to waiting and then append another waiting item.
When a new user decision becomes necessary, resolve the current item as partial
and append the linked waiting follow-up in one `replace_plan_items` call.
After `get_active_plan` returns the authoritative snapshot. Do not manually copy
a plan item id into `update_plan_item` or `update_plan_items` for a multi-row
transition. Use one `replace_plan_items` call with the exact ids from that
snapshot, preserving every visible row and changing only the intended states.
Do not call `add_plan_item`, `update_plan_item`, or `update_plan_items` first in
this user-decision transition. Once inspection establishes that approval is
required, the first plan mutation after that inspection must be exactly one
`replace_plan_items` call. Do not call `add_plan_item` at all for that
transition, including as a probe with one unresolved parent and then another.
The replacement must preserve every visible item id, resolve the current item
as partial, and add one waiting follow-up whose `dependsOnItemIds` contains
every unsuccessful or partial attempt id already shown by the active-plan
snapshot.
If the snapshot already has a later unresolved item, do not append a new item
behind it. Instead, reuse the earliest existing unresolved item as the waiting
approval item, preserve its id, update its label and completion criteria to the
exact user decision, and leave any later items pending. Never place a waiting
approval row after an earlier pending validation row.


## Provider and data-source prerequisite failures

For a provider/gateway error or a `data_source_required` start result, load
`references/provider-and-prerequisite-evidence.md` before deciding the cause
or next action. Preserve the causal evidence, selected model/settings and
returned setup alternatives; a blocked prerequisite is not a completed run.

Duplicate-delivery override: a notice that the same terminal hook or external
event was already delivered and must not be duplicated is not a new rescue
authorization or a new terminal outcome. Treat an explicit "duplicate",
"already delivered", "do not rerun", or "do not duplicate the rescue" message
as a user stop for replaying that event. Do not inspect code, edit files, create
a replacement rescue plan, or call `start_backtest` from that duplicate notice.
You may read the current plan or exact backtest list only when needed to confirm
that no new run was created, then answer briefly that no duplicate action was
taken. This duplicate-delivery override takes precedence over the mandatory
repair-mode rules below.

Rules review rule: a terminal wake carries factual backtest state and a `Result check for this wake` line. A clean run (completed with filled trades, no error and no rejected orders) follows that line: no Rules review. The full review runs when the run failed, had zero filled trades or rejected orders, or the customer asks whether it follows the rules: with active `rules.json` Rules, load `strategy-rules`, inspect the exact revision and per-Rule evidence, and commit it with `commit_backtest_rules_review` (the tool only stores your conclusion). If the review fails, repair Python without weakening the Rule and call `start_backtest` again inside the same five-attempt budget. If it passes, do not make cosmetic repair rewrites. No active Rules means no review.

Raw completed rule: do not treat the raw manager word `completed` as first-cycle success by itself. Success requires terminal completion plus at least one real filled trade, or a stricter user-specified performance target if one exists. Raw `completed` with `tradeCount=0`, `resultClassification="no_trades"`, `firstCycleOutcome="no_trades"`, or UI/API status `completed_no_trades` is first-cycle repair mode until a filled-trade success, real blocker, user stop, or attempt budget applies.

Timeout override: a `terminated_timeout`, `timed_out` / timed-out run, `failureCategory=timeout`, or `tradeCountStatus=not_applicable_timeout` is NEVER "completed with no trades", even if the wake includes `tradeCount=0` or a no-trade classification. Narrate a timeout / platform-infrastructure failure. Prefer the run logs first, subject to the hook queryability rules above. Do not enter the no-trade rule-loosening or zero-trade rescue sequence unless the run truly completed: `completed_no_trades`, or raw `completed` with `tradeCountStatus="counted"` and `tradeCount=0`, with no timeout evidence. Timeout evidence takes precedence over zero counts and no-trade labels. Preserve strategy rules and code unless logs establish a concrete, intent-preserving technical repair; a timeout alone does not justify a strategy edit. This override takes precedence over the rescue edit/rerun sequence below.

## Data and platform failures during unfinished validation

A supported strategy's failed first validation remains active work when the
failure is in a provider or platform dependency. Inspect the concrete terminal
error and saved revision. Missing auxiliary metadata, including corporate-action
coverage, does not prove missing credentials, an unsupported instrument, or an
unavailable primary price series. Generic fallback labels such as
`failureOwner="strategy"`, `failureCategory="strategy_or_runtime"`, or an
unexplained `retryable=false` do not override concrete runtime evidence.

When the supported path has no proven credential, entitlement, required-data
integrity or compatibility blocker, no validation is already running, and the
attempt budget remains, perform one bounded availability retry on the unchanged
saved revision. A data retry requires no code edit or new revision; this
exception overrides the edit-then-retest sequences below. Preserve the selected
instrument, provider, strategy rules, sizing and execution behavior. Do not ask
the user to select another provider or approve that routine retry.

Copy the failed run's exact start and end dates into the retry. Do not apply the
initial first-test window chooser again, convert a calendar window to a shorter
Monday-through-Friday interval, or substitute another recent week. Only concrete
window-availability evidence or the user's changed mandate can justify different
bounds; a metadata failure supplies neither.

Record the returned external wait on the visible plan. The first build is still
unfinished until terminal validation succeeds. If the same platform prerequisite
persists after the bounded retry and no concrete recovery is available, record
that persistent blocker with the executed retry evidence. Genuine missing
credentials, entitlements, unsupported inputs, explicit user stops, exhausted
attempt budgets and duplicate active runs retain their existing stop boundaries.

Decision-time wake checklist:
- If the wake says `completed_no_trades`, raw `completed` with `tradeCount=0`, `resultClassification="no_trades"`, `firstCycleOutcome="no_trades"`, `failed`, `terminated_timeout`, `timed_out`, or another terminal non-success, this turn is a rescue execution turn. It is not a final report turn. Apply the timeout override first; timeout rescue starts with runtime diagnosis, not no-trade rule changes.
- If there is no active plan item, create or repair visible plan state, then continue rescue. The hook evidence is not dependent on having a perfect plan already.
- If a plan tool fails, read the exact error text. When it returns unresolved unsuccessful/partial attempt ids, retry with `item.dependsOnItemIds` containing every listed id, or call `replace_plan_items` once to reconcile the full visible plan. Do not keep alternating one id at a time.
- After the plan has an `in_progress` rescue item, the next step is `get_file` or another visible evidence/edit tool, then a file edit that returns a new revision, then `start_backtest`. Final prose is invalid before that sequence unless you recorded a real blocker, user stop, or attempt budget exhaustion with plan tools.
- A failed `query_csv`, missing artifact, stale edit handle, or failed plan mutation is normal recovery feedback. Correct the shape/handle or use the available terminal hook evidence and keep moving.

Mandatory action rule:
- In repair mode, diagnosis-only is not a completed rescue when you can name a concrete fix. If logs/artifacts/code show a fixable cause, create a normal corrected revision with file tools in the same rescue turn, then call `start_backtest` on the new revision over the first-test window (see First test window below).
- For a localized runtime error such as one bad attribute or helper call, prefer `patch_file` against the `get_file` edit handle. Preserve the rest of the runnable file, especially its `if __name__ == "__main__"` backtest/live runner. Do not replace the whole file with only the strategy class. If an edit result reports blocked execution readiness or `MISSING_RUNNER`, repair that readiness issue and read back the next revision before calling `start_backtest`.
- For `ModuleNotFoundError` or another missing-package import failure, read both the saved `main.py` and `requirements.txt` before editing. If the imported third-party package is absent, add it with an exact public PyPI `==` pin, read `requirements.txt` back, and start the next smoke on the returned revision. Preserve the failed run's date bounds when available; otherwise choose the first-test window below. Repairing an import or plotting dependency does not justify expanding that window. Use `replace_file` when `requirements.txt` is empty; use a bounded `patch_file` or complete replacement when it is populated. Preserve every required strategy capability and make the smoke exercise the import path. Do not wrap the import in a fallback, make it optional, or delete the dependent feature just to make startup pass.
- If the exact dependency is already present in the saved `requirements.txt` and the run still reports that it cannot be imported, classify that as a platform installation or interpreter defect rather than generated strategy logic. Preserve the files, inspect the runtime logs and package-install evidence, and report the product defect. Do not keep rewriting valid dependency declarations or the user's strategy to hide the platform failure.
- Zero-trade cause order (apply before any edit, rule proposal, or approval request): (1) window too short, (2) code bug, (3) data missing, (4) rules never fire or conflict. Check (1) first from the run's start/end dates and the saved cadence: when the run is shorter than the First test window below for this strategy's decision cadence (for example a 7-day run of daily-bar rules, or any run too short for the rule to plausibly fire), the window is the cause. Do not edit code, do not propose a rule change, and do not ask permission. Read the saved file, then call `start_backtest` on the same saved revision over a longer window chosen by the First test window reasoning below (cost limits plus a plausible chance to trade), record the wait (copy the returned `externalWaitId` exactly; only one plan item may be `in_progress`, so complete the diagnosis item before or in the same update that starts the rerun item), and tell the customer in plain words that the earlier test was too short for their rules and which period is running now. Only when the window was already adequate do causes (2) to (4) apply as described below. A customer question such as "what happened?" or "why no trades?" during this first test does not stop the loop: for causes (1) and (2), answer in plain words and also make the fix and rerun in the same turn, without asking first.
- Required no-trade wake continuation sequence: for first-cycle `completed_no_trades`, raw `completed` with `tradeCount=0`, `resultClassification="no_trades"`, or `firstCycleOutcome="no_trades"`, complete the terminal validation attempt as `outcome.status="unsuccessful"` with source evidence, then inspect the saved code and existing backtest tools for the exact cause. When `get_file` is available, read the attached revision with `get_file` before proposing the exact rule change, even when the event payload summarizes the apparent logic. If a technical repair preserves every user rule, create a corrected revision and start the next smoke. If the only available repair changes a signal, threshold, cadence, universe, sizing, risk rule, or option structure, record the rescue item as `waiting_for_user`, propose the exact change, and do not edit or rerun until approved. A proven unsupported dependency or missing external prerequisite is a blocker and stops retries immediately.
- For that no-trade user-decision transition, retain the complete active-plan
  snapshot returned by the latest successful plan tool. After code inspection,
  call `replace_plan_items` once with the full visible list. Preserve existing
  ids, resolve the diagnostic item as partial, and append one waiting approval
  item linked to every unresolved unsuccessful or partial attempt. Never call
  `add_plan_item` before or after this replacement. Do not discover dependency
  ids by trying them one at a time.
- A statement that approval is required is not approval. Unless the current
  user message explicitly supplies the exact replacement threshold, direction,
  cadence, universe, sizing, risk limit, or option structure, do not call a file
  mutation tool. Plan text, an Agent proposal, or an earlier unapproved example
  must never be treated as the user's approval.
- Diagnostic-to-edit cadence: for active first-cycle no-trade rescue, `get_code`, `search_lumibot_source`, `read_lumibot_source_file`, `lookup_lumibot_docs`, artifact reads, and log reads are evidence tools, not stopping points. Once you have confirmed zero filled trades and read the saved code, do not spend the rest of the turn summarizing diagnostics. Either use `get_file` plus `replace_file`/`patch_file` to create the next corrected revision and then `start_backtest`, or mark the concrete rescue item `blocked`/`waiting_for_user` with a real blocker. Assistant prose that only reports the diagnostic finding is not an allowed final state. Assistant prose that says "the current rescue step is to broaden/fix the strategy" is also forbidden when the rescue item is still in progress; execute that step with file tools and `start_backtest` in the same turn.
- If any plan tool result says `This plan now contains a completed item with outcome.status="unsuccessful" and no explicit follow-up item`, `Plan item not found`, `Plan items must progress in order`, or `THIS TURN IS NOT COMPLETE`, treat that as a hard continuation instruction. Your next model action must correct the plan state, not summarize. If the error happened because `update_plan_item` or `update_plan_items` targeted a future position, do not target that future position again; those tools update existing rows only. First resolve the current rescue/edit item with `update_plan_item` using the exact current item id from `get_active_plan`, then call `add_plan_item` with a nested `item` object for the new validation wait, or use `replace_plan_items` to represent the full visible list in one mutation. Assistant prose, metric summaries, and final answers are invalid until the follow-up exists and is executed or a real blocker is recorded.
- If the active rescue item is already `in_progress`, that item includes the concrete code edit plus the next `start_backtest` call. Do not mark it completed from diagnosis alone. Do not create or target a future `Start rescue smoke backtest` or `Validate rescue smoke result` row before a file edit succeeds and `start_backtest` returns the new backtest id. If a plan tool says a future position does not exist or plan items must progress in order, treat that as retry feedback: execute the active rescue item with visible file/backtest tools or retry the corrected plan mutation, not assistant prose.
- A file-edit tool only succeeds when its result returns a new revision id/version. If `replace_file` or `patch_file` reports a stale edit handle, EDIT FAILED, or any file-tool error, no new revision exists; treat the tool error as correction feedback, refresh the file/edit handle with `get_file` or `list_files`, retry the edit with the latest returned `editHandle`, and do not call `start_backtest` until a real edit has returned a new revision id.
- After a file edit succeeds, the next validation tool must be `start_backtest` using the returned revision id. Do not call `backtest_status`, `list_backtests`, or any polling/status tool for the new attempt until `start_backtest` has actually returned a new backtest id.
- Only skip file-edit repair plus `start_backtest` when the request is unsupported, a required credential/data entitlement is missing, the user stopped you, the five-backtest-attempt budget is reached, or one concise clarification is truly required before changing intent.
- If a strategy is already attached and the user asks to rescue or finish its build, use the attached strategy without requiring a special "refine it" phrase. Inspect the current revision and evidence, make an authorized intent-preserving repair when needed, and verify it. A request to run or test an existing strategy authorizes the requested execution; it does not by itself authorize edits. An explicit unchanged/as-saved request preserves every file through the terminal follow-up, even when the analysis discovers a defect. Report that defect and a proposed repair without saving it or purchasing another run. A server wake and an existing plan do not expand the originating customer's permission. Preserve autonomous repair inside an unfinished creation/repair mandate when no such boundary was imposed.
- If a no-trade first-cycle run is blocked by a code-level date gate, contest window check, warmup early-return, or market-session assumption that stops the real strategy logic from ever running, that gate is a code bug: fix the gate so the real rules are evaluated, preserving the user's intended live/contest behavior, and rerun the same window. If the window itself is too short for the rules, extend the window instead of editing code.
- If logs show messages like "outside competition window", "outside contest window", or "staying flat" and the first-cycle smoke has no completed filled-trade result, fix the date gate before rerunning. Preserve the live contest dates, use pre-contest smoke bars for warmup/inspection only, and make sure the actual contest-window iterations can reach the strategy's normal entry logic.
- If a first-cycle smoke fails with `TypeError: 'Bars' object is not iterable`, that is a fixable generated-code/LumiBot API shape error, not a blocker. Do not stop just because `logs.csv` or `errors.csv` artifacts are unavailable; the hook error string is enough evidence. Inspect the saved code, replace direct iteration such as `for bar in bars` or `[bar.close for bar in bars]` with `bars.df` / dataframe column access, create a normal corrected revision, and immediately call `start_backtest` over the same first-test window.
- Do not rescue by adding an unrelated backtest-only validation order, dummy trade, separate backtest-only entry branch, or unapproved simplified or broadened entry path. Do not add branches such as `if IS_BACKTESTING and not traded: buy SPY`.
- Do not use `from __future__ import annotations` or other future imports in rescue-generated strategy files. If a startup failure says a future import is not at the beginning of the file, remove the future import entirely instead of moving it around.
- Do not confuse BotSpot schedule metadata with LumiBot market names. `marketSession: "regular"` and schedule `regular` describe product scheduling only; they are not valid `self.set_market(...)` values. For ordinary US stocks/ETFs, omit `set_market` unless needed, or use a documented LumiBot value such as `"NYSE"`, `"NASDAQ"`, or `"stock"`. Never use `self.set_market("regular")`.
- If docs lookup is unavailable or blocked, continue from the focused skills, artifacts, logs, and code evidence. Do not stop only because a docs lookup failed.

First-cycle smoke rule:
First test window (used whenever the customer did not name a backtest length; a customer-named length always wins):
- Keep first tests short and fast. Unless the user or a known failed run supplies dates, the default startDate is endDate minus 7 calendar days, with endDate at the latest completed trading day. Use a different length only for the cost or entry-frequency reasons below. An unchanged strategy that can enter during an ordinary week gets this seven-day default after a startup repair too. Warmup history always comes from before the window; never shorten the window, lookbacks, or rules for warmup. A lookback alone is not a reason to add sessions to the validation period: fetch that earlier history before the window, and choose the run length from the entry frequency.
- Adjust the length for what makes a backtest slow or expensive: number of symbols (one symbol is cheap; dozens or 100+ symbols stay at about a week or less), asset type (options are much slower than stocks and ETFs; crypto trades 24/7 so each day holds more data), timeframe (minute and hour bars can be orders of magnitude slower than daily bars, especially on uncached Interactive Brokers data), and, for AI-owned decisions, the model cost per decision (a default model with daily decisions about a week; for an expensive model, explain the cost and use about 1 to 2 days; an explicit choice of that model plus a request to start validation already authorizes that short test, so do not ask for the same choice again).
- A cheap strategy (one or a few stocks or ETFs, daily bars, plain Python) may use about 1 to 3 months when that is what its rules need.
- Before calling `start_backtest`, reason about the rules: will they plausibly trade at least once in this window? Count the bars the window gives at the strategy's cadence and compare with how often the entry can fire (a daily 20/50-day crossover happens only every month or few; a daily RSI dip below 30 a few times a quarter; a 50/200-day cross about once a year). If a trade is unlikely, pick a longer window within the cost limits above. If even that is unlikely, run the affordable window and say plainly, before results arrive, that it may show no trades and why, and offer a longer test.
- The final answer names the window, explains the reason and explicitly states that the user can request a different period, even if an earlier status message already said this. For a longer window chosen because entries are rare, name the actual entry condition and cadence, explain why a week offers too few opportunities, and connect that to the longer period. A plain explanation structure is: "[Named entry condition] is checked [cadence] and may not trigger during a single week; [chosen period] gives it more opportunities. You can request a different period." This required date-control information belongs in the explanation of the chosen run. Do not call it a smoke test.
- Every rerun in the rescue loop uses the same window unless the cause was a too-short window, in which case the rerun uses a longer window chosen by the same cost and plausibility reasoning.
- When you create the first revision for a new strategy, run its first backtest over the first-test window.
- A first-cycle smoke is not successful unless it completes and has at least one filled trade.
- For chartable strategies, a polished first-cycle smoke also needs visible indicator/marker evidence. If a completed filled-trade smoke has no indicator rows or the BotSpot indicators chart is empty, do not assume the product is fine. Load `lumibot-indicators-and-charting` and, when needed, `backtest-indicator-chart-diagnostics`; read the saved code and inspect `indicators.parquet` / `indicators.csv`. If the saved code computes or trades from chartable prices, entries, exits, stops, thresholds, or indicators but does not call `add_line` and `add_marker`, create a normal new revision that adds those calls and rerun the same first-test window. If the saved code already emits chart data but artifacts/UI are missing it, diagnose the backend/frontend artifact path instead of changing strategy logic.
- Treat failed, timed out, force-stopped, completed_with_errors, completed_no_trades, and raw completed with `tradeCount=0` or `resultClassification="no_trades"` as not done.
- Simple build or edit result check: one `backtest_status` read (or the wake) gives status, errorSummary, tradeCount and rejectedOrderCount; null means unknown, not zero. An error or rejected orders: fix and rerun once. Zero trades where the rules should trade: find out why. Otherwise reply with the result and one line restating the rules (entry, exit or stop, size); a negative return is context, not a failure. Artifact queries, log reads, data-evidence review and the Rules review run only when the customer asks to analyze the results or the run looks wrong.

- If a strategy has never had a completed filled-trade backtest, failed, timed out, force-stopped, completed_with_errors, and completed_no_trades outcomes are still repair mode even if the current revision number is higher than 1.
- A failing Rules review and zero filled trades are different failures that can both require repair. Keep their evidence and plan outcomes separate. First-build success is a run completed with filled trades, no error and no rejected orders.
- Never change the customer's rules to make a test trade: no shorter lookbacks, no swapping a crossover for "already above" trend state, no buy-now or first-evaluation activation paths, no wider thresholds, no smaller universe, no dropped confirmations, unless the customer says yes to that exact change. A too-short window is fixed by testing a longer window, never by changing rules.
- Never loosen a user constraint to obtain smoke fills without explicit approval. Name one change with its new value and reason (never ask which to change), mark the rescue waiting; save after a yes.
- A generated threshold, liquidity filter, spread cap, safety gate, or other
  Agent-invented constraint that is absent from rules.json is not a user Rule.
  If it blocks a required first-build action, treat it as generated-code logic
  to repair, not as a user constraint that requires permission to change. Keep
  genuine execution safety and broker validity checks, but remove or correct an
  invented blocker when the available market data supports the user-requested
  package. Never silently add the invented blocker to Rules after the failure.
- If the user explicitly asks to verify a known defect fix after a prior filled-trade success, help verify with `start_backtest`. Do not shrug with post-success no-auto-rescue policy when the current turn is an explicit verification request for a known bad prior fill.
- Historical filled trades are evidence for their exact revision and window. They do not validate a later saved repair or finish an active authorized build/validation mandate. For that unfinished work, inspect the newest revision and terminal evidence and continue a proven intent-preserving technical repair/retest within the remaining attempt budget, even if `firstCycle=false`. A later completed_no_trades notification after the requested work is complete may be intentional: explain the result without automatically editing or rerunning. Never loosen Rules merely to force a trade.
- If a repair-mode smoke fails or has zero filled trades, diagnose it and continue only while a technical repair preserves user intent. Stop immediately for unsupported input, a required credential or data entitlement, or a user decision on a proposed rule change. The five-attempt budget is a ceiling, not a quota.
- Do not mark the original first-smoke validation item blocked merely because the entry rule never fired. Complete the attempt as `outcome.status="unsuccessful"` and inspect the cause. Continue with an in-progress repair only for an intent-preserving technical fix. Use `waiting_for_user` when a rule change needs approval, and use blocked only for a proven external prerequisite or essential incompatibility.
- If the visible plan already has completed rescue diagnosis/edit/start/validation items and the newest rescue validation also ended `completed_no_trades`, do not consume another attempt automatically. Reuse the existing diagnosis. Apply and validate an intent-preserving technical repair, or record the exact prerequisite, incompatibility, or user approval needed.
- If a terminal no-trade validation item is still waiting, update that same item to `completed` with `outcome.status="unsuccessful"` and source evidence before moving on. Then add a concrete rescue edit/start/validation item or replace the visible list once; do not batch-update that same validation item twice. Do not compensate by adding duplicate diagnosis items. Continue the rescue sequence and move to the next edit/rerun action.
- If a wake says terminal `completed_no_trades`, `get_active_plan` shows a waiting validation item, and `list_backtests`, `query_csv`, or artifacts confirm zero filled trades, that is not a reportable waiting state. Complete that waiting validation item with `outcome.status="unsuccessful"` and source evidence, then add or mark the next concrete rescue edit/start item `in_progress`. Do not create an inspect-only rescue item that can be completed by reading code; the rescue item should require a saved file edit, a new revision id, and a new `start_backtest` call unless a real blocker is proven. Assistant prose that only reports the latest zero-trade metrics is forbidden.
- If a wake says terminal `completed`, `tradeCountStatus="counted"`, and `tradeCount > 0`, while `get_active_plan` still shows a rescue edit item as `in_progress`, the backtest evidence wins over the stale item. Mark the active rescue/validation item completed with `outcome.status="satisfied"` and evidence for the completed filled-trade backtest, then call `complete_plan`. Do not call `get_file`, edit code, or `start_backtest` again just because that stale rescue item was still current.
- In first-cycle repair mode, after `list_backtests` or `backtest_status` confirms terminal no-trade evidence and `get_code` succeeds, inspect logs, trades, statistics, artifacts, provider errors, symbol coverage, and revision linkage as applicable. Then either apply an intent-preserving technical repair and start a new validation, or mark the concrete rescue item `blocked` or `waiting_for_user` for a proven prerequisite, incompatibility, or rule-change decision. Missing one optional artifact is not itself a blocker when other evidence identifies a technical repair.
- If you already marked a rescue item `in_progress` and then called `get_code`, do not end with a vague status report. Continue through an intent-preserving file repair and `start_backtest`, or update the item to `waiting_for_user` or blocked with the exact prerequisite or decision.
- If you have already called `get_code` after a no-trade wake, do not end with a summary headed like "Smoke result", "Evidence", "What happened", or "What I found" unless it follows a successful new `start_backtest` or a recorded blocker. In a fixable no-trade case, that summary is premature; continue with `get_file`, edit the saved file, start the rescue smoke, and then record the waiting validation.
- After rescue `start_backtest` returns a new validation `backtestId`, the rescue turn is still incomplete until you update or add the visible `Validate rescue smoke result` item as `waiting` with `waitReason=waiting_for_external_event`, linked through generic evidence containing `externalKind="backtest"`, `externalId=<backtestId>`, and `revisionId`. Prefer `replace_plan_items` for this exact post-start transition: include the full visible list, keep existing item ids, mark the current rescue item `completed`, and append the new waiting validation item in one visible mutation. If you do not use `replace_plan_items`, first resolve the current rescue item with `update_plan_item`, then call `add_plan_item` with a nested `item` object. Do not target a future position with `update_plan_item` or `update_plan_items`; those tools only update existing items. If you accidentally used `update_plan_items` to both complete the rescue item and target a non-existent future validation row, assume that mutation did not create or complete anything; use `replace_plan_items`, or resolve the rescue item first and then append the validation row. Do this before any final assistant answer or active-validation handoff.
- Starting a rescue smoke is progress, not success. Do not call `complete_plan`, report "done", or imply the strategy has passed first-cycle validation merely because a broader rescue revision/backtest was launched. The plan can only complete after a terminal rescue result proves at least one real filled trade, after the user stops the work, after a real blocker is recorded, or after the five-attempt budget is exhausted.
- Before rescue `start_backtest` returns a new validation `backtestId`, there is no concrete external wait to record. Do not add a waiting validation row early and do not target a missing future position. Use the active rescue item to perform the code edit and `start_backtest`; then record the returned backtest id on the validation row.
- Do not end a repair-mode turn by asking permission with wording like "If you want, I can keep rescuing..." when the plan already contains failed/no-trade validation evidence. Continuing the repair loop is the work.
- Use the attempt budget from the wake context (`maxAttempts`, normally four: the first test plus three automatic repairs) for first-cycle repair loops. Each attempt must be a normal visible revision/backtest cycle, not a hidden code patch. The budget counts every real rescue `start_backtest`, whatever its outcome; edits do not reset it. It limits only runs you start on your own: when the customer asks you to run it again, start one run. Before calling `start_backtest` in rescue mode, count the attempts already visible in `list_backtests`, `backtest_status`, wake messages, or plan evidence for this conversation/strategy. If the budget's attempts have already been started and none completed with at least one filled trade, do not call `start_backtest` again; explain in plain words why there were no trades, what you would change, and ask at most two short questions. Mark the concrete rescue/validation item `blocked` with `blockedReason="workflow_budget_exhausted"`, include the backtest ids/statuses as evidence, and explain the blocker.

Stock/ETF indicator no-trade pattern:
- Apply this pattern only after the window check: the run must already cover the first-test window for the strategy's cadence. A rare gate on a 7-day run of daily rules is a too-short window, not over-filtering.
- When the rules themselves never fire in an adequate window or conflict (for example RSI above 90 while price is below its 200-day average almost never happens together), explain why in plain words and offer two or three specific choices, such as testing a longer period, one exact threshold change, or dropping one named condition. Wait for the customer's pick before editing or rerunning.
- If a supported stock/ETF first-cycle smoke confirms `completed_no_trades` and the saved code uses rare indicator gates such as RSI above 80/90, RSI below 20/10, a long moving-average filter such as a 100/200-day SMA, or multiple stacked confirmations, treat that as a proven first-cycle over-filtering cause after code inspection. Do not keep looking up framework docs unless an actual API error is present.
- A minimal implementation is not itself evidence of a technical defect. If the backtest completed normally, the saved code evaluates the user's exact restrictive signal, and no log, provider error, tool result, or artifact proves an execution defect, do not rewrite it to add a runner, charting, logging, indicator helpers, or bar filtering. Those improvements cannot rescue an intentionally rare signal. Record the exact user approval needed and wait without calling file-edit or backtest tools.
- A terminal `completed_no_trades` without an error proves the saved revision executed. Alternative API styles found in reference documentation are not defect evidence. Do not load API-reference guidance solely to restyle an executable no-trade revision, and do not call file-edit tools merely because a different Asset constructor, order-side constant, runner block, indicator helper, or state pattern is preferred.
- When saved rules are the demonstrated cause, the required active follow-up is a plan item waiting for user approval of one exact rule change. That is not permission to add chart instrumentation, replace an executable file, or try a preferred API style while waiting. The instruction to continue from diagnostics into an edit applies only to a causal non-rule defect proven by an error, log, artifact, or tool result.
- A permanently latched execution flag is a causal defect, not a preferred API
  style. Repair its complete pending-order lifecycle as above. Read back both
  the later-entry and duplicate-prevention paths; fixing only initialization
  does not finish the demonstrated repair.
- State the causal counterfactual before any no-trade code edit: identify which non-rule branch prevented an otherwise qualifying entry, cite the saved-code plus runtime/log/artifact evidence, and explain why the proposed edit changes that branch without changing user intent. If the proposed edit cannot change whether a trade qualifies, it is cosmetic and forbidden in rescue. If no observed non-rule blocker exists, wait for the user's rule decision without editing.
- Preserve the user's exact signal, threshold, cadence, universe, sizing, risk, and option-structure rules. Repair warmup and technical execution without changing them. If a rule itself prevents trades, propose one exact adjustment and wait for approval before saving it.
- If warmup or another technical repair preserves the stated RSI/SMA rule, validate that repaired revision. If the threshold or lookback itself must change, propose the exact change and wait for approval.

Smoke stuck or dev-data pattern:
- If a first-cycle smoke starts and logs at least one real filled trade but then hangs, times out, or crawls because the strategy scans a broad stock universe with repeated messages like "asset does not exist or does not have data", treat that as a repairable smoke failure.
- Do not accept a confirmed early fill as success until the backtest reaches a terminal completed status. A working first-cycle result requires both a terminal completed run and at least one filled trade.
- Optimize batching, caching, and data access while preserving the requested universe. Reducing or replacing a user-specified universe requires approval. If the universe was an Agent-selected default rather than a user rule, it may be narrowed to one to three supported liquid symbols and disclosed.

Diagnosis order:
1. Use `list_backtests` to pick the exact run and confirm revision, status, date range, and available artifacts.
2. For crashes or timeouts, inspect the run logs first with
   `get_backtest_logs`, using `diagnosticPreset="runtime_failure"`,
   `contextLines=5`, `limit=1000`, and a batched `queries` array covering
   `Traceback|Exception|ERROR|WARNING|NoSuchKey|timeout|terminated`,
   `order|trade|fill|position`, and
   `strategy|runtime|main\\.py|on_trading_iteration`. Runtime logs are not
   artifacts; never request `logs.csv` or `errors.csv` through
   `get_backtest_artifact` or `query_csv`.
3. For completed runs, inspect `trades.csv` or `trades.parquet` and use `query_csv` for exact counts. Do not infer zero trades from zero return metrics.
4. For no-trade runs, inspect `indicators.parquet` or `indicators.csv` and decision logs to find which entry conditions never triggered or whether orders were rejected/unfillable.
5. Use `get_code` before deciding what to edit. Map the evidence to the actual code path.
6. Load focused skills and docs before changing code: options issues need `lumibot-options-helper`, indicator/chart issues need `lumibot-indicators-and-charting`, and AI-agent strategy issues need `lumibot-ai-agents`. For lifecycle/order/API facts use `lumibot-api-reference`. For an execution-state repair, even a small constant edit, load `strategy-building-core` and its one applicable complete pattern: `references/entry-fill-allowance.py` for filled-entry limits, `references/protective-position-example.py` for protection/retained exits, or `references/rebalance-example.py` for accepted allocations. Wire the needed pattern or preserve an equivalent working owner before saving; a known state defect is not fixed by disclosing it. Broad corrections also need `strategy-building-core`.
7. Use `lookup_lumibot_docs` when an error mentions a LumiBot method, helper, entity, lifecycle hook, or data/backtesting API.

Agent-detail artifact inspection:
- `agent_detail.parquet` can contain very long prompt, context, memory, event-payload, summary, and final-text fields. Do not raw-select full text columns such as `effective_system_prompt`, `base_system_prompt`, `runtime_context_text`, `context_text`, `memory_state_text`, `event_payload_json`, `event_text`, `summary`, or `final_text`.
- First use aggregate queries plus at least one ordered, limited timeline/excerpt query with bounded text. Aggregate counts alone are not enough to answer what the agent was doing. Good starting queries:
  - `SELECT event_kind, tool_name, COUNT(*) AS events FROM data GROUP BY event_kind, tool_name ORDER BY events DESC`
  - `SELECT call_index, event_index, event_kind, tool_name, LEFT(event_text, 500) AS event_text, call_input_tokens, call_output_tokens, call_cached_input_tokens, call_thinking_tokens, call_latency_ms FROM data ORDER BY call_index, event_index LIMIT 50`
  - `SELECT call_index, MIN(timestamp) AS first_ts, MAX(timestamp) AS last_ts, MAX(agent_name) AS agent_name, LEFT(MAX(summary), 500) AS summary_excerpt, LEFT(MAX(final_text), 500) AS final_text_excerpt, MAX(call_input_tokens) AS input_tokens, MAX(call_output_tokens) AS output_tokens, MAX(call_latency_ms) AS latency_ms FROM data GROUP BY call_index ORDER BY call_index LIMIT 50`
  - `SELECT COUNT(DISTINCT call_index) AS calls, MAX(call_input_tokens) AS max_input_tokens, MAX(call_output_tokens) AS max_output_tokens, MAX(call_latency_ms) AS max_latency_ms FROM data`
- Aggregating a long text column does not make it safe. Do not use `MAX(summary)`, `MAX(final_text)`, `ANY_VALUE(summary)`, or `ANY_VALUE(final_text)` unless the aggregate is wrapped in `LEFT(...)`, for example `LEFT(MAX(summary), 500) AS summary_excerpt`. Omit those columns when the query is only for counts or token totals.
- If `query_csv` returns `payloadTruncated`, `cellTruncated`, or `truncationHint`, rerun a narrower SQL query with fewer columns, `WHERE`, lower `LIMIT`, or `LEFT(long_text_column, N)`. Treat bounded results as a prompt to query more precisely, not as a failure.

Futures no-trade pattern:
- If a futures or continuous-futures backtest has OHLC/indicator artifacts but the logs repeatedly say the futures price is unavailable, inspect whether the code gates entries on `get_last_price(asset)` returning non-`None`.
- For `Asset.AssetType.FUTURE` and `Asset.AssetType.CONT_FUTURE`, fix that gate by using the latest completed historical bar close as a fallback reference price when `get_last_price(...)` returns `None`.
- Do not solve this by adding more filters. The correct rescue is to preserve the user's futures signal and make the price/sizing path use available bars so the smoke can place at least one small trade.

LumiBot API collision pattern:
- If a failed backtest logs `TypeError: 'Bars' object is not iterable`, inspect every historical price helper. LumiBot historical price calls return a Bars object whose dataframe is available as `bars.df`; the Bars object itself is not a Python list of bar rows. Fix the code to use `df = bars.df`, then read `df["close"]`, `df["open"]`, `df["high"]`, `df["low"]`, or iterate `df.iterrows()` only if row iteration is truly needed. This is a normal rescue edit and must be followed by a fresh seven-day smoke backtest.
- If a failed backtest logs `TypeError: 'float' object is not callable`, `TypeError: 'dict' object is not callable`, or a similar callable/non-callable mismatch around a helper call, inspect the strategy code for helper names that collide with LumiBot runtime attributes or broker/account state.
- Do not rerun the same revision or make superficial threshold changes for this error. Rename private-looking helpers such as `_gross_exposure`, `_portfolio`, `_portfolio_value`, `_cash`, `_cash_value`, `_account_value`, `_positions`, `_orders`, `_broker`, `_strategy`, or `_last_price` to explicit strategy-local names such as `_botspot_gross_exposure_ratio(...)` or `calculate_portfolio_value(...)`, and replace undocumented calls such as `self.get_portfolio()` with documented public APIs such as `self.get_portfolio_value()` or `self.get_cash()`.
- If the code contains `def _portfolio_value(self):` or a call like `self._portfolio_value()`, treat it as the concrete private-name collision until proven otherwise. Rename the helper, update every call site, then rerun the smoke.
- After the rename/API fix, create a normal new revision and immediately start a fresh backtest for that revision over the same first-test window.

Crypto no-trade pattern:
- If a BTC/USD, ETH/USD, BTC/EUR, ETH/EUR, or stablecoin-quoted spot crypto backtest logs missing data for a symbol like `BTC-USD/USD`, inspect whether the code used a pair string as the crypto base asset.
- Spot crypto `Asset` symbols are base coins only: use `Asset("BTC", asset_type=Asset.AssetType.CRYPTO)` with a separate quote asset. Do not use `BTC-USD`, `BTC/USD`, `BTCUSD`, `BTC/EUR`, or `BTCEUR` as the `Asset.AssetType.CRYPTO` symbol.
- Do not silently convert pairs such as BTC/EUR into BTC/USD. Preserve the requested quote asset when the runner/data path supports it; if a fresh capability check proves a specific pair is unavailable, explain that precise limitation and offer a supported pair.

Options and complex order no-trade pattern:
- If an options backtest has chains and option prices but still completes with zero trades, inspect whether the code only tries a complex order and returns when any leg has missing quotes, unusable bid/ask, a wide spread, missing Greeks/delta, missing expiration, or too-strict liquidity.
- Complex options includes covered calls, cash-secured puts, vertical spreads, calendar spreads, diagonal spreads, butterflies, iron condors, straddles, strangles, ratio spreads, and any multi-leg order that requires every leg to pass quote/liquidity checks before placing an order. Do not make rescue guidance wheel-specific.
- Load `lumibot-options-helper` before editing options code. Use `OptionsHelper` for chain, expiration, strike, quote, and multi-leg helper operations; do not manually select contracts from raw chains when the helper has the needed operation.
- For options strategies, technical quote, chain, expiration, and order-construction repairs may proceed when they preserve the requested structure. Changing a multi-leg spread into a single leg, widening an expiration window, changing delta or strike targets, or loosening a spread limit changes user intent and requires approval before saving.
- Do not solve this by tightening option filters. A first-cycle options smoke that finds chains and buy prices but logs only "one or more option legs had unusable prices or spreads" is invalid because complex-order validation blocked the activation smoke.
- Do not add dummy fills, fake option legs, hardcoded proof-only orders, or `if backtesting` branches. The rescue revision must be understandable as a normal strategy that can trade because the entry/order path was made practical.

When to edit:
- If a structured `STRATEGY_EXECUTION_NOT_READY` or other readiness failure
  contains `issues[].filePaths`, legacy `issues[].files`, or `referencedFiles`
  naming more than one file, treat that file list as
  machine evidence. Call `list_files`, then inspect every relevant named file
  before editing. Repair the actual multi-file execution structure and preserve
  the trading idea; do not guess from `main.py` alone or merely explain the
  readiness error.
- If the readiness issue is `missing_executable_runner`, put the executable
  runner in the file that defines the strategy class, normally `main.py`, so
  the saved project has one importable and directly executable entrypoint.
  Editing only a sidecar such as `runner_settings.py` does not repair this
  readiness issue.
- Edit when the failure is caused by generated code, wrong API shape, wrong asset/data handling, or order plumbing that can be repaired without changing user rules.
- Make the smallest useful revision that addresses the proven cause.
- For first-cycle no-trade failures, do not loosen thresholds, broaden the universe, add fallback entry behavior, or change order structure without user approval. Propose the smallest exact change and wait when a rule change is required.
- Save rescue fixes as normal strategy revisions. Do not silently mutate an existing revision in place.
- After a successful rescue file edit, immediately run `start_backtest` on the returned revision over the same first-test window. Do not end the turn after the edit unless `start_backtest` itself fails or a blocker above applies.
- Never invent or reuse a backtest id to validate a rescue revision. A rescue validation id must come from the `start_backtest` result for the just-created revision.

When not to edit:
- Do not edit just to hide missing provider credentials, invalid API keys, expired data access, billing/quota blocks, or broker authorization problems. Explain the required setup.
- Do not keep retrying unsupported or unreliable first-cycle asset paths. BotSpot does not currently support forex trading as a first-class path, spot gold/silver as forex-style markets, or Indian index options such as Nifty, Bank Nifty, Sensex, NSE options, or BSE options as a first-class build/backtest path. For unsupported or mixed market requests, explain the limitation and suggest supported alternatives such as supported crypto pairs, GLD/SLV, gold or silver futures, US-listed stocks/ETFs, US options, or supported futures.
- Do not run a filled-trade smoke backtest for an alerts-only strategy unless you first convert it into a tradeable strategy with the user's consent. Alerts-only strategies do not place filled trades, so they cannot satisfy the first-backtest success metric as written.
- Do not rewrite a strategy into a different idea without telling the user. If the needed change materially changes the user's intent, ask one concise clarification.

Long-running backtests:
- `start_backtest` is asynchronous. During first-cycle smoke/rescue, it is acceptable to monitor progress because validation is part of the task.
- For first-cycle smoke/rescue, after `start_backtest` returns a backtest id with `agentRunStatus="waiting_on_external"`, record the wait in the plan and end the turn; do not poll `backtest_status` for that new run. BotSpot wakes this conversation with the terminal result. Poll only when the newest user message explicitly asks you to keep checking until it finishes.
- For first-cycle smoke/rescue, do not end with optional check-later wording while a new validation run is still active. If the runtime must yield before terminal completion, update or add the validation/rescue plan item to `waiting` with `waitReason=waiting_for_external_event` and generic evidence containing `externalKind="backtest"`, `externalId=<backtestId>`, and `revisionId`, say that the validation run is still active, and say the server-side rescue flow will continue automatically when it reaches a terminal result.
- Backtest ETA is noisy. The first simulated day can be much slower than later days because the runner starts infrastructure, imports LumiBot, and loads data. Say that plainly when reporting ETA.

Success response:
- Keep the architecture rationale from `strategy-building-core` in the final
  handoff, including when validation is queued: fixed fast rules run in Python
  because calling an AI model in the trading loop adds variable latency and
  model-credit cost. Separately disclose feed, broker and order-fill limits;
  those execution limits do not replace the model-latency/cost explanation.
- Report the final revision id/version, test date range, data provider, filled
  trade count, recorded cash/holdings and applied fee/slippage basis, following
  `backtest-analysis`'s "Reconcile the final handoff against the exact run".
  Include the actual configured nonzero costs even when the user did not choose
  them. "Fees may differ" is not a disclosure of the nonzero costs this run used.
  Reuse the exact saved settings/code and artifacts; do not invent a rate or
  assume zero. Keep this factual cost statement compact, and explain the main
  change that made the strategy work.
- If the user approved looser filters or changed order behavior, say exactly what changed and preserve that approval in the visible plan evidence.
- If no working revision is possible, state the exact blocker and the best supported alternative.

Files in this skill

  • SKILL.md76.8 KB
  • references/provider-and-prerequisite-evidence.md2.5 KB

Attribution

Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.

View all in ai-agents →

Comments

Loading comments…

Newsletter

Get the weekly list of safe new skills, and the ones we pulled.