{"modulePath":"github.com/bborbe/agent-task-executor","version":"v0.71.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package handler\n\n## Constants\n\n```go\nconst DefaultReconcileInterval = 60 * time.Second\n```\nDefaultReconcileInterval is the default interval between reconcile-loop passes (spec 005), overridable per deployment via RECONCILE\\_INTERVAL. 60s is a reasonable recovery latency for a task whose deferral was lost across a restart.\n\n```go\nconst DefaultReconcilePassTimeout = 45 * time.Second\n```\nDefaultReconcilePassTimeout bounds one reconcile pass so a slow or large vault cannot hold a pass open indefinitely (spec 005 Failure Modes: \"Pass bounded by a per-pass timeout; logs evaluate count so cost is visible\"). Three quarters of the interval: a pass completes within a tick and leaves headroom for the next one. Raised from 30s on 2026-10-19 — a pass over the openclaw vault aborted on \\`context\\_cancelled\\` every minute after evaluating only 8-73 of ~200 non-terminal tasks, so the tasks ordered after the cut were never reached. The per-assignee active-Job cache added in the same change removes most of the cost; this is the headroom that keeps a slow pass from re-opening the same window. Overridable per deployment via RECONCILE\\_PASS\\_TIMEOUT: on 2026-10-21 a sun executor reading the 15k-file openclaw vault aborted every pass at 45s with evaluated=0.\n\n```go\nconst DefaultRunClaimTTL = 2 * time.Hour\n```\nDefaultRunClaimTTL is how long a run\\_claim frontmatter value is treated as live. It matches the dev run budget (runBudgetSeconds: 7200), so one claim covers the whole window a single trading run may occupy.\n\n## Functions\n\n```go\nfunc DefaultVaultAliases(vault string) []string\n```\nDefaultVaultAliases returns the built-in alias set for vault, or nil when the vault has no known alias. A nil result means exact equality, which is the behaviour of every vault that is not mid-rename.\n\n```go\nfunc IsTerminal(phase domain.TaskPhase) bool\n```\nIsTerminal reports whether the given phase is in the terminal set. Tasks at a terminal phase must not be re-spawned; operator intervention is required.\n\n```go\nfunc IsTerminalStatus(status domain.TaskStatus) bool\n```\nIsTerminalStatus reports whether the given status is in the terminal set. A terminal task must never be a candidate: its file says the work is over, so a spawn could only hand an agent a task nobody wants run, and a cap would charge it to the re-drive budget on every pass forever.\n\n```go\nfunc NewAgentsHandler(provider k8s.Provider[agentv1.Config], authSecret string) http.Handler\n```\nNewAgentsHandler returns an http.Handler that lists all known agent configs from the in-memory store as JSON. If authSecret is non-empty, requests must include X-Agent-Auth header with the secret.\n\n```go\nfunc NewHealthcheckTriggerHandler(\n\trunner probe.HealthcheckRunner,\n) http.Handler\n```\nNewHealthcheckTriggerHandler returns an HTTP handler that fires the healthcheck runner once per invocation with fire-and-forget + single-flight semantics. Concurrent invocations collapse into one in-flight run (second request is silently dropped).\n\nThe handler uses context.Background() for its internal operations so it is not affected by the caller's context cancellation. The handler only stops when the HTTP server shuts down.\n\n```go\nfunc NewKubeJobControl(\n\tkubeClient kubernetes.Interface,\n\tnamespace libk8s.Namespace,\n\tresolver pkg.ConfigResolver,\n\tview TaskView,\n) claim.JobControl\n```\nNewKubeJobControl returns the JobControl the lease manager needs before a claim-taking mode may run its fence. Without it a claim that cannot renew keeps its Job running unclaimed, which is the duplicate the claims exist to prevent.\n\nresolver and view let the fence find a Job a Config has placed outside the executor's namespace; either may be nil, in which case every lookup targets the executor's namespace — today's behaviour, and the only behaviour possible before a Config sets jobNamespace.\n\nThe task comes from the TaskView, never from the spawn-time TaskStore: the store is empty after a restart, and startup recovery asks about Jobs this pod was running BEFORE it restarted. Reading the store released the claims of sandboxed Jobs that were still running, so a peer could run the same task twice. The view replays the compacted task event topic instead.\n\n## Types\n\n```go\ntype ClaimLifecycleEventHandler interface {\n\tTaskEventHandler\n\tpkg.ClaimReleaser\n\t// ClaimLeaseManager returns this executor's lease manager, or nil in claim\n\t// mode off, where no manager is constructed.\n\tClaimLeaseManager(ctx context.Context) (claim.LeaseManager, error)\n}\n```\nClaimLifecycleEventHandler is the TaskEventHandler plus the claim lifecycle seam main and the Job watcher use. Every claim method is a no-op in claim mode off.\n\n```go\nfunc NewTaskEventHandler(\n\tjobSpawner spawner.JobSpawner,\n\tnamespace libk8s.Namespace,\n\tbranch base.Branch,\n\tcluster string,\n\tstageFilter bool,\n\trunUntagged bool,\n\tresolver pkg.ConfigResolver,\n\tresultPublisher pkg.ResultPublisher,\n\ttaskStore *pkg.TaskStore,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n\tview TaskView,\n\ttaskVault string,\n\treconcilePassTimeout time.Duration,\n\treconcileInterval time.Duration,\n\tclaimMode pkg.ClaimMode,\n\tclaimRefClientFactory pkg.ClaimRefClientFactory,\n\n\topts ...HandlerOption,\n) ClaimLifecycleEventHandler\n```\nNewTaskEventHandler creates a new TaskEventHandler.\n\n```go\ntype HandlerOption func(*taskEventHandler)\n```\nHandlerOption customises a taskEventHandler at construction. It replaces the former single-purpose variadic so a new optional dependency does not widen the positional parameter list every call site has to repeat.\n\n```go\nfunc WithClaimClientFactory(factory pkg.ClaimClientFactory) HandlerOption\n```\nWithClaimClientFactory supplies the typed vault-api claim client. A claim-taking mode without one fails at lease-manager construction rather than holding nothing, which is why it is not a positional argument: only the modes that take a claim need it, and every other caller would pass a nil it never uses.\n\n```go\nfunc WithClaimJobControl(control claim.JobControl) HandlerOption\n```\nWithClaimJobControl attaches the job control the claim lease manager acts on.\n\n```go\nfunc WithConfigProvider(provider libk8s.Provider[agentv1.Config]) HandlerOption\n```\nWithConfigProvider supplies the Config store the accepted-set metric reads. Nil (the default) skips the refresh.\n\n```go\nfunc WithDeadLetterPublisher(publisher pkg.DeadLetterPublisher) HandlerOption\n```\nWithDeadLetterPublisher attaches the durable sink for a message the consumer can never process. Without it a permanent failure is surfaced rather than skipped, because skipping with nowhere to record the message would lose it.\n\n```go\nfunc WithParkStore(store claim.ParkStore) HandlerOption\n```\nWithParkStore supplies the durable park marker directly, bypassing the claim-ref-client factory. It exists for tests that need a fake — the store's error paths have no other way in, since the factory is a boot-time constructor with no failure mode to provoke.\n\n```go\nfunc WithPodQuotaLimiter(limiter spawner.PodQuotaLimiter) HandlerOption\n```\nWithPodQuotaLimiter attaches the reader that bounds admission by the pod quota of the agent's priority class. An absent limiter means no quota bound.\n\n```go\nfunc WithSuccessStore(store claim.SuccessStore) HandlerOption\n```\nWithSuccessStore supplies the shared success record directly, bypassing the claim-ref-client factory the handler would otherwise build it from. It exists for tests that need a fake — the store's error path has no other way in, since the factory is a boot-time constructor with no failure mode to provoke.\n\n```go\nfunc WithTokenSpendReader(reader claim.TokenSpendReader) HandlerOption\n```\nWithTokenSpendReader supplies the per-task token-history reader the window token ceiling sums. A nil reader (the default) disables the ceiling, which is the no-vault deployment's shape.\n\n```go\nfunc WithVaultAPIIndexClient(client claim.VaultAPIIndexClient) HandlerOption\n```\nWithVaultAPIIndexClient supplies the vault-api task-index reader used by the reconcile pass's view/vault divergence check. A nil client (the default) skips the check, which is the no-URL deployment's shape.\n\n```go\nfunc WithVaultAliases(aliases []string) HandlerOption\n```\nWithVaultAliases replaces the accepted vault names for this executor. It is how VAULT\\_ALIASES reaches the matcher without every call site carrying the value, and it is per handler by construction: two executors built in one process each get their own set, so neither can accept the other's vault.\n\n```go\ntype HighwaterMarksFunc func(ctx context.Context, topic libkafka.Topic) (libkafka.PartitionOffsets, error)\n```\nHighwaterMarksFunc returns the high-water mark of every partition of topic.\n\n```go\ntype TaskEventHandler interface {\n\tConsumeMessage(ctx context.Context, msg *sarama.ConsumerMessage) error\n\t// EvalDeferredRespawns evaluates all pending deferred-respawn entries immediately.\n\t// Called by RunDeferredRespawnLoop on each tick; also callable directly in tests.\n\tEvalDeferredRespawns(ctx context.Context) error\n\t// RunDeferredRespawnLoop polls evalDeferredRespawns every deferredRespawnInterval\n\t// until ctx is cancelled. Must be run alongside the Kafka consumer.\n\tRunDeferredRespawnLoop(ctx context.Context) error\n\t// ReconcileOnce runs one reconcile pass: it snapshots the in-memory task\n\t// view, applies the eligibility filter, and re-drives every eligible owned\n\t// task through the existing spawn path. Called by RunReconcileLoop on each\n\t// tick; also callable directly in tests.\n\tReconcileOnce(ctx context.Context) error\n\t// RunReconcileLoop runs one pass immediately at startup, then every\n\t// reconcile interval until ctx is cancelled. Must be run\n\t// alongside the Kafka consumer.\n\tRunReconcileLoop(ctx context.Context) error\n}\n```\nTaskEventHandler processes task event messages from Kafka and manages deferred respawns.\n\n```go\ntype TaskView interface {\n\t// CaptureHighWaterMarks records the topic's per-partition high-water marks at\n\t// start. It must be called once, before the replay consumer starts.\n\tCaptureHighWaterMarks(ctx context.Context) error\n\t// ConsumeMessage applies one task event. It is the MessageHandler the replay\n\t// consumer is built with.\n\tConsumeMessage(ctx context.Context, msg *sarama.ConsumerMessage) error\n\t// Ready reports whether every partition reached the mark captured at start.\n\tReady() bool\n\t// Snapshot returns a point-in-time copy of every task in the view.\n\tSnapshot() []lib.Task\n\t// Get returns the task for id, or false when the view has none.\n\tGet(id lib.TaskIdentifier) (lib.Task, bool)\n\t// Evict drops the entry for id.\n\t//\n\t// It exists for the one removal no event will ever deliver: a record whose\n\t// task file was deleted from the vault. Kafka compaction keeps the last value\n\t// for every key, so a deleted task never publishes the tombstone the view\n\t// would need, and nothing else can take the entry out. The claim gate is the\n\t// caller — a 404 from the vault is the proof that the file is gone.\n\t//\n\t// Eviction is safe to repeat and safe to race a live event: a later event for\n\t// the same id simply re-adds it, which is what a restored task file publishes.\n\tEvict(id lib.TaskIdentifier)\n}\n```\nTaskView is an in-memory, latest-wins view of the compacted task event topic.\n\n```go\nfunc NewTaskView(\n\thighwaterMarks HighwaterMarksFunc,\n\ttopic libkafka.Topic,\n\tcurrentDateTimeGetter libtime.CurrentDateTimeGetter,\n) TaskView\n```\nNewTaskView creates an empty view for topic.\n\n```go\ntype VaultMatcher struct {\n\t// contains filtered or unexported fields\n}\n```\nVaultMatcher decides whether a task's stamped vault belongs to this executor.\n\nA task is owned when its stamp equals the executor's own task vault, or is one of that vault's accepted aliases. The alias set exists because one Obsidian vault is stamped under more than one slug while a rename is in flight across clusters: plain equality makes every cluster that disagrees silently drop the other's tasks, and that drop is logged rather than raised, so it reads as a quiet fleet.\n\nThe set belongs to the matcher, never to a shared global. A single list applied to every executor would make each one accept the others' vaults — the same bug in the opposite direction, and the reason the tests assert both the admit and the drop.\n\n```go\nfunc NewVaultMatcher(vault string, aliases []string) VaultMatcher\n```\nNewVaultMatcher returns a matcher for vault that accepts vault itself plus every name in aliases. An empty vault accepts nothing.\n\n```go\nfunc (m VaultMatcher) Accepts(stamp string) bool\n```\nAccepts reports whether a task stamped with stamp is owned by this executor. An empty stamp is never owned: a task carrying no stamped vault belongs to no executor.\n\n```go\nfunc (m VaultMatcher) Vault() string\n```\nVault returns the executor's own task vault, for logging.\n\n","path":"github.com/bborbe/agent-task-executor/pkg/handler","name":"handler","synopsis":"","isRedistributable":true}
