bot

package
v1.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 33 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package bot — boot_report.go

BootReport is the structured, persisted, Wails-emitted record of one boot attempt. It is built incrementally by the BootOrchestrator and surfaces three places: the in-memory status (returned to the React side via the bot_init_report Wails event), the JSON file under paths.ResolveConfig("logs/"), and the bundled boot profile (p95 / recommended timeout — see bootprofile.go).

The intent is "never again should the user see a bare 'failed to initialize bot' line and have to grep app.log to find out why." Every step records its name, duration, result, and a short human detail. The SuggestedAction field is what the orchestrator believes the user should try next ("wait longer", "check adb", etc.) — the React panel surfaces this as a one-liner with optional buttons.

The BootReport type holds a sync.Mutex so the orchestrator can append steps and recovery names from multiple goroutines safely. BootReport is therefore NOT safe to copy by value — copying a sync.Mutex is undefined behavior. The companion BootReportView type below is the value-copyable, JSON-marshalable, Wails-emittable projection: Snapshot() and SaveJSON() produce a BootReportView, and all read paths operate on it. This split keeps the mutex where it belongs (on the writer) and prevents the "go vet warning: return copies lock value" footgun.

Package bot — bootorchestrator.go

BootOrchestrator is the single entry point that brings the bot from "user clicked Start" to "ready to capture frames". It replaces the inline boot sequence that used to live in NewBot() in bot.go, and turns the multi-step hand-rolled procedure into a state machine with named steps, layered recovery, structured reporting, and learned timing.

The orchestrator does NOT own the capture loop, the classifier, the attack executor, or any of the runtime subsystems. It only owns the BOOT phase. NewBot() now reads:

bctx, err := NewBootOrchestrator(cfg, client).Boot(ctx)
if err != nil { ... }
// bctx.ScreenW/H, bctx.Client, bctx.BlueStacksRestarted are ready

BootConfig carries the tunables. The defaults are production-safe; in dev mode NewBot shrinks them via WithDevFastFail so a failed boot surfaces in 25s instead of 180s+.

Threading: the orchestrator is single-use. Construct one per NewBot call, call Boot() once, and discard. The Client it receives is mutated (its transport is connected, the pipe is not enabled) — that's the intended hand-off.

Package bot — bootprofile.go

BootProfile is the persistent, learned-timing store for boot durations. Each successful boot appends a sample; on timeout the recommended timeout is bumped (p95 * 1.5 capped at MaxRecommended). The orchestrator reads the recommended timeout before starting, so after one or two runs on a slow MacBook the bot stops timing out on a value that was hand-picked for fast hardware.

The file lives at paths.ResolveConfig("boot_profile.json") and is written atomically (tmp + rename) so a crash mid-write doesn't corrupt the existing profile.

Package bot — builderbase.go

The Builder Base battle: boat, Attack, match, one troop, surrender, home. It is a second, much simpler battle loop than the home-village attack sequence, and it exists for the reason every competitor's builder-base mode exists: Builder Base loot is paid by destruction on a base nobody is defending, so a single troop and a surrender is the cheapest income the account has.

The reason this file is mostly preconditions is that none of it is visible from the code: the versus screen, the troop bar and the result panel are references that have to be proven on a live frame. Every step therefore proves its screen before the next tap and names the step that failed, so a run logs "the versus screen's Battle button was not located" instead of "builder base failed".

Package bot — humanize.go

Helpers that turn fixed wall-clock intervals into varied ones.

A bot's loudest behavioural signature is not where it taps but WHEN: the same 30 s gap between raids, the same 18 s between camera pans, the same session and break length every single day. Server-side play-pattern checks see those, and a human never produces them. Every interval in this file is a distribution, not a constant; none of them changes what the bot decides, only how long it waits before doing it.

Package bot — idle.go

Everything the bot does between battles, in one place.

It used to live at the bottom of processFrame, *after* the "attack button detected" branch — which returns. So every frame where the Attack button was on screen (i.e. every frame in the village) skipped the maintenance work entirely: the storage gate refused the attack, the branch returned, and the upgrade/collect/wander blocks below it were unreachable. A full village with maxed walls therefore produced no input at all, forever.

The maintenance pass now runs before the attack decision, owns the storage verdict the attack path reads, and is the only place that decides "this village is fine, we are just not attacking right now".

Package bot — notify.go

Nothing about a 24/7 farm is visible from the machine it runs on, so the events worth a human's attention leave through internal/notify: attack results, village halts, and scheduler pauses. The wiring lives here so bot.go stays about the capture loop.

The notifier is nil whenever notifications are off, which is every install that never configured them, so each call site is a nil check and nothing more.

Package bot — personal_break.go

Supercell puts a player on a "Personal Break" after a long uninterrupted session. The dialog blocks the whole village, the classifier has no rule for it, and before this file the flow was: Unknown -> self-heal taps -> 35 s watchdog -> game restart -> the dialog is still there -> repeat. That burned the account's session, looked nothing like a player, and broke farming until a human closed the game.

The dialog is text, so it is read as text: one OCR pass on an unclassified frame (never on a classified one) at most every personalBreakOCRInterval, matching phrases that only that dialog carries. Detection triggers the scheduler's break, which already knows how to pause input, stop the game, and resume afterwards.

Package bot — recovery.go

RecoveryPolicy is the layered escalation engine that decides what to try when a boot step fails. The whole point of replacing the hard-coded "kill BlueStacks" with named strategies is that the bot tries the cheapest fixes first and only escalates to destructive actions as a last resort.

Strategy ladder (cheapest to most-destructive):

  1. RetryTransport — close + reopen the ADB transport socket. Fast (~50ms). Handles the common case of a stale connection from BlueStacks restart.

  2. SoftReset — `adb shell stop && adb shell start`. Restarts the Android runtime without killing BlueStacks. ~5-10s. Handles the "boot_completed never appeared" case where Android is up but wedged.

  3. RelaunchGame — force-stop + restart CoC via monkey. Doesn't touch BlueStacks or the Android runtime. ~3-5s. Handles the "PackageManager up but CoC crashed" case.

  4. RestartBlueStacks — osascript quit + open -a BlueStacks. ~10-15s for the launch. The last reasonable option before…

  5. NuclearOption — kill -9 BlueStacks + rewrite config from scratch. ~20s. Only used when EnsureBlueStacksMac itself failed (config write rejected, etc).

Each strategy has metadata: the action function, a "what went wrong" predicate that decides when to try it, and a budget. The orchestrator walks the ladder, applying backoff between attempts, and surfaces a "SuggestedAction" string for the UI.

Package bot — runtime_state.go

The bot has three reasons to be deliberately idle: the scheduler does not authorize an attack right now, the storages are full, or the army is empty. Before this file they were three unrelated booleans living in three different call sites, and none of them was visible to the UI — a halted bot looked exactly like a working one, and the stuck-watchdog treated a deliberate halt as a hang and force-restarted the game every 35 s.

This file owns the single verdict the rest of the bot reads:

gate.allowed / gate.reason

plus the small amount of state that must survive a process restart (the scheduler's hourly and daily attack counters, which used to be in-memory only — so every crash or keepalive respawn reset the daily cap that exists to keep the account inside a human-looking attack budget).

Package bot — training.go

The bot could not retrain: when the camps were spent the Start Attack panel said "Train an army before attacking!", the capture loop latched that and idled 60 s at a time, forever. A 24/7 farm therefore stopped farming after the first battle. See the comment this file replaces in clickSequence.

The queue is driven entirely through controls the bot already proves on the live frame: the Attack button it taps every cycle, the empty-army panel's own EDIT ARMY button (located, never predicted), the saved-recipe card, and the army sheet's action button. Every step fails closed and logs why, so a UI change leaves the account idle instead of tapping coordinates blind.

Package bot — village.go

The bot can size its search floors from the account's own Town Hall instead of a static pair of numbers, using the export the player copies out of the game (internal/village). Nothing here touches the device: an account with no export imported simply keeps its configured floors.

Index

Constants

View Source
const DefaultRecommendedTimeoutMs = 90_000

DefaultRecommendedTimeoutMs is the initial recommended boot timeout when no profile exists yet. 90s matches the prior hard-coded value in bot.go so behavior is unchanged on first launch.

View Source
const DefaultStopWait = 5 * time.Second

DefaultStopWait bounds Close: a stop must never hang the app on a disk that stopped answering. Anything still queued at the deadline is reported.

View Source
const MaxBootProfileSamples = 30

MaxBootProfileSamples is the rolling window of recent boots the profile keeps. 30 is enough to absorb a few bad days without forgetting that "this user usually boots in 12s."

View Source
const MaxRecommendedTimeoutMs = 300_000

MaxRecommendedTimeoutMs is the upper cap on the recommended timeout. Even on a very slow machine, 5 minutes is enough — past that, something is actually wrong and the user should investigate rather than have the bot silently retry for 10 minutes.

View Source
const MinRecommendedTimeoutMs = 30_000

MinRecommendedTimeoutMs is the lower bound. 30s is a reasonable floor: any device that boots faster than 30s on a clean run is already happy at the floor, and bumping below 30s just causes spurious timeouts on noisy hardware.

Variables

View Source
var (
	// ErrWriterStopping means the request arrived while the writer was
	// draining; the write was not queued.
	ErrWriterStopping = errors.New("async writer stopping")
	// ErrWriteQueueFull means the backlog is full; the write was not queued.
	ErrWriteQueueFull = errors.New("async write queue full")
	// ErrFlushTimeout means WriteSync gave up waiting for the async backlog
	// (a stalled disk); it did not write, so it cannot interleave with it.
	ErrFlushTimeout = errors.New("timed out waiting for queued writes")
)

Functions

func AsyncWriteFile

func AsyncWriteFile(path string, data []byte, perms os.FileMode) error

AsyncWriteFile queues a state write. It returns once the request is queued, not once it is on disk.

func CPUTime

func CPUTime() time.Duration

CPUTime returns the total CPU time consumed by this process since it started, as an absolute duration. It is the sum of user + system time reported by the kernel (getrusage RUSAGE_SELF).

Unlike a percentage, this number is device-independent: it means the same thing on an M1, an M3 Max, or any other machine. A busy-loop burning one core for 10 seconds reports ~10s here regardless of how many cores the host has. To compare efficiency across devices, measure CPUTime() delta over a fixed wall-clock window (see CPUUsage).

func RunWallUpgradeLoop

func RunWallUpgradeLoop(h *WallUpgradeHooks)

RunWallUpgradeLoop drives the wall-upgrade sequence with explicit deps (parametrised by h). Production wires a Bot-built hooks struct; the cmd/test_wall_upgrade diagnostic tool wires its own hooks struct against a live adb.Client without instantiating a full *Bot.

Flow selection (in priority order):

  1. ASSET-DRIVEN (BLIND-TAP) — when wall_upgrade_buttons.json + wall_upgrade_confirm.json + wall_upgrade_x_roi.json ALL load cleanly: a0. Capture ONE pre-tap baseline frame and gate on it: locateWallTray must find a painted chip inside both mapped gold/elixir rects (a builder-menu row drawn at those coordinates has white text on a dark panel, zero saturated pixels, and fails the gate), otherwise the iteration ends with `wall_tray_absent` and fires NO input. The same frame records each X rect's red-pixel level, so every later popup check asks for GROWTH over it as well as the absolute floor (xPopupPresent) rather than brightness alone. a. Tap the LOCATED gold chip Center (mapped rect when the frame had nothing better to offer). b. Capture the confirm page and require the CONFIRM control to be DRAWN inside the mapped confirm rect (a green face with a white caption, confirmButtonDrawn). If it is not there the tap is skipped — no input — and the next button is tried. c. Tap the confirm rect Center, wait + capture. Then check BOTH xPopupPresent(x_popup_roi) AND xPopupPresent(x_popup_roi_alt) (alt only if configured). The alt tap that follows is evidence-gated on its own fresh capture, so a clean primary popup no longer drags a blind tap onto whatever the alt rect happens to cover. Chained-popup support per the user's spec: dismissing the gem-buy modal can reveal a SECOND popup whose X lives at x_popup_roi_alt; both must be down before declaring success. d. If ANY popup is still up, single-tap each X in sequence: primary center, then alt center (if configured). ONE tap per X, no retry, no offsets. Per the user's "click X, then click X again in the confirm menu" spec. e. Verify both rects dismissed after the sequence. If either is still up → fall through to the NEXT button on this same wall (gold → elixir per spec "if gold was unsuccessful, click elixir"), emitting primary_still_up / alt_still_up diagnostics so the user knows which rect mis-picked. If the dismissal SUCCEEDED the button is unaffordable too — a popup that had to be closed is the "this would cost gems" signal, not an upgrade — so that also falls through to the next button, logged as `asset_driven_unaffordable_dismissed`. Once both buttons are unaffordable the post-button-loop check surfaces the `all_unaffordable` exit and the sequence ends. Wall-level aborts only fire on defensive capture failures (modalErr / verErr — transport sick), not on rect mis-picks. f. No popup at all → silent spawn = success. Move to next wall.

  2. PROBE-AND-DISCARD — when only wall_upgrade_buttons.json loads (legacy mode from the original pre-rect refactor): - Tap gold → if btn_confirm_upgrade template matches ∧ checkConfirmRed says white → tap template-derived confirm. - Tap gold → confirm missing → silent spawn = success. - Tap gold → confirm shown + checkConfirmRed says red → tap X. - Then loop to elixir with the same logic.

  3. LEGACY TEMPLATE — when no rect assets load: - For each btn_upgrade_wall candidate (multi-scale match): pre-tap cost-color check via costROI, then probe-and-discard with btn_confirm_upgrade template match.

Each phase boundary emits an OnStep event so the diagnostic tool can capture + annotate a screenshot at every decision point. Payloads follow the Mat-ownership contract documented on WallUpgradeHooks.step.

func SuggestedAction

func SuggestedAction(lastStep, lastStrategy, lastErr string) string

SuggestedAction is the human-readable "what to try next" string surfaced in the BootReport and the React UI. It takes the most recent failed step + the last strategy attempted and produces a one-liner. Kept short (1 sentence) so it fits a UI card.

func WriteFileSync added in v1.1.0

func WriteFileSync(path string, data []byte, perms os.FileMode) error

WriteFileSync writes a state file on the caller's goroutine. Explicit on-disk path for callers that must not proceed before the bytes land.

Types

type AsyncWriter

type AsyncWriter struct {
	// contains filtered or unexported fields
}

AsyncWriter serialises best-effort state writes on one background goroutine.

Write      queues and returns; it never waits for the disk.
WriteSync  is the explicit on-disk variant for callers that must block.
Close      drains, then joins the worker (bounded), and is re-armable.

Ordering: requests are written in the order they were queued. Data is not copied, so a caller must not mutate the slice after Write returns.

func NewAsyncWriter

func NewAsyncWriter() *AsyncWriter

NewAsyncWriter builds an idle writer. The worker starts on the first Write or Start, so a process that never saves state never carries the goroutine.

func (*AsyncWriter) Close

func (aw *AsyncWriter) Close()

Close stops accepting writes, drains what is already queued, and waits for the worker to exit. The wait is bounded: if the disk stops answering it logs how many writes were abandoned and returns instead of hanging shutdown. A later Write (or Start) re-arms a fresh worker.

Idempotent: a second Close while the first is draining joins the same bounded wait instead of closing the queue again; Start during that window is a no-op, so nothing reopens or writes through the closed queue.

After a bounded abandon the worker may still be alive. Until it exits, Start is a no-op and Write is rejected, so a second worker cannot drain the same queue and a late abandoned write cannot land after a newer one.

func (*AsyncWriter) Start added in v1.1.0

func (aw *AsyncWriter) Start()

Start arms the worker if it is not running. Safe to call repeatedly.

func (*AsyncWriter) Write

func (aw *AsyncWriter) Write(path string, data []byte, perms os.FileMode) error

Write queues a write and returns once it is queued. The error is about queueing only (writer stopping, or backlog full); a disk failure is logged by the worker because the caller has already moved on. Writers are re-armed on demand, so a write after Close starts a fresh session instead of silently degrading to a direct synchronous write.

Race with Close: the mutex makes the outcome one of two, never a send on a closed queue. A Write that reaches the lock before Close is queued and Close drains it; a Write that arrives while Close is draining is rejected with ErrWriterStopping (logged with its path) and never touches the disk.

func (*AsyncWriter) WriteSync added in v1.1.0

func (aw *AsyncWriter) WriteSync(path string, data []byte, perms os.FileMode) error

WriteSync writes through the same atomic primitive on the caller's goroutine. Use it when the bytes must be on disk before the next step; Write is the normal, non-blocking path. Any writes already queued are drained first, so a snapshot flushed at shutdown cannot be overwritten by an older queued one.

The wait is bounded like Close. If it times out the write is NOT performed: a queued request may still be in flight, and writing now would let that older payload land after this newer one. The caller gets ErrFlushTimeout and can decide; ordering is never inverted.

type AttackReport

type AttackReport struct {
	Timestamp        string `json:"timestamp"`
	Strategy         string `json:"strategy"`
	TargetEdge       string `json:"target_edge"`
	DeploySuccess    bool   `json:"deploy_success"`
	UndeployedSlots  int    `json:"undeployed_slots"`
	DeployError      string `json:"deploy_error,omitempty"`
	ParsedResults    bool   `json:"parsed_results"`
	Stars            int    `json:"stars"`
	GoldStolen       int    `json:"gold_stolen"`
	ElixirStolen     int    `json:"elixir_stolen"`
	DarkElixirStolen int    `json:"dark_elixir_stolen"`
	BonusGold        int    `json:"bonus_gold"`
	BonusElixir      int    `json:"bonus_elixir"`
	BonusDE          int    `json:"bonus_de"`
	TotalAttacks     int32  `json:"total_attacks_session"`
	EndReason        string `json:"end_reason,omitempty"`
}

type BootConfig

type BootConfig struct {
	// ADB timeouts.
	AdbConnectTimeout time.Duration // overall budget for the transport connect loop
	AdbConnectPoll    time.Duration // gap between connect attempts
	AdbPerCallTimeout time.Duration // passed to transport.Exec (one Shell call)

	// Boot-probe timeouts (multi-signal).
	BootProbeTimeout    time.Duration // overall budget for the probe loop
	BootProbePoll       time.Duration // gap between probe passes
	BootProbeMinSignals int           // required # of ready signals (2 = 2-of-4)
	BootProbePerSignal  time.Duration // per-signal timeout inside one probe pass

	// Recovery knobs.
	MaxRecoveryAttempts    int
	AllowNuclear           bool
	InitialRecoveryBackoff time.Duration
	MaxRecoveryBackoff     time.Duration

	// Misc.
	WaitForGameSettle time.Duration // post-StartApp sleep
	PackageName       string
	DeviceID          string
	ExpectedWidth     int
	ExpectedHeight    int
	ExpectedDPI       int

	// DevFastFail is true when wails dev is running. Shrinks all
	// the timeouts above; the orchestrator does NOT touch this
	// field directly (NewBootConfigFromBotConfig reads the env).
	DevFastFail bool
}

BootConfig is the per-call configuration for a single boot attempt. Constructed by NewBootConfigFromBotConfig; tune via the WithDevFastFail and WithAllowNuclear helpers.

func DefaultBootConfig

func DefaultBootConfig() BootConfig

DefaultBootConfig returns the production defaults. 90s on the boot probe, 90s on the ADB connect loop, 2-of-4 signals, 5 recovery attempts with a 0.5s..4s exponential backoff.

func NewBootConfigFromBotConfig

func NewBootConfigFromBotConfig(cfg *config.BotConfig) BootConfig

NewBootConfigFromBotConfig merges the BotConfig defaults with the orchestrator's own defaults. The DeviceID, PackageName, and resolution come from cfg.Device. The recovery policy reads cfg flags for future tunability (currently none — the orchestrator has its own opinion).

func (BootConfig) WithDevFastFail

func (c BootConfig) WithDevFastFail() BootConfig

WithDevFastFail returns a copy of cfg with shrunken timeouts suitable for `wails dev`. 10s for the ADB loop, 15s for the boot probe, 500ms poll cadence, no nuclear option. A coding error in dev cycles through the failure modes in ~25s instead of 180s+.

type BootContext

type BootContext struct {
	Client              *adb.Client
	DeviceID            string
	PackageName         string
	ScreenW             int
	ScreenH             int
	ExpectedScreenW     int
	ExpectedScreenH     int
	BlueStacksRestarted bool
	Report              BootReportView
	BootDuration        time.Duration
	RecoveryUsed        []string
}

BootContext is what the orchestrator returns on success. NewBot reads ScreenW/H to build the Calibration; everything else is passed through to the Bot struct for runtime use.

Report is a value-copyable BootReportView (no mutex), safe to pass across goroutines, serialize, or emit via Wails.

type BootOrchestrator

type BootOrchestrator struct {
	// contains filtered or unexported fields
}

BootOrchestrator is the live state of a single boot attempt. One per NewBot call. Use NewBootOrchestrator to construct.

func NewBootOrchestrator

func NewBootOrchestrator(cfg BootConfig, client *adb.Client, logger zerolog.Logger) *BootOrchestrator

NewBootOrchestrator wires the orchestrator. The client is the already-constructed adb.Client from NewBot (no transport connect has happened yet — the orchestrator does that itself).

func (*BootOrchestrator) Boot

Boot runs the full sequence. The returned BootContext is non-nil iff err is nil. On failure the BootContext is nil; use orchestrator.Report().Snapshot() to get the structured report.

func (*BootOrchestrator) Report

func (o *BootOrchestrator) Report() *BootReport

Report returns the live (not snapshot) report. Callers that need to serialize should use Report().Snapshot() instead.

type BootProfile

type BootProfile struct {
	DeviceID      string              `json:"device_id,omitempty"`
	Samples       []BootProfileSample `json:"samples"`
	LastUpdated   time.Time           `json:"last_updated"`
	RecommendedMs int                 `json:"recommended_timeout_ms"`
	// contains filtered or unexported fields
}

BootProfile is the persistent learned-timing record for a single device. Currently the file is per-host (one profile, not per device), but the DeviceID field is kept on every sample so a future per-device split is a one-line change.

func LoadBootProfile

func LoadBootProfile(path string) (*BootProfile, error)

LoadBootProfile reads path from disk. A missing file is not an error — the caller gets a default profile. Any other read or parse failure is returned wrapped.

func NewBootProfile

func NewBootProfile() *BootProfile

NewBootProfile returns a fresh, empty profile. Use LoadBootProfile to read an existing one from disk.

func (*BootProfile) AddSample

func (p *BootProfile) AddSample(s BootProfileSample)

AddSample appends a sample and recomputes the recommended timeout in one atomic-with-respect-to-readers step. Trims the rolling window to MaxBootProfileSamples so the file stays small.

Recommendation rule:

  • If any sample is a "timeout", the recommended timeout is bumped to max(p95(all) * 1.5, currentRecommended).
  • Otherwise the recommended timeout is max(p95(successful) * 1.5, MinRecommended).
  • Always clamped to [Min, Max].

1.5x headroom covers a single noisy run without overcorrecting.

func (*BootProfile) RecommendedTimeout

func (p *BootProfile) RecommendedTimeout() time.Duration

RecommendedTimeout returns the recommended boot timeout in milliseconds, clamped to [Min, Max]. The mutex is held only for the read; recomputation is cheap.

func (*BootProfile) Save

func (p *BootProfile) Save(path string) error

Save writes the profile to path atomically (write to .tmp, fsync, rename). The mutex is held only over the in-memory mutation; the disk write is best-effort and any error is returned to the caller.

type BootProfileSample

type BootProfileSample struct {
	StartedAt time.Time `json:"started_at"`
	Duration  int64     `json:"duration_ms"`
	Outcome   string    `json:"outcome"`
}

BootProfileSample is one observation. Outcome is "ok" or "timeout" — both are recorded so the recommended timeout adapts to BOTH typical-case speed AND the worst-case stretch the user has hit.

type BootReport

type BootReport struct {
	// contains filtered or unexported fields
}

BootReport is the full per-attempt record. It is safe for concurrent writes via the embedded mutex; the orchestrator holds the lock while appending steps. DO NOT copy a BootReport by value — use Snapshot() to get a value-copyable BootReportView for reads, JSON marshaling, or Wails emission.

The mutex is embedded (not a pointer) so the zero value is usable without explicit initialization. NewBootReport() handles the slice and map allocations.

func NewBootReport

func NewBootReport() *BootReport

NewBootReport constructs an empty report with the current wall clock as the start time. The caller is expected to fill DeviceID, PackageName, ExpectedWidth/Height, and Metadata before appending the first step (or, at minimum, before Snapshot() / Complete()).

func (*BootReport) AppendStep

func (r *BootReport) AppendStep(name string, startedAt time.Time, result BootResult, detail string)

AppendStep records a completed step. Safe for concurrent use. The passed-in startedAt is when the step began; Duration is recomputed here to keep callers from getting the wall-clock math wrong.

func (*BootReport) Complete

func (r *BootReport) Complete(outcome string, err error, suggestedAction string)

Complete finalizes the report. outcome should be "ok" or "failed". err may be nil for "ok". suggestedAction is a short imperative like "wait longer" or "relaunch BlueStacks manually" — surfaced in the UI and the JSON file.

func (*BootReport) JoinedStepSummary

func (r *BootReport) JoinedStepSummary(maxLen int) string

JoinedStepSummary returns "adb.connect=ok/2.1s | boot.probe=ok/87s | ..." suitable for one-line log emission and the Wails bot_init_report event payload. Truncates to maxLen characters with a trailing "…" so a 90-second probe doesn't blow up a UI card.

func (*BootReport) MarkRecovery

func (r *BootReport) MarkRecovery(strategy string)

MarkRecovery appends a recovery-strategy name to the report. Called once per executed strategy (not per attempt) so the user can see "we had to SoftReset this time" in the UI.

func (*BootReport) SaveJSON

func (r *BootReport) SaveJSON(path string) error

SaveJSON writes the report to path as pretty-printed JSON. Errors are returned to the caller but should typically be logged at debug level — a failed persistence must not itself become a boot failure.

func (*BootReport) SetAttempts

func (r *BootReport) SetAttempts(n int)

SetAttempts records the number of probe attempts the orchestrator made. Called once at the end of the boot.

func (*BootReport) SetBlueStacksEnsured

func (r *BootReport) SetBlueStacksEnsured(v bool)

SetBlueStacksEnsured marks whether EnsureBlueStacksMac was called during this boot. Used by the UI to distinguish "cold-started BlueStacks" from "reused an already-running instance."

func (*BootReport) SetDeviceContext

func (r *BootReport) SetDeviceContext(deviceID, packageName string, width, height int)

SetDeviceContext sets the device/package/resolution fields. Called once at construction so Snapshot() can include them in the view. Safe to call before any concurrent writer exists.

func (*BootReport) SetMetadata

func (r *BootReport) SetMetadata(kv map[string]string)

SetMetadata merges key/value pairs into the report's free-form metadata. Safe for concurrent use. Existing keys are overwritten; new keys are added.

func (*BootReport) Snapshot

func (r *BootReport) Snapshot() BootReportView

Snapshot returns a value-copyable, JSON-marshalable view of the report. The mutex is held only long enough to clone the slices and map; the returned BootReportView is independent of the source BootReport and can be passed across goroutines, marshaled, or emitted via Wails without any lock-copy issues.

func (*BootReport) Summary

func (r *BootReport) Summary() string

Summary returns a one-line human description for log lines. Format:

"boot ok in 12.3s (4 steps, no recovery)"                   — success
"boot failed in 90.0s: android boot timeout (5 steps, 2 recovery)" — failure

type BootReportView

type BootReportView struct {
	StartedAt         time.Time         `json:"started_at"`
	CompletedAt       time.Time         `json:"completed_at,omitempty"`
	Duration          time.Duration     `json:"duration_ns"`
	Outcome           string            `json:"outcome"`
	FinalError        string            `json:"final_error,omitempty"`
	SuggestedAction   string            `json:"suggested_action,omitempty"`
	DeviceID          string            `json:"device_id,omitempty"`
	PackageName       string            `json:"package_name,omitempty"`
	ExpectedWidth     int               `json:"expected_width,omitempty"`
	ExpectedHeight    int               `json:"expected_height,omitempty"`
	BlueStacksEnsured bool              `json:"bluestacks_ensured"`
	RecoveryUsed      []string          `json:"recovery_used,omitempty"`
	Attempts          int               `json:"attempts"`
	Steps             []BootStep        `json:"steps"`
	Metadata          map[string]string `json:"metadata,omitempty"`
}

BootReportView is the JSON-serializable, Wails-emittable, copyable view of a BootReport. It has the same fields as BootReport minus the mutex, and is what callers actually read/serialize. The orchestrator hands out views via Snapshot() and the React side consumes them as plain JSON.

type BootResult

type BootResult string

BootResult is the terminal outcome of a single step in the boot pipeline. We keep it as a small enum-style string so it round-trips through JSON cleanly and is grep-friendly in app.log.

const (
	BootResultOK      BootResult = "ok"
	BootResultTimeout BootResult = "timeout"
	BootResultError   BootResult = "error"
	BootResultSkipped BootResult = "skipped"
)

type BootStep

type BootStep struct {
	Name      string        `json:"name"`
	StartedAt time.Time     `json:"started_at"`
	Duration  time.Duration `json:"duration_ns"`
	Result    BootResult    `json:"result"`
	Detail    string        `json:"detail,omitempty"`
}

BootStep is one discrete phase of the boot sequence. The orchestrator emits one per phase. Latency at the field level is the per-step duration; cumulative timing is recomputed by Summary().

func (BootStep) StepSummary

func (s BootStep) StepSummary() string

StepSummary is a small printable summary for the React side / log line. One per step, joined with " | " by JoinedStepSummary.

type Bot

type Bot struct {
	OnStatsUpdate func()
	// contains filtered or unexported fields
}

func NewBot

func NewBot(cfg *config.BotConfig) (*Bot, error)

NewBot builds a fully-booted Bot using a background context (no external cancellation). CLI and tests use this; the Wails app uses NewBotWithContext so a Stop click can abort a boot in progress.

func NewBotWithContext

func NewBotWithContext(bootCtx context.Context, cfg *config.BotConfig) (b *Bot, err error)

NewBotWithContext boots the bot under the caller's context. The context is threaded through the boot orchestrator AND becomes the parent of the bot's runtime context, so cancelling it (the app's Stop click) aborts an in-progress boot and stops a running bot.

On any error the freshly-constructed adb.Client is closed — a failed boot must not leak a half-open transport (visible as a lingering localhost:5555 ghost that breaks the next Start).

func NewHeadlessBot added in v1.1.0

func NewHeadlessBot(cfg *config.BotConfig) *Bot

NewHeadlessBot builds a Bot that owns cfg and the same config-consuming sub-managers a booted bot builds, without dialing ADB or launching the game. UpdateConfig then takes the identical code path it takes during a run, so a wiring check can assert that a UI change reaches the scheduler gate and the builder manager filters. It cannot run a session: Start needs a device.

func (*Bot) Cancel

func (b *Bot) Cancel()

Cancel signals the bot's context to stop. The captureLoop and any in-flight attack sequence see the cancellation on their next `b.ctx.Done()` check (sub-millisecond), which is what makes the Stop button feel "instant" to the user — no more taps, captures, state transitions, or attack progression. The full `Stop()` path (ADB close, async-writer drain, file flush) is intentionally kept out of this method so callers can split the work: `Cancel()` for the synchronous "stop what you're doing" signal, and `Stop()` for the heavier teardown that App.StopBot detaches into a goroutine.

func (*Bot) CollectVillageResources

func (b *Bot) CollectVillageResources()

CollectVillageResources sweeps the main village collector positions to collect ready Gold Mines, Elixir Collectors, Dark Elixir Drills, and Loot Cart.

The sweep used to be a metronome: the same five coordinates, in the same order, at the same 350 ms cadence, every five minutes, forever. That is the strongest behavioural signature in the app after the builder menu. Order, point offsets and dwell are now drawn per pass, one pass in five skips a point entirely, and the closing backdrop tap is jittered like every other input.

func (*Bot) Done

func (b *Bot) Done() <-chan struct{}

Done returns a channel that closes when the bot's runtime context is cancelled — i.e. after a Stop, or after the attack-cap graceful shutdown (a --once CLI run). External owners (the CLI main) wait on it so they can exit once the bot finishes its session instead of blocking on a signal that never arrives.

func (*Bot) DumpDiagnostics

func (b *Bot) DumpDiagnostics(reason string, screen gocv.Mat, context map[string]interface{}) error

DumpDiagnostics saves a screenshot and a JSON file containing the bot's state.

func (*Bot) HaltedReason added in v1.1.0

func (b *Bot) HaltedReason() HaltReason

HaltedReason returns the current halt verdict for the UI.

func (*Bot) Health

func (b *Bot) Health() game.SystemHealth

func (*Bot) LiveConfig added in v1.1.0

func (b *Bot) LiveConfig() LiveConfig

LiveConfig snapshots the effective configuration. Every part is read through the owner's own publication mechanism (atomic pointer or mutex-guarded copy), so it is safe to call while a save is in flight.

func (*Bot) QuickDeploy

func (b *Bot) QuickDeploy() error

QuickDeploy is the manual single-shot deploy path for tools/run_designed_attack.sh. The user is assumed to already be on the attack screen with a base loaded — there's no search loop, no attack-button discovery, no home → finds-match pipeline. We capture the current screen once, run deployTroops (which honors formula.json overrides if design_attack wrote one next to the strategy), and return.

The captureLoop is intentionally NOT started; cli.go's --deploy-only branch calls this directly and bypasses b.Start() to avoid the Find-Attack-Button race that would otherwise kick the bot into the next-base search cycle.

On non-Battle screens (e.g. user is still on home, or in clouds), we log a WARN and proceed anyway — the deployTroops path will see the absence of a troop bar and either error out cleanly or succeed-by-luck if the screen does actually contain a deployable base. Caller should surface the error.

func (*Bot) ResetStats added in v1.1.0

func (b *Bot) ResetStats()

ResetStats zeroes the session counters while the bot keeps running. Uptime restarts from zero without touching startedAt, so a reset live session does not race the goroutine that reads Stats.

func (*Bot) Start

func (b *Bot) Start() error

func (*Bot) Stats

func (b *Bot) Stats() BotStats

func (*Bot) Stop

func (b *Bot) Stop()

func (*Bot) UpdateConfig

func (b *Bot) UpdateConfig(cfg *config.BotConfig)

UpdateConfig applies a live settings save. It replaces the published configuration atomically and hands each sub-manager a copy under its own lock, so a save from the UI goroutine cannot race the capture loop, the attack sequence or the stats poll.

func (*Bot) UpgradeWalls

func (b *Bot) UpgradeWalls(gc *game.GameContext)

UpgradeWalls executes the wall-upgrade sequence repeatedly until no more affordable options exist. After this refactor it is a thin wrapper that delegates to runWallUpgradeLoop with the production Bot's dependencies. The diagnostic tool at cmd/test_wall_upgrade calls runWallUpgradeLoop directly with a hand-built hooks struct.

type BotStats

type BotStats struct {
	AttacksCompleted int32         `json:"attacks_completed"`
	SearchSkips      int32         `json:"search_skips"`
	TotalGold        int64         `json:"total_gold"`
	TotalElixir      int64         `json:"total_elixir"`
	TotalDE          int64         `json:"total_de"`
	Stars0           int32         `json:"stars_0"`
	Stars1           int32         `json:"stars_1"`
	Stars2           int32         `json:"stars_2"`
	Stars3           int32         `json:"stars_3"`
	Uptime           time.Duration `json:"uptime"`
	AdbHealth        adb.Health    `json:"adb_health"`

	CPUTimeSec float64 `json:"cpu_time_sec"`

	CPUCores float64 `json:"cpu_cores"`

	// Classify-gate observability (see classifygate.go): how many frames were
	// classified, how many reused the previous verdict, and how much the last
	// frame changed. These are how a user verifies the setting on their device.
	ClassifyRan          int64   `json:"classify_ran"`
	ClassifyReused       int64   `json:"classify_reused"`
	LastFrameChangePct   float64 `json:"last_frame_change_pct"`
	ClassifyGateEnabled  bool    `json:"classify_gate_enabled"`
	ClassifyThresholdPct float64 `json:"classify_threshold_pct"`

	// Capture-cache observability (see internal/adb/capturecache.go): captures
	// the emulator was not asked to take because another consumer had just read
	// the same screen, and how many requests the input barrier refused (a frame
	// older than the bot's last tap must never answer a post-tap check). Hits
	// climbing means the emulator is doing less; hits at zero with the cache
	// enabled means nothing captures concurrently on this workload.
	CaptureCache adb.CaptureCacheStats `json:"capture_cache"`

	// Pacing telemetry. A bot that is deliberately idle (scheduler break, full
	// storages, empty army) used to look identical to a working one in both the
	// UI and the logs; these fields are the difference, and HaltedReason is the
	// single answer to "why is it not attacking right now?".
	ScheduleEnabled  bool   `json:"schedule_enabled"`
	ScheduleState    string `json:"schedule_state"`
	HaltedReason     string `json:"halted_reason,omitempty"`
	AttacksToday     int    `json:"attacks_today"`
	MaxAttacksPerDay int    `json:"max_attacks_per_day"`
	NextChangeAt     string `json:"next_change_at,omitempty"`
}

type BuilderManager

type BuilderManager struct {
	// contains filtered or unexported fields
}

BuilderManager automates village progression using the modern Clash of Clans Build Overview Menu (Suggested Upgrades, Laboratory, and Hero Pets) with fine-grained strategy filters (heroes first, cheapest first, category toggles, and max spend limits).

func NewBuilderManager

func NewBuilderManager(client *adb.Client, cal *game.Calibration, cfg config.UpgradeConfig, logger zerolog.Logger) *BuilderManager

func (*BuilderManager) ApplyBuildingInGameFilter added in v1.1.0

func (bm *BuilderManager) ApplyBuildingInGameFilter() error

ApplyBuildingInGameFilter drives the Build Menu's own filter popup so the rows the bot OCRs are the rows it asked for: Type buttons follow the category toggles, currency filters are cleared (a selected currency ANDs with Type and hid every row in a live run), and Sorting follows the priority where it maps.

func (*BuilderManager) ApplyLabInGameFilter

func (bm *BuilderManager) ApplyLabInGameFilter(strategy string, k float64)

func (*BuilderManager) CloseMenu

func (bm *BuilderManager) CloseMenu() error

CloseMenu closes the Builder Overview modal by tapping the close button.

func (*BuilderManager) CloseModalDialog

func (bm *BuilderManager) CloseModalDialog() error

CloseModalDialog taps the top-right X button on a modal confirmation dialog.

func (*BuilderManager) OpenMenu

func (bm *BuilderManager) OpenMenu() error

OpenMenu opens the Builder Overview modal from the main village.

func (*BuilderManager) PerformAutoUpgrades

func (bm *BuilderManager) PerformAutoUpgrades() error

PerformAutoUpgrades inspects the builder overview, checks builder availability, and starts eligible building, laboratory, or pet upgrades according to user priorities.

func (*BuilderManager) SetConfig added in v1.1.0

func (bm *BuilderManager) SetConfig(cfg config.UpgradeConfig)

SetConfig replaces the upgrade policy under the lock readers take.

type BuilderOverviewStats

type BuilderOverviewStats struct {
	FreeBuilders  int
	TotalBuilders int
	LabFree       bool
	PetsFree      bool
	Items         []UpgradeItem
}

BuilderOverviewStats holds parsed status of the builder menu tabs.

func ParseBuilderOverviewOCR

func ParseBuilderOverviewOCR(regions []vision.TextRegion) BuilderOverviewStats

ParseBuilderOverviewOCR parses recognized text regions from a builder overview frame.

type DiagnosticData

type DiagnosticData struct {
	Timestamp time.Time              `json:"timestamp"`
	Reason    string                 `json:"reason"`
	State     string                 `json:"state"`
	Context   map[string]interface{} `json:"context,omitempty"`
}

DiagnosticData holds the state of the bot at the time of failure.

type FailureContext

type FailureContext struct {
	TransportDown bool
}

FailureContext describes what the failed step says about the world, so the ladder can skip strategies that cannot help. Today it carries one bit: TransportDown means the ADB shell path itself is dead (screencap AND package manager both errored). RelaunchGame is a force-stop + start over that same shell: firing it with a dead transport burns ~5-15s proving nothing, so the ladder jumps straight to the emulator-level strategies.

type HaltReason added in v1.1.0

type HaltReason string

HaltReason is why the bot is not attacking. Empty means "nothing is holding it back". It is a string (not an int) because it travels to the React UI through BotStats and is read by humans in the log.

const (
	HaltNone        HaltReason = ""
	HaltScheduler   HaltReason = "scheduler"
	HaltStorageFull HaltReason = "storage_full"
	HaltArmyEmpty   HaltReason = "army_empty"
	HaltCap         HaltReason = "session_cap"
)

type LiveConfig added in v1.1.0

type LiveConfig struct {
	// Config is the pointer the capture loop, storage gate, wall upgrade and
	// scheduler gate read directly through b.cfg().
	Config config.BotConfig
	// ArmySlot is the recipe slot resolved from Attack.StrategySlots and the
	// strategy YAML — what the train menu will arm.
	ArmySlot int
	// Scheduler is the copy the scheduler gate (CanAttack) uses.
	Scheduler *config.ScheduleConfig
	// Upgrade is the copy the builder manager's filters and pet/lab selection
	// use (BuilderManager.cfg).
	Upgrade *config.UpgradeConfig
}

LiveConfig is the configuration the running loop and its config-owning sub-managers currently hold. It exists so a wiring check can prove that a settings change reached the object the loop reads, instead of only proving that a value reached config.json.

The pointers are nil when the corresponding owner is not built (a headless wiring bot has no attack executor, for example).

type Pinpoint

type Pinpoint struct {
	X, Y int
	Name string
	// XA and YA declare which screen edge — or the axis centre — the point
	// keeps its distance to, one anchor per axis. Measured, not inferred: the
	// game anchors each widget per axis, so a single Anchor for both axes (or
	// the classifier's band heuristic, which reads the widget's reference y)
	// cannot express the layout. The attack menu is the case that broke 720p
	// live: its buttons keep their left edge offset (ref x 158 -> 209) but are
	// centred vertically (ref y 494 -> 530, where the bottom-edge model put
	// them at 405 — 125 px above the button, so Find a Match was never
	// clicked and the search never started). See docs/RESOLUTION.md.
	//
	// Verified live at 1280x720 with cmd/tplprobe and Apple Vision OCR on the
	// same screen at both geometries.
	XA, YA game.AxisAnchor
}

Pinpoint defines a precise location on the reference screen (860x732) and a color check to verify it before clicking.

type RecoveryConfig

type RecoveryConfig struct {
	MaxAttempts int

	AllowNuclear bool

	InitialBackoff time.Duration
	MaxBackoff     time.Duration
}

RecoveryConfig is the orchestration knobs the policy consults.

type RecoveryPolicy

type RecoveryPolicy struct {
	// contains filtered or unexported fields
}

RecoveryPolicy wires the strategy ladder to the live Client. It is constructed once by the orchestrator and consulted at most once per attempt. Stateless after construction.

func NewRecoveryPolicy

func NewRecoveryPolicy(cfg RecoveryConfig, client adbClient) *RecoveryPolicy

NewRecoveryPolicy constructs a policy. The client is the live ADB client (or a fake in tests); the cfg carries the budgets.

func (*RecoveryPolicy) Backoff

func (p *RecoveryPolicy) Backoff(attempt int) time.Duration

Backoff returns the wait time before the next attempt. Exponential with a cap, starting from cfg.InitialBackoff. attempt is 1-based.

func (*RecoveryPolicy) Escalate

func (p *RecoveryPolicy) Escalate(strats []RecoveryStrategy, attempt int, fc FailureContext) int

Escalate decides which strategy (by index in Strategies()) to try next. failureContext tells the policy what step failed; the return value is the index into Strategies() to try, or -1 if the ladder is exhausted.

The walk is linear from the attempt offset, except game-level strategies (RelaunchGame) are skipped while the transport is down — relaunching the game over a dead shell cannot work, and the wait it costs is the slowest part of a recovery users watch.

func (*RecoveryPolicy) Strategies

func (p *RecoveryPolicy) Strategies(packageName string, w, h, dpi int) []RecoveryStrategy

Strategies returns the ordered ladder for the current config. The returned slice is a fresh copy — callers can mutate without affecting future ladders.

Order rationale (cheapest to most-destructive, with the diagnostics- first principle applied):

  1. RetryTransport — close + reopen the ADB transport socket. Fast (~50ms). Handles a stale connection from a fresh BlueStacks start.
  2. ResetAdbServer — `adb kill-server` + `adb start-server`. ~3s. Handles the "localhost:5555 listed as offline in `adb devices` even though the device is up" failure mode that hits after a hard kill or a wails-dev session. Non-destructive of the emulator state but does drop ALL adb connections globally — noted in the BootReport.
  3. SoftReset — `adb shell stop && adb shell start`. Restarts the Android runtime without killing BlueStacks. ~8s. Handles Android wedged at the runtime layer.
  4. RelaunchGame — force-stop + restart CoC via monkey. Doesn't touch BlueStacks or Android. ~5s. Useless if ADB isn't yet talking to a device, so in practice only invoked from the boot-probe ladder.
  5. RestartBlueStacks — osascript quit + open -a BlueStacks. ~15s. The nuclear option, only used when AllowNuclear is true and everything above has failed.

type RecoveryStrategy

type RecoveryStrategy struct {
	Name string

	Apply func(ctx context.Context) error

	Cost time.Duration

	Destructive bool
}

RecoveryStrategy is one named escalation step.

type Rect

type Rect struct {
	X1 int `json:"x1"`
	Y1 int `json:"y1"`
	X2 int `json:"x2"`
	Y2 int `json:"y2"`
}

Rect is the JSON-friendly shape for picker'd tap regions. Each of the three wall-upgrade asset files

  • assets/wall_upgrade_buttons.json (top-level: gold, elixir)
  • assets/wall_upgrade_confirm.json (top-level: confirm_button)
  • assets/wall_upgrade_x_roi.json (top-level: x_popup_roi)

writes a top-level dict with one or more {x1, y1, x2, y2} rects, which this struct decodes uniformly.

Coords are REFERENCE-frame (860x732) pixels: the pickers write the pick's `reference` block as `physical / scale`, and the shipped wall-upgrade assets were picked at 860x732, where that division is the identity. They are mapped into live geometry by Rect.Live at load time (see that method for the law and for what consuming them raw cost on a 1280x720 device).

The legacy tap pattern in earlier versions of this file used the image.Rectangle stdlib type via image.Rect(x1,y1,x2,y2). image.Rectangle serializes to JSON as `{"Min":{"X":x,"Y":y},"Max":{"X":x2,"Y":y2}}`, which doesn't match the picker's flat x1/y1/x2/y2 output. The Rect struct here decodes the flat shape 1:1 with no per-file ad-hoc map[string]int shape, so adding a new asset file is one struct-tag each.

func (Rect) Center

func (r Rect) Center() (cx, cy int)

Center returns ((X1+X2)/2, (Y1+Y2)/2). Integer truncation matches adb input.tap's nearest-pixel rounding, so a 153-wide rect lands at ±0.5 px off geometric center — visually indistinguishable from the user's drag.

func (Rect) Empty

func (r Rect) Empty() bool

Empty returns true if the rect has zero area — i.e., zero width (X1==X2) OR zero height (Y1==Y2). The picker writes degenerate (0,0,0,0) only when handed a broken drag; the loaders use Empty() to reject that so the bot's tap path starts with `ok=false` rather than emitting a 0-area tap region that would silently tap the top-left corner of the screen. The all-zero (0,0,0,0) case is covered by the X1==X2 path because (X1==X2 AND Y1==Y2) is a subset of (X1==X2 OR Y1==Y2).

func (Rect) ImageRect

func (r Rect) ImageRect() image.Rectangle

ImageRect converts to Go's stdlib image.Rectangle for use with gocv.Region / image.Rect expected by vision math elsewhere. The returned rectangle uses the same Min/Max convention as image.Rect.

func (Rect) Live

func (r Rect) Live(cal *game.Calibration) Rect

Live maps a rect from the authored frame the pickers wrote it in into the live geometry, so a device that is not the reference geometry taps its widgets and not the map next to them.

Every rect in this family (wall_upgrade_buttons.json, ..._confirm.json, ..._x_roi.json) holds REFERENCE-frame (860x732) coordinates. Both pickers that write them derive a `reference` block as `physical / scale` (tools/picker.py's menu preset, tools/internal/select_builder_roi.py), and the shipped wall_upgrade_*.json files carry physical == reference — the values were picked at 860x732, where that division is the identity. The tap path used to consume those numbers RAW, which is right only while the device still runs the reference geometry. On the live 1280x720 device (pinned k = 1.325, device.display_scale) raw consumption put the resource buttons ~210 px and the gem-buy X ~110 px from their widgets, i.e. the blind taps fired into the village instead of the tray — the failure mode docs/RESOLUTION.md lists under "Consequences of flipping 860x732 -> 1280x720 with only a config change".

The law is the HUD one (Calibration.HudRect): the widget keeps its distance to the edge it sits against — the tray buttons and the popup X are bottom- and right/centre-anchored chrome — and its size grows with k. It is the identity at the reference geometry and for a nil Calibration, which is what keeps the authored 1:1 dataset and the small-frame test fixtures valid unchanged.

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

func NewScheduler

func NewScheduler(cfg config.ScheduleConfig, logger zerolog.Logger) *Scheduler

func (*Scheduler) AttacksToday added in v1.1.0

func (s *Scheduler) AttacksToday() (attacks, cap int)

AttacksToday reports today's completed attacks against the configured cap, for the dashboard. A cap of 0 means unlimited.

func (*Scheduler) CanAttack

func (s *Scheduler) CanAttack(now time.Time) (bool, string)

CanAttack evaluates whether the bot is authorized to start an attack right now. Returns (allowed, reason).

func (*Scheduler) Config added in v1.1.0

func (s *Scheduler) Config() config.ScheduleConfig

Config returns a snapshot of the schedule for diagnostics.

func (*Scheduler) Counters added in v1.1.0

func (s *Scheduler) Counters() (daily int, hourly []time.Time, date string)

Counters returns the rate-limit state for persistence: today's count, the day it belongs to, and the timestamps inside the hourly window (pruned to one hour so the saved file cannot grow without bound).

func (*Scheduler) NextChange added in v1.1.0

func (s *Scheduler) NextChange(now time.Time) time.Time

NextChange is when the scheduler state changes by itself: the end of the current break, the end of the current session, or the next active-hours boundary. Zero means "no scheduled change" (scheduler disabled).

func (*Scheduler) RecordAttack

func (s *Scheduler) RecordAttack(now time.Time)

RecordAttack records an attack completion for rate limiting.

func (*Scheduler) RestoreCounters added in v1.1.0

func (s *Scheduler) RestoreCounters(daily int, date string, hourly []time.Time)

RestoreCounters seeds the rate-limit state from the previous process. A counter from an older day is dropped: it cannot apply to today's cap, and keeping it would only make the UI report a number that is not this day's.

func (*Scheduler) SetBreakHooks

func (s *Scheduler) SetBreakHooks(onEnter, onExit func())

func (*Scheduler) SetConfig added in v1.1.0

func (s *Scheduler) SetConfig(cfg config.ScheduleConfig)

SetConfig replaces the schedule under the same lock every reader takes, so a live settings save cannot be observed half-applied (session window, break, caps and active hours all belong to one config value).

func (*Scheduler) State

func (s *Scheduler) State() SchedulerState

func (*Scheduler) TriggerPersonalBreak

func (s *Scheduler) TriggerPersonalBreak(duration time.Duration, reason string)

TriggerPersonalBreak triggers an immediate break when Supercell shows Personal Break modal.

type SchedulerState

type SchedulerState string
const (
	SchedulerActive SchedulerState = "ACTIVE"
	SchedulerBreak  SchedulerState = "BREAK"
	SchedulerSleep  SchedulerState = "SLEEP"
)

type UpgradeItem

type UpgradeItem struct {
	Name     string
	Category string // "heroes", "defenses", "resources", "army", "traps", "other"
	Cost     int
	Currency string // "gold", "elixir", "dark_elixir"
	Duration string
	Region   vision.TextRegion
}

type WallUpgradeHooks

type WallUpgradeHooks struct {
	Logger    zerolog.Logger
	Client    wallClient
	Cal       *game.Calibration
	Templates *game.TemplateStore

	// Classify is invoked with each capture during the MainVillage
	// verify loop and to detect interruption dialogs. May be nil.
	Classify func(gocv.Mat) (game.GameState, int)

	// Classifier is the classifier DismissOverlay verifies an interruption
	// against before moving it (see game/dismiss.go). May be nil; a nil
	// classifier makes interruption dismissal a no-op rather than a blind tap,
	// which is the safe direction. Production wires the bot's own classifier.
	Classifier *game.Classifier

	// Dismiss taps a neutral background area to clear any active
	// wall-selection after a failed button-template match. May be nil.
	Dismiss func()

	// StopCheck is consulted at the top of every wall-upgrade
	// iteration; when it returns true the loop breaks immediately
	// (between walls, never mid-tap). May be nil. Production wires
	// `func() bool { return b.ctx.Err() != nil }` so a user Stop
	// interrupts an otherwise-unbounded wall-upgrade run.
	StopCheck func() bool

	// WallResource specifies resource preference ("gold", "elixir", "both").
	WallResource string

	// OnStep is the optional phase-boundary instrumentation hook.
	OnStep func(step string, data map[string]any)

	// Sleep is the sequence's timing primitive. nil means time.Sleep, which
	// is the production behaviour. A caller (the test suite) may inject a
	// no-op so a full pass costs milliseconds instead of the ~20s of
	// animation/ADB settle the sequence is tuned for on a real device.
	Sleep func(time.Duration)
}

WallUpgradeHooks groups the dependencies a wall-upgrade loop iteration needs. Used both by Bot.UpgradeWalls (production path) and the cmd/test_wall_upgrade diagnostic tool.

Optional fields:

  • Classify: nil disables state verification + interruption dismissal (the diagnostic tool's "manual" mode assumes the user navigated the game into MainVillage themselves and skips dialog handling).
  • OnStep: nil silences all instrumentation events. When wired, each phase boundary calls OnStep("phase_name", data). The diagnostic tool uses this to save annotated screenshots per phase. Frames are only cloned for a wired receiver (see stepScreen).
  • Sleep: nil means time.Sleep. A no-op injection lets the test suite run a full sequence in milliseconds.
  • Dismiss: nil makes the loop's fallback skip the neutral-tap dismiss (e.g. when btn_upgrade_wall or btn_confirm_upgrade fail matching). Production wires this to Bot.dismissSelection.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL