reliant-labs/forge/workers

Claude Code and agent skill by reliant-labs/forge

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

Background workers — adding, implementing, and testing workers (including cron-scheduled).

Install

npx vskill@latest install reliant-labs/forge/workers

SKILL.md

The same SKILL.md was published earlier as reliant-labs/forge/workers.

Background Workers

Workers are long-running background processes that don't serve HTTP but participate in the single-binary lifecycle with the same typed dependency injection and graceful shutdown as services. They live under internal/workers/<name>/ — the workers/ role subtree is nested under internal/, never a top-level workers/ directory.

Naming

Worker names canonicalize to lowercase snake_case: hyphens become underscores and PascalCase/camelCase boundaries split (email-sender → email_sender, EmailSender → email_sender, calibrator_refit stays calibrator_refit). The canonical form is what appears on disk, in the Go package decl, and in the scaffolded Name() (the identifier in log lines, and a cron worker's tick-claim key). forge.yaml records no workers: forge discovers each one from internal/workers/<name>/.

  • forge scaffold worker calibrator_refit → directory internal/workers/calibrator_refit/, package calibrator_refit.
  • forge scaffold worker email-sender → directory internal/workers/email_sender/, package email_sender.

(A worker scaffolded before this rule returned a kebab-case Name(); it is yours, so keep it or change it. For a cron worker, changing it starts a fresh claim history.)

Migrating from a non-forge codebase: rename existing worker directories to the canonical snake_case leaf under internal/workers/ before running forge generate: the directory is what forge discovers the worker by.

Adding a Worker

bash
forge scaffold worker <name>
forge scaffold worker <name> --kind cron --schedule "*/5 * * * *"

This creates:

  • internal/workers/<name>/worker.go — Worker implementation with Start(ctx) / Stop(ctx)
  • internal/workers/<name>/worker_test.go — Basic lifecycle test
  • Its constructor method in internal/app/compose.go, func (g *Graph) new<Name>() (*<name>.Worker, error): the next forge generate adds it when it discovers the worker. The default server root supervises every worker nothing else depends on, so there is nothing to append and nothing to register. forge.yaml is not touched.

When you add a field to the worker's Deps, forge adds the key to its constructor method; a field another node produces is resolved by type, and the values stay yours — see Wiring below.

A pre-graph project (an owned Infra + NewComponents composition) gets the worker's construction in NewComponents and its accessor in internal/app/lifecycle.go WorkerList instead, reconciled the same way, until forge fix composition-graph moves it to the graph.

Worker Lifecycle

Every worker implements the same contract:

go
func (w *Worker) Name() string { return "email_sender" }
// Start runs the cycle loop until ctx is cancelled. The supervisor
// cancels ctx the moment graceful shutdown begins.
func (w *Worker) Start(ctx context.Context) error {
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil // graceful shutdown — return promptly
case <-ticker.C:
if err := w.runOnce(ctx); err != nil {
w.deps.Logger.Error("worker cycle failed", "error", err)
}
}
}
}
// runOnce is a single work cycle. Pass ctx into every context-aware
// call so a long cycle observes shutdown mid-flight.
func (w *Worker) runOnce(ctx context.Context) error { /* ... */ return nil }
// Stop is called during graceful shutdown, after the loop returned.
func (w *Worker) Stop(ctx context.Context) error {
w.deps.Logger.Info("worker stopping", "worker", w.Name())
return nil
}

Key contract: Start must block until ctx is cancelled, then return promptly — the supervisor waits for it before continuing shutdown. Stop is called after cancellation with a deadline context for cleanup. Always thread ctx into per-cycle work (DB queries, HTTP calls, adapters) so in-flight cycles honor shutdown instead of running to completion.

A worker may also implement serverkit's optional ContextWorker extension — RunContext(ctx context.Context) error — which the supervisor prefers over Start when present (legacy Start workers are unaffected).

Common Patterns

Queue Consumer
go
func (w *Worker) Start(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
default:
msg, err := w.deps.Queue.Receive(ctx)
if err != nil {
time.Sleep(time.Second)
continue
}
w.process(ctx, msg)
}
}
}
Cron-Scheduled Worker

Use --kind cron with a --schedule (standard cron expression) to scaffold a worker that runs on a schedule using forge/pkg/cronkit:

bash
forge scaffold worker cleanup --kind cron --schedule "0 */6 * * *"

The generated worker has a Run(ctx context.Context) error method for your job logic. Start blocks in cronkit.Run until its context is cancelled, then waits for an in-flight tick (whose ctx is cancelled too) — same lifecycle as a regular worker. Each tick is a trace of its own (cron.<name>.tick); a returned error is logged and a panic recovered, so one bad tick never stops the schedule.

go
func (w *Worker) Run(ctx context.Context) error {
// Your scheduled job logic here. Plumb ctx through every
// context-aware downstream call so shutdown is observed.
at, _ := cronkit.TickTime(ctx) // the scheduled time, identical on every replica
return w.deps.Store.SweepBefore(ctx, at)
}

Each tick fires on ONE replica, by default. A cron worker runs inside a long-running workload (the hosted api workload, not a Kubernetes CronJob), so every replica computes the same schedule. Before running a tick, cronkit claims it: an INSERT … ON CONFLICT DO NOTHING of (worker name, scheduled tick time) into the forge_cron_ticks table in the app's Postgres. The replica whose insert lands runs the tick; every other replica skips it (a DEBUG log, and forge_cron_ticks_total{outcome="skipped"}). The table is bookkeeping, like the migrator's own: cronkit creates it on first use and prunes rows older than a day. In the scaffold that is:

go
// Deps
// forge:optional-dep
DB orm.Context // resolved to the ORM by type; nil when the app has no database
// Start
return cronkit.Run(ctx, cronkit.Options{
Name: w.Name(), // the claim key: renaming the worker resets its history
Schedule: Schedule,
PerReplica: PerReplica,
Claims: cronkit.Postgres(w.deps.DB),
Logger: w.deps.Logger,
}, w.Run)

What the claim guarantees, and what it does not:

  • At most once per tick. The claim is taken before Run, so a replica that crashes mid-tick loses that tick (cron semantics: no catch-up). A claim that fails (database down) skips the tick on that replica, logs at ERROR and counts outcome="claim_error"; it never runs unclaimed.
  • Ticks on one replica never overlap: a tick that outlives its period skips the ticks it covered (WARN). A later tick can still start on another replica while a slow one runs here; if Run must never overlap itself, hold a forge/pkg/lease lease inside it.
  • `@every <d>` is aligned to multiples of d, so replicas that started at different moments share tick times (robfig/cron counts it from process start).
  • No database, no claims. A project without db/migrations scaffolds no DB field, and an app booted without DATABASE_URL hands cronkit a nil ORM. Either way every replica fires, as before, and Start logs a WARN at boot (cron worker started WITHOUT tick claims).

Opting out. A job meant to run on every pod (refreshing an in-process cache, sweeping a local temp dir) declares it beside the schedule; claims are then never consulted:

go
// PerReplica: every tick runs on every replica.
const PerReplica = true

forge_cron_ticks_total{worker, outcome} counts every tick each replica saw: ran, failed (Run returned an error or panicked), skipped (claimed elsewhere), claim_error. Summed over replicas, ran + failed is the number of ticks that executed.

The schedule is not recorded anywhere outside the code. The Schedule const the cron template emits IS the declaration — discovery reads it back off internal/workers/<name>/worker.go to classify the worker as cron and to carry the expression into the deploy manifests:

go
// Schedule is the cron expression that controls how often Run executes.
const Schedule = "0 */6 * * *"
Choosing: a cron worker or a kind = "cron" workload

Both run on a schedule, and both run on Reliant hosting. They differ in where each tick runs:

cron worker (forge scaffold worker --kind cron)kind = "cron" workload (a Kubernetes CronJob)
Runs inthe long-running server process (hosted _api), beside the servicesa pod of its own per run, which exits when the run does
Costs when idlenothing extra: the process is up anywaynothing: no pod between runs
Per tickno start-up; claimed in Postgres so it fires on one replicaa fresh pod: scheduling, a VM boot and an image pull, billed per second of the run
Resources and limitsshares the server'sits own resources, and a run time limit (activeDeadlineSeconds)
Best forfrequent, light ticks in an app that already has a serverheavy, infrequent batch work (reports, exports, backfills)

Declare a CronJob in deploy/kcl/workloads.k (kind = "cron", schedule, and args for the command one run executes). On hosting it runs in the env's own namespace, with the bounds deploy/hosting lists (UTC unless timeZone says otherwise, runs never overlap, a run limit of 1 hour by default and 24 hours at most). Hosted cron is switched on per env by the control plane, so until the env's control plane admits it a deploy is refused naming the reason; a cron worker runs hosted everywhere.

Simple Periodic (no cron)

For basic intervals without cron expressions, use a plain worker with a ticker:

go
func (w *Worker) Start(ctx context.Context) error {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return nil
case <-ticker.C:
w.runBatchJob(ctx)
}
}
}

Wiring

A worker's Deps are interface-typed fields filled by type in the composition graph (internal/app/compose.go), not by string-matched field names and not by a generated wire_gen.go. forge writes the worker's constructor method when it first discovers the worker, and adds a key when its Deps gains a field; the value expressions are yours. Each value is another node's memoized accessor (g.QueueClient(), a component or a provider func's value from the owned internal/app/providers.go) or a graph input (g.Cfg, g.Log):

go
type Deps struct {
Logger *slog.Logger
Cfg *config.CleanupConfig // scalars travel as one typed config block, not naked fields
Queue queue.Client // an interface — the default fill is the real in-process impl
}
// in internal/app/compose.go (yours; generate adds missing methods and Deps keys, never touches a value)
func (g *Graph) newCleanup() (*cleanup.Worker, error) {
return cleanup.New(cleanup.Deps{
Logger: g.Log, // a graph input
Cfg: g.Cfg.Cleanup,
Queue: g.QueueClient(), // another node's accessor, resolved BY TYPE
}), nil
}

A root selects what a process builds and supervises. With no //forge:root declared, the generated Server root runs every runnable node nothing depends on (the API listener, every worker, every operator), which is what <bin> server runs. To run a worker as a process of its own, declare a root that names it and deploy that root (load architecture, "Roots and commands"):

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
0

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/reliant-labs/forge/workers/badge)](https://verified-skill.com/skills/reliant-labs/forge/workers)

Something wrong with this skill or its page? Tell us.