Part of AI_CHEATSHEET.md.
Console output: three detail levels, all same tree format:
- Overview (info, always visible) — major blocks + outcomes, beautified, skimmable, no opt-in needed.
- Reasoning trail (debug, opt-in, written by default) — the why: which branch decision took, candidates considered/rejected, computed threshold/estimate values. Hidden from normal ALL view (
docs/components/console.md'sconsole.debug()), so no spam for non-opted players — reading with debug on should tell whole run story without in-game breakpoint/watch debugger (§8). Every console call costs 0.1 s of simulation time, shown or hidden (docs/BENCHMARK.md), so consecutive debug lines are buffered into one message (see Buffering below). Not for per-item work inside hot loops: that istrace. - Trace (opt-in per module, gated before reaching
console) — truly high-volume noise: method entry/exit, per-item loop detail.TreeConsole.trace()true no-op (noconsolecall, no disk write) unless the module's level is"trace". Hot loops and per-item detail belong here, not indebug(). When fires, still emits at debug level (not custom"trace"badge) —docs/components/console.md'sconsole.print()only treatsinfo/warn/error/debugas filter-feeding; other strings = colored badge in normal ALL view, defeating opt-in gating.
Log levels — console.log_levels archive dict {module_name: level} sets lowest level each TreeConsole(module=...) writes: "trace" < "debug" < "info" < "warn" < "error". Unlisted module takes "*" entry, else "debug" (all but trace). Missing dict seeded {"*": "debug"} by first TreeConsole constructed. Lines below level dropped before console (no 0.1 s cost); block header/END below level dropped too, lines inside keep own level. Custom badge levels count as info. Read once at construction — restart script after editing archive key via Data Archive Notebook, no per-tick re-check. log.verbose true when level is "trace": gate costly trace-only detail on it. log.debugging true when level is "debug" or "trace": gate costly debug-line formatting on it (drone_haul_plan planner lines). Headless simulation sets {"*": "debug"} and makes debug lines free (--log-levels, --paid-debug, docs/cheatsheet/stub_tests.md §10b). module must be passed explicitly (sandbox has no inspect/frame introspection); convention: lib/ filename without extension (e.g. "power", "vehicle_energy").
lib/tree_console.py's TreeConsole wraps get_component("console") with tree-drawn indentation (inspired by inspirations/discord-panels/) so levels read like call stack, not flat scroll:
from tree_console import TreeConsole
# Create once in __init__ (or once before a run_*_loop()'s `while True:`), store as
# self.log — never re-construct per call/per tick, since __init__ reads the
# console.log_levels archive dict. Variable/attribute name is `log`, not `tree`
# (the tree-drawing is just formatting, `log` is what it's used for).
self.log = TreeConsole(module="power") # default_level="info"; grabs get_component("console") itself
self.log.start("Creating tasks") # info: visible overview
for task_type in candidates:
self.log.trace(f"Evaluating candidate {task_type.__name__}") # trace: no-op unless "power" is "trace"
self.log.debug(f"Considering {task_type.__name__}: score={score:.2f}") # debug: reasoning trail
self.log.print(f"Creating task {task_type.__name__}") # info: outcome
self.log.end("Task creation success")
self.log.color("#FF0000").end("Task creation failed") # one-off color override, next line only
self.log.level("warn").print("Battery below safety floor, aborting trip") # one-off level overridestart(msg)/end(msg)open/close block, print┏━/┗━line, indent (┃per level) everything between — default level info.print(msg)logs one line at current indent, atdefault_level(info) unless overridden via.level(...).debug(msg)= shorthand for.level("debug").print(msg)— in-depth opt-in reasoning trail, nested under info-level blocks. Written unless module level above"debug".trace(msg)same shape at debug level (not custom"trace"badge — see above), but short-circuits beforeconsoleunlessmodule=passed toTreeConsole(...)is"trace"inconsole.log_levels(see Log levels). Use for method entry/exit + per-item loop noise wanted during active debugging only.- Convention: one
TreeConsoleper controller instance, in__init__(or once beforerun_*_loop()'swhile True:for bare function, not inside), stored asself.log/log— never re-construct per call/tick, since__init__readsconsole.log_levelsarchive dict. Name itlog(nottree— tree-drawing just formatting,lognames purpose). - Blocks: one
start()/end()pair per coherent unit of work (trip, order/recipe cycle, build/upgrade/commission, sweep, active tick phase); theend()message carries the outcome. Everystart()is closed on every path (earlyreturn, error branch,continue/break), enforced statically bytests/test_log_blocks_balanced.py(per-branch depth must match; a loop body must be net zero). No block on idle ticks; nowith(unsupported in-game) and no reliance onfinally(a stopped script is killed without unwinding). Mixins log throughself._host.log. An exception escaping a block leaves its indent open, so each top-levelrun*loop's first statement isreset_all()(from tree_console import reset_all; drops every instance's open blocks;tests/test_reset_in_run_loops.py). Polling loops nested inside a function must not call it. - Debug blocks:
start(msg, level="debug")…end()wraps a function's decision trail. The header is written only once a line is logged inside (an idle block prints nothing),end()writes┗━ END <name>when the header was shown (nothing otherwise; a message replacesEND <name>), and the outermost debugend()does not flush the buffer (consecutive blocks share oneconsole.print). Lines inside drop their ownfunction_name:/[name]prefix, since the header names it. Convention: any function that can log two or more debug/trace lines in one call opens a debug block as its first statement (after the docstring) and closes it before everyreturn(_ret = expr; log.end(); return _retwhen the expression calls something).step(),run*loops and functions with their own info block are exempt. For a function with several returns, use a wrapped block (next bullet) or a public method that doesstart/_impl()/end. Blocks nest (outer headers are written first, once). - Wrapped blocks:
log.run(label, fn, level="debug")runsfn()insidestart(label, level=level)…end()and returns its result, so the function needs noend()before eachreturn. Decorators:@method_block(name=None, level="debug")(from tree_console import method_block) for methods, readsself.logat call time (mixins included,selfis the host), runs unwrapped without one;@log.block(name=None, level="debug")for module-level functions with a module-levellog.name= header text, or a callable taking the call's arguments (selffirst) for a dynamic header, e.g.@method_block(lambda self, for_stage=False: f"[{self.name}] flush_surplus"); default the function's name. A debug block still collapses and closes withEND <name>; an info block closes withEND <name>, since the wrapper has no outcome text (use manualstart/end(outcome)when the outcome belongs in the END line). An exception escaping the wrapped block writes pending headers and held lines, closes the block and every block left open inside it with┗━ END <name> !! <Type>: <message>, and is raised again.reset_all()stays required in run loops for manual blocks. In use on every method whose debug block had 5+ bareend()exits (fleet commission/upgrade, drone/vehicle navigation, depot, turbine, fabricator, ...);grep -rn method_block scripts/lists them. - Collapsing: a debug block that logs exactly one line is written as
name: message(at that line's level) instead of header + line + END. The line carries the time it was logged, plus(+4m05s)for the game time the block then took (omitted when 0). The first line is held back until a second line, a nested block,end("msg"),flush(), a line from anotherTreeConsoleorreset()shows it must expand.console.now()is a normal cheap call (docs/BENCHMARK.md); onlyprint()/debug()/sleep()cost 0.1 s. - Warn/error lines are not indented (the console's own level badge precedes the message, so an indent would not line up); their block's
┏━/┗━lines still frame them.end()at warn/error keeps its┗━. color(c)/level(lvl)set one-shot override (CSS color /info|warn|error|debug| custom) consumed by nextprint/start/end/debug/tracecall only, then reset to instance default.- Buffering (
tree_console._BUFFER, one buffer for everyTreeConsolein the script):debug/tracelines collect and are written as one multi-lineconsole.print; info,warnanderrorprint immediately after flushing pending debug lines, so order is kept. A run also flushes at a level/channel/color change or a different console object (instances built withoutconsole=share one cachedget_component("console"),_DEFAULT_CONSOLE), when the outermoststart()/end()block closes, at the size cap, and onlog.flush()/tree_console.flush_all().swallowed()flushes before it prints. Cap = half the interpreter string limit (read once from theOverflowErrormessage), at mostMAX_BUFFER_CHARS=20000,FALLBACK_BUFFER_CHARS=4000if unreadable; a longer single line is truncated. A script stopped from the UI is killed without unwinding (finallyblocks do not run), so lines still buffered then are lost: callflush_all()before everysleep()and comms wait (tests/test_flush_before_sleep.pyenforces it for tier 4+).TreeConsole(buffered=False)prints its debug lines immediately. - Info/warn/error lines go through
console.print(..., timestamp=True). Buffered debug/trace lines are stamped byTreeConsoleitself (console.now()when the line is logged,"HH:MM:SS "prefix) and printed withouttimestamp, so every line of a multi-line message has its own time; works with Console channel/level filters. - Inside atomic calls: every console write goes through
atomic.console_print(); inside alib/atomic.pyrunner it is queued and written after the call (dev_workflow.md §1d-1), so pass the controller'slogdown and log as usual. - Reserve plain
warn/errorfor real status changes player should notice without debug output;debug()/trace()purely detail, never attention-needing.
Every broad handler that recovers (returns a default, continues, keeps looping) calls swallowed() as its first line:
from swallow import swallowed
try:
count = port.count()
except Exception as error:
swallowed("storage.crop_automator_forage: port.count", error)
continuewhere="module.Class.function: call". Append#2,#3when one function has several sites calling the same thing. It is the dedupe key, so keep it unique per site.- Every caught error → one debug line. Identical consecutive errors at one site are logged once, so a per-tick handler can't flood the log.
- "Code bug" types (
TypeError,AttributeError,NameError,KeyError,IndexError,ZeroDivisionError) → also one warn per site per script run, visible without debug output on. Exception:AttributeErroronNoneType, which is how a missing component (aNonefromget_component()) usually surfaces. call_or(where, obj, method, default, *args):obj.<method>(*args), elsedefaultwhen the method is missing, raises (swallowed as"<where>: <method>") or returnsNone. Machine controllers wrap it in a one-line_call(method, default, *args)(Fuel Assembler, Feed Maker, Habitat, Refiner).- Why: a broad except can't tell "game said no" from "our code is wrong" (e.g. a
TypeErrorfrom a wrong API signature silently reads as "empty"). - Allowed to stay silent (with a comment saying why):
- inside an
archive.transaction()updater: any log call there rejects the transaction; swallowed()itself;- narrow handlers that fully handle their case, e.g.
except (TypeError, ValueError)around afloat()parse with a fallback, orexcept IndexErroras a loop escape.
- inside an
- Tier
0_cold_boot(nolib/) uses a local_swallowed()stand-in (debug only) defined in the script itself.