{"modulePath":"github.com/bborbe/agent-task-executor","version":"v0.71.2","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package pkg\n\n## Constants\n\n```go\nconst (\n\t// AbortReasonBrokenSignature means the most recent attempts all failed with\n\t// the same broken signature — the work is not going to succeed by retrying.\n\tAbortReasonBrokenSignature = metrics.RedriveAbortReasonBrokenSignature\n\t// AbortReasonTransientExhausted means the failures were transient, but the\n\t// bounded extension is spent.\n\tAbortReasonTransientExhausted = metrics.RedriveAbortReasonTransientExhausted\n)\n```\nThe two reasons a record may be closed out with. The vocabulary is closed: nothing else is ever written to aborted\\_reason by the re-drive path, which is why executor\\_redrive\\_aborted\\_total can be pre-initialised for both values.\n\n```go\nconst (\n\t// ParkReasonLostClaim is the reason a task is parked after another executor\n\t// took over its claim and its Config forbids a rerun.\n\tParkReasonLostClaim = \"parked_lost_claim\"\n\t// ParkReasonSucceeded is the reason a task is parked after its Job succeeded\n\t// without advancing the task's phase.\n\tParkReasonSucceeded = \"parked_succeeded\"\n\t// ParkReasonRedriveCap is the reason a task is parked after its re-drive\n\t// budget was spent on a result that never reported done. It is a distinct\n\t// token from ParkReasonSucceeded on purpose: the two parks have opposite\n\t// outcomes — one is finished work, the other is an escalation — and a shared\n\t// token made a failed run's section byte-identical to a finished one's.\n\tParkReasonRedriveCap = \"parked_redrive_cap\"\n)\n```\nThe reason tokens a park records in its \"## Parked\" section. No two park paths may share one: an operator reading the section has to be able to tell a lost-claim hand-off from a succeeded Job that never moved the phase, and both of those from a run that spent its re-drive budget without finishing.\n\n```go\nconst TaskPhaseAnnotationKey = \"agent.benjamin-borbe.de/task-phase\"\n```\nTaskPhaseAnnotationKey records on a spawned Job the task phase it was spawned for, so the job watcher can tell which phase a succeeded Job completed. An annotation rather than a label: nothing selects on it.\n\n## Variables\n\n```go\nvar DefaultTriggerPhases = domain.TaskPhases{\n\tdomain.TaskPhasePlanning,\n\tdomain.TaskPhaseExecution,\n\tdomain.TaskPhaseAIReview,\n}\n```\nDefaultTriggerPhases is the fallback phase allow-list used when a Config carries no Trigger or an empty phase list. It holds every phase the executor runs: planning, execution and ai\\_review.\n\n```go\nvar ErrClaimModeInvalid = stderrors.New(\"claim mode invalid\")\n```\nErrClaimModeInvalid is returned by ParseClaimMode for an unrecognised or explicitly empty value.\n\n```go\nvar ErrConfigAmbiguous = stderrors.New(\"config ambiguous\")\n```\nErrConfigAmbiguous is returned by ConfigResolver.ResolveByTaskType when more than one Config in the store declares the requested task\\_type. The executor does not guess between them: the ambiguous task is left untouched and the skip is logged, so an operator can narrow the Configs' taskTypes.\n\n```go\nvar ErrConfigNotFound = stderrors.New(\"config not found\")\n```\nErrConfigNotFound is returned by ConfigResolver.Resolve when no Config in the store has a matching Spec.Assignee.\n\n## Functions\n\n```go\nfunc CurrentRunWindowStart(now time.Time, window *agentv1.RunWindow) (time.Time, bool)\n```\nCurrentRunWindowStart returns the instant the current run window opened. It is the lower bound for a per-window token sum: only runs that completed at or after it count toward the current window. ok is false when window is nil or now is outside the window — there is no current window to sum.\n\n```go\nfunc DefaultCRDClientBuilder(c *rest.Config) (apiextensionsclient.Interface, error)\n```\nDefaultCRDClientBuilder wraps apiextensionsclient.NewForConfig to satisfy CRDClientBuilder.\n\n```go\nfunc EffectiveTaskTypes(taskType string, taskTypes []string) []string\n```\nEffectiveTaskTypes computes the union of a singular taskType and a taskTypes list. The singular taskType is first in the result when non-empty. Duplicates are removed while preserving order. The result is the set an agent accepts.\n\n```go\nfunc EffectiveTriggerPhases(trigger *agentv1.Trigger) domain.TaskPhases\n```\nEffectiveTriggerPhases returns the phase allow-list a Config's trigger declares, falling back to DefaultTriggerPhases when the trigger is nil or its phase list is empty. It is the single definition of the effective set shared by the spawn gate and the liveness probe.\n\n```go\nfunc IsJobFailed(job *batchv1.Job) bool\n```\nIsJobFailed reports whether the Job carries a true JobFailed condition.\n\nConditions, not the pod counters, are the source of truth: an activeDeadlineSeconds kill sets this condition while leaving .status.failed and .status.active at zero. Any caller deciding whether a Job is still running must use this (see spawner.IsJobActive) — reading the counters alone reports a deadline-killed Job as active forever.\n\n```go\nfunc IsJobSucceeded(job *batchv1.Job) bool\n```\nIsJobSucceeded reports whether the Job carries a true JobComplete condition.\n\n```go\nfunc IsWithinRunWindow(now time.Time, window *agentv1.RunWindow) (bool, time.Time)\n```\nIsWithinRunWindow reports whether now falls inside the agent's run window, together with the next time the window opens. A nil window admits everything. A window whose times cannot be parsed admits nothing, so a typo fails closed rather than silently disabling the constraint.\n\n```go\nfunc NewResourceEventHandlerConfig(\n\tctx context.Context,\n\thandler EventHandlerConfig,\n) cache.ResourceEventHandler\n```\nNewResourceEventHandlerConfig adapts an EventHandlerConfig to the cache.ResourceEventHandler the informer expects.\n\n```go\nfunc NextRunWindowOpen(now time.Time, window *agentv1.RunWindow) time.Time\n```\nNextRunWindowOpen returns the first minute after now at which the window opens. The scan is bounded to eight days, which covers every weekly shape, so a malformed window cannot spin.\n\n```go\nfunc ReadGitRestGatewaySecret(\n\tctx context.Context,\n\tkubeClient kubernetes.Interface,\n\tnamespace libk8s.Namespace,\n\tsecretName string,\n) (string, error)\n```\nReadGitRestGatewaySecret returns the git-rest gateway secret value from the named K8s Secret, or \"\" when secretName is empty (gateway auth disabled). The value is read once at startup and held in memory only — it is never logged, never embedded in the image, and never in env (spec 005 Security; the env var GITREST\\_GATEWAY\\_SECRET references the secret by NAME, matching the JobKafkaClientCertSecret pattern). Returns an error when the Secret is missing, lacks the gateway-secret data key, or holds an empty value there, so a misconfigured deployment fails loudly at startup instead of silently sending no auth header. An empty secretName is the only way to disable gateway auth.\n\n```go\nfunc ReadVaultAPIGatewaySecret(\n\tctx context.Context,\n\tkubeClient kubernetes.Interface,\n\tnamespace libk8s.Namespace,\n\tsecretName string,\n) (string, error)\n```\nReadVaultAPIGatewaySecret returns the vault-api gateway secret value from the named K8s Secret, or \"\" when secretName is empty (gateway auth disabled).\n\nIt mirrors ReadGitRestGatewaySecret on purpose: the secret is referenced by NAME from env, read once at startup, and held in memory only — never logged, never embedded in the image, and never in env. A missing Secret, a missing data key or an empty value is an error, so a misconfigured deployment fails loudly at startup instead of silently sending no auth header and having every claim refused.\n\n```go\nfunc ResolveJobNamespace(\n\tctx context.Context,\n\texecutorNamespace libk8s.Namespace,\n\tjobNamespace string,\n) (libk8s.Namespace, error)\n```\nResolveJobNamespace returns the namespace in which a Config's Jobs must be created. An empty jobNamespace means the executor's own namespace, preserving the behaviour of every Config that does not set the field. A jobNamespace equal to the executor's own namespace is rejected: that would be an explicit opt-out of isolation, and no Config may author one.\n\n```go\nfunc ResolveServiceNamespace(\n\tctx context.Context,\n\texecutorNamespace libk8s.Namespace,\n\tserviceNamespace string,\n) (libk8s.Namespace, error)\n```\nResolveServiceNamespace returns the namespace in which a Config's service StatefulSet must be deployed. An empty serviceNamespace means the executor's own namespace. A value equal to the executor's own namespace is rejected: that would be an explicit opt-out of isolation.\n\n```go\nfunc SecondsUntilRunWindowClose(now time.Time, window *agentv1.RunWindow) (int32, bool)\n```\nSecondsUntilRunWindowClose returns how long the window stays open from now. The caller caps a Job's deadline with it so a run admitted near the end of the window is stopped when the window closes rather than running into business hours. ok is false when there is no window, or when the window never closes within the eight-day scan (a permanently open configuration).\n\n```go\nfunc TaskTypeInSet(taskType string, effectiveTypes []string) bool\n```\nTaskTypeInSet reports whether taskType is in the effectiveTypes set. Empty taskType never matches — strict semantics, no bypass for legacy tasks.\n\n## Types\n\n```go\ntype AgentConfiguration struct {\n\t// Assignee is the task frontmatter assignee value that routes to this agent.\n\tAssignee string\n\t// Type is how the executor runs this agent, from ConfigSpec.Type. Empty means\n\t// AgentTypeJob, so a Config predating the field behaves exactly as before. An\n\t// AgentTypeService agent is reconciled as a long-running workload rather than\n\t// spawned per task.\n\tType agentv1.AgentType\n\t// TaskType is the singular task_type value from ConfigSpec.TaskType.\n\t// Deprecated in favour of TaskTypes; stays functional.\n\tTaskType string\n\t// TaskTypes is the list of task_type values from ConfigSpec.TaskTypes.\n\t// Nil when the CRD only sets the singular TaskType field.\n\tTaskTypes []string\n\t// DefaultForTaskTypes is the list of task_type values from\n\t// ConfigSpec.DefaultForTaskTypes: the types this Config declares itself the\n\t// designated default for. Routing metadata, carried so a resolved\n\t// configuration reports the declaration it was picked by.\n\tDefaultForTaskTypes []string\n\t// Image is the container image base name (without tag). Tag is appended at runtime from branch.\n\tImage string\n\t// Env holds per-agent environment variables (e.g. API keys, config).\n\t// These are merged with shared env vars (TASK_CONTENT, TASK_ID, KAFKA_BROKERS, BRANCH)\n\t// when spawning the K8s Job.\n\tEnv map[string]string\n\t// VolumeClaim is the name of an existing PVC to mount into the container.\n\t// Empty means no volume mount.\n\tVolumeClaim string\n\t// VolumeMountPath is the container path where the PVC is mounted.\n\t// Required when VolumeClaim is set.\n\tVolumeMountPath string\n\t// ConfigMapName is the name of an existing ConfigMap to mount as files.\n\t// Empty means no ConfigMap mount.\n\tConfigMapName string\n\t// ConfigMapMountPath is the container path where the ConfigMap is mounted.\n\t// Required when ConfigMapName is set.\n\tConfigMapMountPath string\n\t// ConfigMapItems maps ConfigMap keys to file paths inside the mount.\n\t// Empty means the whole ConfigMap is mounted as-is.\n\tConfigMapItems []agentv1.ConfigMapItem\n\t// SecretName is the name of a K8s Secret to mount as envFrom on the container.\n\t// Empty means no secret is mounted.\n\tSecretName string\n\t// Resources declares optional resource requests and limits for the agent container.\n\t// Nil means \"do not set, keep the k8s builder default\".\n\tResources *agentv1.AgentResources\n\t// MaxConcurrentJobs caps how many Jobs this agent may run at once.\n\t// 0 means unlimited.\n\tMaxConcurrentJobs int\n\t// PriorityClassName is stamped on Job PodTemplates and on a service StatefulSet pod template.\n\tPriorityClassName string\n\t// NodeSelector is stamped on Job PodTemplates. Empty leaves scheduling unconstrained.\n\tNodeSelector map[string]string\n\t// Tolerations are stamped on Job PodTemplates. Empty adds none.\n\tTolerations []corev1.Toleration\n\t// JobNamespace is the namespace this Config's Jobs must be created in, from\n\t// ConfigSpec.JobNamespace. Empty means the executor's own namespace. Resolve\n\t// it with ResolveJobNamespace before use.\n\tJobNamespace string\n\t// ServiceNamespace is the namespace this Config's service StatefulSet must be\n\t// deployed in, from ConfigSpec.ServiceNamespace. Empty means the executor's\n\t// own namespace. Resolve it with ResolveServiceNamespace before use.\n\tServiceNamespace string\n\t// ImagePullSecret is the name of the K8s Secret used for image pulls.\n\t// Empty uses the cluster default (typically \"docker\").\n\tImagePullSecret string\n\t// Trigger declares the per-agent phase and status conditions under which the executor spawns a Job.\n\tTrigger *agentv1.Trigger\n\t// RerunOnLostClaim mirrors ConfigSpec.RerunOnLostClaim. After another\n\t// executor takes over this agent's expired claim, false parks the task at\n\t// phase human_review instead of re-dispatching it; nil means the Config did\n\t// not set the field and parks too. Resolve it with LostClaimAction.\n\tRerunOnLostClaim *bool\n\t// ZombieJobTimeoutSeconds mirrors ConfigSpec.ZombieJobTimeoutSeconds. The\n\t// spawner stamps this value onto Job.Spec.ActiveDeadlineSeconds; the sweeper\n\t// uses it as the elapsed-time threshold. nil means \"use the default\n\t// DefaultZombieJobTimeoutSeconds from the CRD types package\".\n\tZombieJobTimeoutSeconds *int32\n\t// RunWindow mirrors ConfigSpec.RunWindow. nil means no window: spawns are\n\t// admitted at any hour.\n\tRunWindow *agentv1.RunWindow\n\t// RunBudgetSeconds mirrors ConfigSpec.RunBudgetSeconds. 0 means no separate\n\t// budget; the zombie timeout is the only deadline.\n\tRunBudgetSeconds int32\n\t// TokenCeiling mirrors ConfigSpec.TokenCeiling. nil or 0 means no ceiling.\n\tTokenCeiling *int64\n}\n```\nAgentConfiguration defines the container image and environment for one agent type.\n\n```go\nfunc (a AgentConfiguration) EffectiveRunDeadlineSeconds() int32\n```\nEffectiveRunDeadlineSeconds returns the hard deadline stamped on a spawned Job: the run budget when it is set and stricter than the zombie timeout, otherwise the effective zombie timeout.\n\n```go\nfunc (a AgentConfiguration) EffectiveZombieJobTimeoutSeconds() int32\n```\nEffectiveZombieJobTimeoutSeconds returns the effective deadline in seconds: the configured value when non-nil, else agentv1.DefaultZombieJobTimeoutSeconds.\n\n```go\nfunc (a AgentConfiguration) LostClaimAction() agentv1.LostClaimAction\n```\nLostClaimAction maps RerunOnLostClaim to the action to take after another executor takes over this agent's expired claim. It delegates to the CRD type so the mapping has exactly one implementation.\n\n```go\ntype AgentConfigurations []AgentConfiguration\n```\nAgentConfigurations is a list of agent configurations.\n\n```go\nfunc (a AgentConfigurations) FindByAssignee(assignee string) (AgentConfiguration, bool)\n```\nFindByAssignee returns the configuration for the given assignee name. Returns the config and true if found, zero value and false otherwise.\n\n```go\nfunc (a AgentConfigurations) TaggedConfigurations(branch string) AgentConfigurations\n```\nTaggedConfigurations returns a new AgentConfigurations with the branch appended to each untagged image as a tag (e.g. \"registry/image\" + \":\" + \"dev\" → \"registry/image:dev\"). Images that already carry a tag or digest are left as-is (see appendBranchTag), so semver-pinned images are not double-tagged.\n\n```go\ntype CRDClientBuilder func(*rest.Config) (apiextensionsclient.Interface, error)\n```\nCRDClientBuilder constructs the apiextensions clientset from a rest.Config. Injected to allow fake clientsets in tests.\n\n```go\ntype ClaimClientFactory func() claim.ClaimClient\n```\nClaimClientFactory builds the typed vault-api claim client. It is called at most once, by the lease manager's construction, and only when CLAIM\\_MODE is shadow or on.\n\nIt is a separate factory from ClaimRefClientFactory rather than a second method on it because the two clients address different services with different credentials: the ref client still serves the redrive stores, which use git-rest refs as counters, while every lease is held through this one.\n\n```go\ntype ClaimMode string\n```\nClaimMode is the closed set of dispatch claim modes.\n\n```go\nconst (\n\t// ClaimModeOff constructs no claim client and preserves pre-claim dispatch.\n\tClaimModeOff ClaimMode = \"off\"\n\t// ClaimModeShadow takes claims but never blocks a dispatch on one.\n\tClaimModeShadow ClaimMode = \"shadow\"\n\t// ClaimModeOn makes a held claim a precondition of the Job.\n\tClaimModeOn ClaimMode = \"on\"\n)\n```\n\n```go\nfunc ParseClaimMode(ctx context.Context, value string, present bool) (ClaimMode, error)\n```\nParseClaimMode parses the CLAIM\\_MODE value. present reports whether the variable exists in the environment, which distinguishes an unset variable (off) from an explicitly empty one (invalid).\n\n```go\nfunc (m ClaimMode) TakesClaim() bool\n```\nTakesClaim reports whether this mode takes a claim, and so needs the claim transport: a ref client, its git-rest URL and its gateway secret.\n\nIt is an allow-list, not a check for off. A zero-value or otherwise unparsed mode reports false, so an unrecognised mode constructs no transport and reads no secret instead of failing open.\n\n```go\ntype ClaimRefClientFactory func() claim.ClaimRefClient\n```\nClaimRefClientFactory builds the git-rest claim ref client. It is called at most once per consumer of it, and only when CLAIM\\_MODE is shadow or on.\n\nIt lives in pkg rather than handler because both the spawn funnel (through handler) and the result publisher need it, and the publisher must not import handler. Each call returns a fresh client, so the publisher and the handler each build their own store over their own client.\n\n```go\ntype ClaimReleaser interface {\n\tReleaseTaskClaim(ctx context.Context, taskID lib.TaskIdentifier)\n\t// ReleaseTaskClaimAfterSuccess holds the claim until SuccessGracePeriod has\n\t// elapsed since completedAt, then releases it, and records the success at\n\t// phase in the shared claim store so the suppression survives a pod restart.\n\t// A failed Job must call ReleaseTaskClaim instead: a retry belongs to this\n\t// cluster and delaying its claim release would only delay the retry.\n\t//\n\t// phase is the phase the succeeded Job was spawned for, carried on the Job as\n\t// TaskPhaseAnnotationKey. The hold and the record are the same moment, so they\n\t// are written through one end point rather than a second parallel path.\n\tReleaseTaskClaimAfterSuccess(\n\t\tctx context.Context,\n\t\ttaskID lib.TaskIdentifier,\n\t\tphase string,\n\t\tcompletedAt time.Time,\n\t)\n}\n```\nClaimReleaser releases this executor's held claim for a task, if any. The task event handler implements it and the Job watcher is injected with it, so a terminal Job can release the claim taken before the Job was created.\n\n```go\ntype ConfigResolver interface {\n\tResolve(ctx context.Context, assignee string) (AgentConfiguration, error)\n\t// ResolveByTaskType looks up the single AgentConfiguration whose effective\n\t// task-type set ({Spec.TaskType} ∪ Spec.TaskTypes) contains taskType. It is\n\t// the recovery path's routing lookup for a task whose assignee was cleared:\n\t// the task's own task_type still identifies exactly one agent.\n\t//\n\t// When more than one Config declares taskType, a non-empty preferAssignee\n\t// narrows the matches to the ones Resolve would pick for that assignee\n\t// ({preferAssignee}-{vaultName} first, then the plain preferAssignee); a\n\t// single survivor is returned.\n\t//\n\t// When several Configs declare taskType and preferAssignee does not narrow\n\t// them to one, the single Config that names taskType in\n\t// Spec.DefaultForTaskTypes is returned instead. That is an explicit\n\t// declaration on the Config, not a guess: zero or several Configs declaring\n\t// it leave the ambiguity refusal in place.\n\t//\n\t// Returns ErrConfigNotFound when no Config declares taskType, and\n\t// ErrConfigAmbiguous when more than one does and neither preferAssignee nor\n\t// a unique designated default narrows them to exactly one.\n\tResolveByTaskType(\n\t\tctx context.Context,\n\t\ttaskType string,\n\t\tpreferAssignee string,\n\t) (AgentConfiguration, error)\n}\n```\nConfigResolver looks up the AgentConfiguration for an assignee, and — on the recovery path — for a task's task\\_type.\n\n```go\nfunc NewConfigResolver(\n\tprovider k8s.Provider[agentv1.Config],\n\tbranch base.Branch,\n\tvaultName string,\n) ConfigResolver\n```\nNewConfigResolver returns a ConfigResolver backed by the given typed store. The branch is captured here and appended as the image tag at resolution time. Resolutions are scoped to the given vault: each task's plain assignee is matched against the composed {assignee}-{vaultName} Config assignee, so per-vault Config CRs apply per executor instance. When no composed Config exists, Resolve falls back to the plain assignee, so the singular shared-topic executor (v0.6.x Config CRs without a vault suffix) keeps resolving on the v0.7+ line.\n\n```go\ntype CronScheduler interface {\n\tRun(ctx context.Context) error\n}\n```\nCronScheduler runs a cron expression on a schedule.\n\n```go\ntype DeadLetterPublisher interface {\n\t// Publish records msg, the message that failed, together with cause, the\n\t// error that proved it unprocessable.\n\tPublish(ctx context.Context, msg *sarama.ConsumerMessage, cause error) error\n}\n```\nDeadLetterPublisher records a task event the consumer can never process, so skipping it does not also erase the evidence of what was skipped.\n\nIt is the durable half of the permanent-skip path. The consumer returns nil after a successful Publish, which advances the offset past the message; a record that lives only in a sampled log line is not recoverable after the fact, which is exactly the gap SC2 closes.\n\n```go\nfunc NewKafkaDeadLetterPublisher(\n\tproducer libkafka.SyncProducer,\n\ttopic libkafka.Topic,\n) DeadLetterPublisher\n```\nNewKafkaDeadLetterPublisher returns a DeadLetterPublisher that writes the original message to a dead-letter topic. The message key is preserved so partition affinity is kept, and the source coordinates plus the error travel as record headers.\n\n```go\ntype EventHandlerConfig k8s.EventHandler[agentv1.Config]\n```\nEventHandlerConfig is the typed in-memory event handler / store for Config resources. Backed by github.com/bborbe/k8s generics.\n\n```go\nfunc NewEventHandlerConfig() EventHandlerConfig\n```\nNewEventHandlerConfig returns an empty EventHandlerConfig.\n\n```go\ntype JobWatcher interface {\n\t// Run starts the Job and Pod informers and blocks until ctx is cancelled.\n\tRun(ctx context.Context) error\n\t// HandleJob processes a single Job (invoked by the informer event handlers\n\t// and by unit tests directly, avoiding the need for a fake informer).\n\tHandleJob(ctx context.Context, job *batchv1.Job)\n\t// HandlePod processes a single Pod (invoked by the Pod informer event handler\n\t// and by unit tests directly).\n\tHandlePod(ctx context.Context, pod *corev1.Pod)\n\t// PodLister returns the Pod lister backed by namespace's informer cache, or\n\t// nil when that namespace is not watched or its cache has not synced. The\n\t// returned lister is safe for concurrent read access.\n\tPodLister(namespace libk8s.Namespace) corev1listers.PodLister\n}\n```\nJobWatcher watches batch/v1 Jobs and their Pods in the executor's namespace and in every namespace a Config names, and publishes synthetic failure results for terminal-state objects that belong to spawned tasks.\n\n```go\nfunc NewJobWatcher(\n\tkubeClient kubernetes.Interface,\n\tnamespace libk8s.Namespace,\n\tconfigProvider libk8s.Provider[agentv1.Config],\n\ttaskStore *TaskStore,\n\tpublisher ResultPublisher,\n\tclaimReleaser ClaimReleaser,\n\tcurrentDateTimeGetter libtime.CurrentDateTimeGetter,\n) JobWatcher\n```\nNewJobWatcher creates a JobWatcher. The executor namespace is watched unconditionally; the provider supplies the Configs whose resolved jobNamespace values extend that set.\n\n```go\ntype K8sConnector interface {\n\tSetupCustomResourceDefinition(ctx context.Context) error\n\tListen(\n\t\tctx context.Context,\n\t\tnamespace libk8s.Namespace,\n\t\thandler cache.ResourceEventHandler,\n\t) error\n}\n```\nK8sConnector installs the Config CRD and starts an informer.\n\n```go\nfunc NewK8sConnector(config *rest.Config, crdBuilder CRDClientBuilder) K8sConnector\n```\nNewK8sConnector returns a K8sConnector using the given rest config and builder. Production callers pass DefaultCRDClientBuilder as the builder.\n\n```go\ntype PodLogReader interface {\n\t// Tail returns the pod's trailing log text, bounded by logTailMaxLines and\n\t// logTailMaxBytes. It returns an error when the API refuses the read — the\n\t// pod is already garbage-collected, the caller lacks the pods/log grant, or\n\t// the API throttles — and the caller is expected to swallow that error: a\n\t// missing tail must never turn a delivered failure into an error.\n\tTail(ctx context.Context, namespace string, podName string) (string, error)\n}\n```\nPodLogReader reads the tail of one pod's log directly from the Kubernetes API. It takes a client and a namespace per call and holds no informer cache, so it can be constructed independently of the Job watcher.\n\n```go\nfunc NewPodLogReader(client kubernetes.Interface) PodLogReader\n```\nNewPodLogReader creates a PodLogReader backed by client. It reads the log subresource directly and therefore needs the pods/log RBAC grant; without it every call fails and the caller publishes the failure with no tail.\n\n```go\ntype ResultPublisher interface {\n\t// PublishSpawnNotification publishes spawn_notification, current_job,\n\t// job_started_at, and claude_session_id without touching any other\n\t// frontmatter keys.\n\tPublishSpawnNotification(\n\t\tctx context.Context,\n\t\ttask lib.Task,\n\t\tjobName string,\n\t\tsessionID string,\n\t) error\n\t// PublishFailure publishes a zombie failure: clears current_job and atomically\n\t// bumps trigger_count by 1 via a paired IncrementFrontmatterCommand. Leaves\n\t// phase, status, and assignee untouched — the escalation is the controller's\n\t// increment executor, which clears assignee once trigger_count reaches an\n\t// explicitly-set max_triggers, and an empty assignee is what surfaces the\n\t// record in the operator inbox.\n\t//\n\t// That cap is opt-in on the key being present: an absent max_triggers means\n\t// no cap, so a record without the key accrues trigger_count forever and its\n\t// assignee is never cleared. For the pod_crash_no_stdout class this method\n\t// therefore arms the cap by writing max_triggers=defaultMaxTriggers when the\n\t// key is absent — the class is otherwise unreachable, because a crash before\n\t// the first stdout write leaves nothing for the deliverer to act on. The\n\t// other seven classes keep their own escalation semantics and are untouched.\n\t//\n\t// applyTriggerCap (task/controller/pkg/result/result_writer.go) does NOT cover\n\t// this path, and reading it as though it did is what left the hole open: it\n\t// runs on the result-merge path only, while these writes take the atomic\n\t// frontmatter-command path (buildUpdateModifyFn), which never reaches it.\n\t//\n\t// pod is the failed Job's pod as observed by the caller, or nil when the\n\t// caller has no pod (the zombie sweeper, or an unresolvable pod). It feeds\n\t// two consumers: the never-scheduled deadline class at the arm gate, and the\n\t// log tail. A nil pod never arms and yields no tail, and the pod itself is\n\t// never written to the record.\n\t//\n\t// Idempotent per current_job via a TTL'd LRU; concurrent classifications for\n\t// the same job emit one event.\n\tPublishFailure(\n\t\tctx context.Context,\n\t\ttask lib.Task,\n\t\tjobName string,\n\t\treason string,\n\t\tpod *corev1.Pod,\n\t) error\n\t// PublishStoreMissFailure is PublishFailure for a Job whose task has already\n\t// left the executor's in-memory store, so the record carries no failure of\n\t// its own and no other path can report one. It writes the same frontmatter\n\t// and the same `trigger_count` increment, plus a note stating that the record\n\t// was already terminal, that the Job crashed before producing output, that\n\t// the entry exists because the crash would otherwise be silent, and that the\n\t// status is unchanged — the last one because a failure section under a\n\t// terminal status otherwise reads as a status change that never happened.\n\tPublishStoreMissFailure(ctx context.Context, task lib.Task, jobName string, reason string) error\n\t// PublishClearCurrentJob clears current_job in the vault task frontmatter\n\t// (writes \"\" only — no body section, no trigger_count bump, no status/phase\n\t// touch). Used on the job-success path, where the agent already published its\n\t// real result and the task is about to be evicted from the TaskStore: without\n\t// this clear, a succeeded job leaves current_job/job_started_at set forever\n\t// (the zombie sweeper is blind to it because the task left Snapshot()). The\n\t// write is idempotent (empty → empty is a no-op visually) and deduped per\n\t// jobName by the same TTL'd LRU as PublishFailure, so the informer's repeated\n\t// terminal re-deliveries do not spam Kafka.\n\tPublishClearCurrentJob(ctx context.Context, task lib.Task, jobName string) error\n\t// PublishIncrementTriggerCount sends an IncrementFrontmatterCommand that atomically\n\t// increments trigger_count by 1. Must complete before SpawnJob is called.\n\tPublishIncrementTriggerCount(ctx context.Context, task lib.Task) error\n\t// PublishSetTriggerScope sends an UpdateFrontmatterCommand that records a\n\t// trigger_scope and sets trigger_count to count, in one atomic write. Called\n\t// instead of PublishIncrementTriggerCount in the two cases where the scope\n\t// itself has to be written:\n\t//\n\t//   - the scope CHANGED (count 1): a re-dispatch against a new phase or a new\n\t//     ref starts from a fresh budget, counting the spawn about to happen.\n\t//   - the scope was ABSENT (count = existing trigger_count + 1): the task\n\t//     predates the field and adopts the current scope WITHOUT a budget reset.\n\t//     Absent must not be treated as changed — every task in flight today has no\n\t//     trigger_scope, so resetting on absence would hand each of them a free\n\t//     budget on the first event after deploy, including one already at cap.\n\t//\n\t// This is an UpdateFrontmatterCommand rather than a result publish on purpose.\n\t// trigger_count is controller-owned: the result writer's ownership guard\n\t// (MergeFrontmatter in task/controller) discards any incoming counter value, so\n\t// a reset routed through a result payload would be silently dropped. The atomic\n\t// frontmatter commands take a different path (buildUpdateModifyFn), which applies\n\t// Updates directly to the on-disk frontmatter — an explicit, intentional write\n\t// rather than a stale spawn-time snapshot.\n\tPublishSetTriggerScope(ctx context.Context, task lib.Task, scope string, count int) error\n\t// PublishTriggerBudgetRefusal writes a scoped trigger-budget refusal onto the\n\t// task record: the four trigger_refusal_* keys (count, max, scope, at) and a\n\t// \"## Trigger Budget\" body section, and no other key. It never writes\n\t// \"## Failure\", so the older cause a record may already carry stays visible;\n\t// taskcmd.BodySection replaces a section with the same heading, which is why\n\t// this path must not reuse that heading.\n\t//\n\t// The write is deduped per task AND refusal triple (scope, count, max) through\n\t// the same TTL'd LRU as PublishAbort. Keying on the triple rather than the\n\t// task alone is load-bearing: a changed scope is a changed refusal and must\n\t// never be suppressed. The dedupe is needed because the handler reads an\n\t// informer snapshot that does not yet show a write the controller has not\n\t// applied, so without it the identical refusal would be re-published every\n\t// tick.\n\tPublishTriggerBudgetRefusal(\n\t\tctx context.Context,\n\t\ttask lib.Task,\n\t\tscope string,\n\t\tcount int,\n\t\tmaxTriggers int,\n\t) error\n\t// PublishTypeMismatchFailure publishes a synthetic failure when the task's task_type\n\t// is not in the agent's effective type set. Clears assignee and current_job so the\n\t// task surfaces in the operator inbox via assignee==\"\" filter. Does not bump\n\t// trigger_count.\n\tPublishTypeMismatchFailure(ctx context.Context, task lib.Task, reason string) error\n\t// PublishRestoreAssignee writes the resolved configuration's assignee back\n\t// onto a task whose routing value was cleared, so the controller applies the\n\t// write and the resulting hash change re-publishes TaskUpdated — the event\n\t// the normal spawn path already consumes. Writes the \"assignee\" key and\n\t// nothing else.\n\tPublishRestoreAssignee(ctx context.Context, task lib.Task, assignee string) error\n\t// PublishParkLostClaim writes phase \"human_review\" onto a task whose claim\n\t// another executor took over and whose Config says not to re-run it. It\n\t// writes the \"phase\" key in the frontmatter and, in one command, a \"##\n\t// Parked\" body section naming the reason and the claim evidence. status,\n\t// assignee and the counters stay as they are. human_review is already in the\n\t// executor's terminal-phase set, so a parked task is never re-spawned and\n\t// needs no second guard.\n\t//\n\t// reason is the path's token; claimKey and previousHolder are the lost-claim\n\t// path's evidence and are empty on the succeeded path, whose section carries\n\t// the reason line only.\n\tPublishParkLostClaim(\n\t\tctx context.Context,\n\t\ttask lib.Task,\n\t\treason string,\n\t\tclaimKey string,\n\t\tpreviousHolder string,\n\t) error\n\t// PublishParkSucceeded closes a task whose Job succeeded but whose phase\n\t// never moved — the agent exited 0 without advancing it, so nothing will\n\t// move it again. It writes status completed and phase done, plus a\n\t// \"## Parked\" body section carrying the reason line only: the succeeded\n\t// path has no claim key or previous holder. done is already in the\n\t// executor's terminal-phase set, so the reconcile pass stops re-driving it.\n\t// Without this write the task is eligible on every pass and re-spawned\n\t// forever; with human_review instead, a finished record never terminalises\n\t// and has to be closed by hand.\n\tPublishParkSucceeded(ctx context.Context, task lib.Task) error\n\t// PublishParkRedriveCap escalates a task whose Job succeeded but whose\n\t// result never reported done, after its re-drive budget was spent. It writes\n\t// status hold and phase planning plus a \"## Parked\" body section, and\n\t// deliberately writes no terminal outcome: the work did not finish, so\n\t// closing it would report failed work as completed. status hold is the\n\t// escalation channel — it leaves the in_progress population while staying\n\t// open for a human — and the phase moves to planning because vault-cli's\n\t// lint flags hold alongside an active phase. The reason line names the\n\t// non-done last_result_status, so the section is distinguishable from the\n\t// succeeded park's bare token.\n\tPublishParkRedriveCap(ctx context.Context, task lib.Task) error\n\t// PublishAbort closes a record the consecutive-re-drive cap has decided to\n\t// stop driving. It writes status aborted plus the close-out pair vault-cli\n\t// requires (aborted_reason and gate_successor) and clears current_job. It\n\t// writes those four keys and no others. Idempotent per task: an already\n\t// aborted task is left alone, and a publish is deduped through the same\n\t// TTL'd LRU as PublishFailure. streak is the cap's count at the time of the\n\t// decision, carried for the log line only — the reason store's ref count is\n\t// deliberately not the streak count.\n\tPublishAbort(ctx context.Context, task lib.Task, reason string, streak int) error\n\t// PublishQueueEntry records when a task first started waiting behind the\n\t// concurrency cap. It publishes queued_at and touches no other key.\n\tPublishQueueEntry(ctx context.Context, task lib.Task, queuedAt string) error\n\t// PublishRaw publishes a raw payload for testing error paths.\n\tPublishRaw(ctx context.Context, operation base.CommandOperation, payload interface{}) error\n}\n```\nResultPublisher publishes agent-task-v1-request commands to Kafka so the controller writes them to the vault task file.\n\n```go\nfunc NewResultPublisher(\n\tsyncProducer libkafka.SyncProducer,\n\ttopicPrefix base.TopicPrefix,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n\tclaimRefClientFactory ClaimRefClientFactory,\n\tpodLogReader PodLogReader,\n) ResultPublisher\n```\nNewResultPublisher creates a ResultPublisher. claimRefClientFactory may be nil — claim mode off, or a mode that never built a client — in which case no failure reason is recorded and every publish behaves exactly as before.\n\npodLogReader may be nil, in which case no log tail is captured and every failure section is composed exactly as it was before the tail feature.\n\n```go\ntype SucceededJob struct {\n\tPhase       string\n\tCompletedAt time.Time\n}\n```\nSucceededJob is the latest successful Job of a task: the phase it was spawned for (empty for a Job spawned before the phase annotation existed) and when it completed.\n\n```go\ntype TaskStore struct {\n\t// contains filtered or unexported fields\n}\n```\nTaskStore is a thread-safe map from TaskIdentifier to Task. It is populated when the executor spawns a Job and consumed by the job informer when publishing synthetic failure results.\n\nIt also remembers when each task's latest Job succeeded. That record outlives the task entry (which the watcher evicts on success) so the spawn path can tell \"a result is in flight to the vault\" from \"the agent never ran\".\n\n```go\nfunc NewTaskStore() *TaskStore\n```\nNewTaskStore creates an empty TaskStore.\n\n```go\nfunc (s *TaskStore) Delete(id lib.TaskIdentifier)\n```\nDelete removes the task for the given identifier (called on job termination).\n\n```go\nfunc (s *TaskStore) DeleteIfCurrentJob(id lib.TaskIdentifier, jobName string) bool\n```\nDeleteIfCurrentJob removes the entry only while it still names jobName, and reports whether it did.\n\nA caller that decides an entry is stale has read it, done I/O (a cluster lookup), and only then deletes. In that window a spawn can store a NEW entry for a new Job; an unconditional delete would drop it, leaving that Job unclaimed and invisible to the release path — the duplicate this whole mechanism exists to prevent. Comparing the Job name closes that window.\n\n```go\nfunc (s *TaskStore) LastSucceeded(id lib.TaskIdentifier) (SucceededJob, bool)\n```\nLastSucceeded returns the task's latest successful Job, if one is recorded.\n\n```go\nfunc (s *TaskStore) LatestParkPublishedAt(id lib.TaskIdentifier) (time.Time, bool)\n```\nLatestParkPublishedAt returns when the task's most recent park went out, regardless of which success it acted on, and whether one is recorded.\n\nMarkParkPublished keeps one record per task, so this is that record's publish time. The completion-keyed ParkPublishedAt stays for the branch that must match a specific success; this answers the grace question, which is about the park's age, not its subject.\n\n```go\nfunc (s *TaskStore) Load(id lib.TaskIdentifier) (lib.Task, bool)\n```\nLoad retrieves the task for the given identifier.\n\n```go\nfunc (s *TaskStore) MarkParkPublished(\n\tid lib.TaskIdentifier,\n\tcompletedAt time.Time,\n\tpublishedAt time.Time,\n)\n```\nMarkParkPublished records that a park for the success that completed at completedAt went out at publishedAt.\n\nThe publish time is what the caller needs, not just the fact: the phase only becomes human\\_review once the controller applies the write, so between the publish and that write-back the task still reads the phase it succeeded at. A caller that saw only \"a park was published\" could not tell that window apart from an operator re-arming the task to the same phase — and treating the former as a re-arm re-spawns the very work the park exists to stop.\n\nKeyed by completion time because the Job informer re-stamps the identical success record on every resync for the Job's whole TTL; a deletion-based marker would be undone within minutes.\n\n```go\nfunc (s *TaskStore) MarkSucceeded(id lib.TaskIdentifier, phase string, at time.Time)\n```\nMarkSucceeded records that a Job for the task, spawned for the given phase, completed successfully at the given time. Only a later completion replaces the record, so the informer's periodic re-delivery of an old terminal Job cannot move it.\n\n```go\nfunc (s *TaskStore) ParkPublishedAt(\n\tid lib.TaskIdentifier,\n\tcompletedAt time.Time,\n) (time.Time, bool)\n```\nParkPublishedAt returns when the park for the success that completed at completedAt went out, and whether such a park is recorded.\n\n```go\nfunc (s *TaskStore) PruneSucceededBefore(cutoff time.Time)\n```\nPruneSucceededBefore drops success records that completed before the cutoff, bounding the map to the tasks whose result may still be in flight.\n\n```go\nfunc (s *TaskStore) Snapshot() map[lib.TaskIdentifier]lib.Task\n```\nSnapshot returns a shallow copy of the current task map for read-only iteration. Safe to call concurrently with Store/Delete; the returned map is owned by the caller.\n\n```go\nfunc (s *TaskStore) Store(id lib.TaskIdentifier, task lib.Task)\n```\nStore saves the task for the given identifier (called on job spawn).\n\n```go\ntype ZombieReason string\n```\nZombieReason is the closed set of machine-readable reason strings emitted in the ## Failure body section. Operators grep on these values to triage. OOM kills use the dedicated pod\\_oom\\_killed value so operators can grep for OOM specifically; other non-zero pod terminations fall back to the generic pod\\_crash\\_no\\_stdout. Adding a new value requires updating this list and the documentation; renaming or removing a value is a breaking change to the on-disk task body contract.\n\n```go\nconst (\n\tZombieReasonImagePullBackOff  ZombieReason = \"image_pull_backoff\"\n\tZombieReasonPodEvicted        ZombieReason = \"pod_evicted\"\n\tZombieReasonDeadlineExceeded  ZombieReason = \"deadline_exceeded\"\n\tZombieReasonPodNotScheduled   ZombieReason = \"pod_not_scheduled\"\n\tZombieReasonPodCrashNoStdout  ZombieReason = \"pod_crash_no_stdout\"\n\tZombieReasonExecutorWatchLost ZombieReason = \"executor_watch_lost\"\n\tZombieReasonTypeMismatch      ZombieReason = \"type_mismatch\"\n\tZombieReasonPodOOMKilled      ZombieReason = \"pod_oom_killed\"\n)\n```\nEvery new ZombieReason must be added to this block AND to the ParseZombieReason table in zombie\\_reason\\_test.go. The per-value String() specs do not cover the parser.\n\n```go\nfunc JobFailureReason(job *batchv1.Job) ZombieReason\n```\nJobFailureReason maps a failed Job's conditions to a ZombieReason. Returns ZombieReasonDeadlineExceeded when a Failed condition has Reason \"DeadlineExceeded\" (the kubelet killed the pod for running past activeDeadlineSeconds). Returns the generic pod-failure reason ZombieReasonPodCrashNoStdout for \"BackoffLimitExceeded\" (the Job exhausted its retry backoff limit — a distinct reason from a deadline kill; HandleJob resolves the pod's terminated reason + exit code and surfaces them in the published reason) and for any other Failed condition (the pod terminated non-zero and no AgentResult was observed; the Job-condition informer only fires AFTER terminal state, so absence of an AgentResult is implicit at this point).\n\n```go\nfunc ParseZombieReason(s string) (ZombieReason, bool)\n```\nParseZombieReason returns the vocabulary value s names, and false when it names none. It matches up to the first space, so the formatted form produced by backoffFailureReason — \"pod\\_oom\\_killed (OOMKilled/137)\" — parses to ZombieReasonPodOOMKilled. A Kubernetes JobFailed condition reason — published as \"BackoffLimitExceeded (pod-unresolved)\" or \"JobFailed (Error/137)\" — parses through jobFailedConditionAliases to the class it belongs to. Anything else, including the empty string, returns false.\n\nThe formatted string is never persisted: its spaces and parentheses are not valid claim key segments. Callers store the parsed value, or \"unknown\" when this returns false.\n\n```go\nfunc (r ZombieReason) String() string\n```\nString returns the reason as a string (for use with PublishFailure).\n\n```go\ntype ZombieSweeper interface {\n\t// Run blocks until ctx is cancelled. Each tick (interval sourced from the\n\t// first non-nil ConfigSpec.ZombieSweeperIntervalSeconds across the resolver's\n\t// configs, else DefaultZombieSweeperIntervalSeconds) it calls SweepOnce.\n\tRun(ctx context.Context) error\n\t// SweepOnce performs a single sweep pass. Exposed for unit tests so they\n\t// do not have to manage tickers. Returns an error only on context\n\t// cancellation paths; per-task classification errors are logged.\n\tSweepOnce(ctx context.Context) error\n}\n```\nZombieSweeper is a background goroutine that periodically classifies stuck tasks as zombies and emits failure events. It is the safety net for the informer-driven paths in JobWatcher (which handle the cases k8s notifies us about). The sweeper handles: pods unschedulable beyond a grace window, executor restart losing watch on a Job, and any deadline path the informer misses (Job-condition deferred indefinitely, informer cache drift).\n\n```go\nfunc NewZombieSweeper(\n\tjobWatcher JobWatcher,\n\tnamespace libk8s.Namespace,\n\ttaskStore *TaskStore,\n\tpublisher ResultPublisher,\n\tconfigProvider EventHandlerConfig,\n\tcurrentDateTime libtime.CurrentDateTimeGetter,\n) ZombieSweeper\n```\nNewZombieSweeper creates a ZombieSweeper. The JobWatcher is held by reference (not its lister) because a namespace's lister is only populated after that namespace's cache syncs; service.Run starts all components concurrently, so extracting a lister at wiring time would capture nil. SweepOnce resolves each task's lister from the namespace its Job lives in and skips only that task when the namespace's cache is not yet ready.\n\n","path":"github.com/bborbe/agent-task-executor/pkg","name":"pkg","synopsis":"","isRedistributable":true}
