npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

assignment-user-matcher

v1.23.0

Published

[![npm version](https://badge.fury.io/js/assignment-user-matcher.svg)](https://badge.fury.io/js/assignment-user-matcher) [![CI Pipeline](https://github.com/ViljarVoidula/assignment-user-matcher/actions/workflows/npm-publish.yml/badge.svg)](https://github.

Readme

assignment-user-matcher: Lightning-Fast, Tag-Based User & Assignment Matching

npm version CI Pipeline 5xer Cloud

Tired of inefficiently assigning tasks or struggling to connect the right users with the right work? assignment-user-matcher is a specialized Node.js library designed for high-performance, near real-time matching of a smaller pool of users to a large volume of assignments, primarily based on shared tags and priority.

It leverages the speed and efficiency of Redis to deliver a robust solution perfect for scenarios like call centers, customer support queues, back-office operations, and more.

☁️ Don't want to run your own Redis?

5xer Cloud offers this matching engine as a fully managed service — no infrastructure, no maintenance sweeps, no Redis ops. On top of that, you get a polished no-code UI: a mobile-friendly PWA where workers see their assignments, accept, and complete work from anywhere — no client to install, no code to write.

Sign up at 5xer.com → — getting started is free.

The Challenge: Efficiently Connecting Users to Work

In many applications, from customer service platforms to internal task management systems, the core challenge remains the same: how do you quickly and accurately assign incoming work (assignments) to the best available person (user)? This becomes particularly complex when dealing with:

  • Large volumes of incoming assignments: Tasks can pile up quickly, demanding immediate attention.
  • Real-time requirements: Users expect instant responses, and assignments need prompt handling.
  • Varying skill sets and priorities: Not all users are equipped for all tasks, and some assignments are more critical than others.

Traditional matching systems can become bottlenecks, leading to delays, suboptimal pairings, and frustrated users or customers.

Introducing assignment-user-matcher: Your Solution for Smart Task Distribution

assignment-user-matcher tackles these challenges head-on by providing a specialized engine optimized for a common pattern: a relatively small, active set of users (like support agents or back-office staff) processing a continuous, large stream of assignments.

Key Features:

  • Tag-Based Matching: Intelligently connect users and assignments based on an intersection of descriptive tags (e.g., skills, language, department).
  • Priority-Aware: Ensure that high-priority assignments are surfaced and processed first.
  • Redis-Powered: Utilizes Redis for its in-memory data structures, enabling blazing-fast lookups and operations.
  • Optimized for Specific Scenarios: Excels where a smaller group of users handles a large number of assignments.
  • User Backlog Management: Prevents users from being overwhelmed by limiting the number of assignments they can be tentatively matched with.

Why assignment-user-matcher?

  • 🚀 Speed: Designed for near real-time performance, ensuring assignments are matched and delivered swiftly.
  • 🎯 Accuracy: Improves the quality of matches by considering relevant tags and priorities.
  • ⚙️ Efficiency: Optimizes resource allocation, ensuring users are working on the most appropriate and urgent tasks.
  • 😌 Improved Experience: Leads to faster response times for customers and a more streamlined workflow for users.
  • 💡 Scalable (for its niche): Handles a large throughput of assignments efficiently.

Core Concepts: How It Works

assignment-user-matcher operates on a few key principles:

  1. Users and Assignments Have Tags:

    • Users: Each user is defined by an ID and a set of tags representing their skills, capabilities, or any other relevant attributes (e.g., ['english', 'billing_support', 'tier_1']).
    • Assignments: Each assignment has an ID, tags describing its requirements (e.g., ['english', 'billing_inquiry']), and a createdAt timestamp (or a custom priority score) to determine its urgency.
  2. Matching via Tag Intersection: The core matching logic finds users whose tags have a common intersection with an assignment's tags.

When using routingWeights with the built-in matcher:

  • Only positive weights (> 0) make assignments eligible.
  • Weight 0 is a hard veto (exact tag or suffix wildcard like lang:*).
  • Wildcards are suffix-only (prefix*). Patterns like skill:*:node are not treated as wildcards.
  • If a user has routingWeights but no positive entries, assignments stay queued.

Hard veto configuration example:

await assignmentMatcher.addUser({
    id: 'agent_1',
    tags: [],
    routingWeights: {
        'support:*': 100, // eligible
        'lang:*': 0, // hard veto for all language-tagged assignments
        default: 0, // hard veto for default matching fallback
    },
});

Note: usingDefaultMatchScore is an internal implementation detail and is not a public option. Configure hard veto behavior only through routingWeights values.

Assignments can also veto specific users from their side: setting vetoedUsers: ['user_1'] on an assignment guarantees those users are never matched to it, no matter how well their tags, weights, or other criteria fit (this also overrides workflow targeting).

  1. Prioritization Engine: Assignments are typically processed in the order they are received or by a custom prioritization function you can provide. This ensures that older or more critical assignments get attention first. The library aims to match the highest priority assignments to available, suitable users.

  2. Redis as the Backbone: Redis is used to store user availability, assignment details, and manage the matching process. Its speed is crucial for the near real-time performance of the library. Users are maintained in sorted sets based on their backlog size and last activity, ensuring fair and efficient distribution.

  3. User Backlog (maxUserBacklogSize): To prevent any single user from being assigned too many tasks at once (even if they are a match), assignment-user-matcher maintains a backlog for each user. New assignments are only matched if a user's backlog is below this threshold.

Real-World Use Cases

assignment-user-matcher is particularly well-suited for:

  • 📞 Call Centers: Routing incoming calls (assignments) to the agent (user) with the right language skills, product knowledge, and availability.
  • 🎫 Customer Support Ticketing: Assigning new support tickets to support agents based on their expertise (e.g., "technical_issue," "api_support") and the ticket's urgency.
  • 🗄️ Back-Office Operations: Distributing tasks like data entry, document verification, or claims processing to available staff members based on task type and employee skills.
  • 🚗 Gig Economy Platforms (Niche): Matching available service providers to incoming customer requests where the provider pool is managed and assignments are plentiful (e.g., a dispatch system for a fleet of delivery drivers).
  • ** Leads Distribution:** Assigning sales leads to representatives based on territory, product specialization, or lead score.

Getting Started

1. Installation

npm install assignment-user-matcher redis
# or
yarn add assignment-user-matcher redis
# or
pnpm add assignment-user-matcher redis

2. Basic Usage

Here's a simple example to get you up and running:

import AssignmentMatcher from 'assignment-user-matcher'; // or `import { AssignmentMatcher } from 'assignment-user-matcher';`
import { createClient } from 'redis';

async function runExample() {
    // Connect to your Redis instance
    const redisClient = createClient({
        // url: 'redis://your-redis-host:6379' // Optional: specify Redis URL if not default
    });
    await redisClient.connect();
    console.log('Connected to Redis.');

    const assignmentMatcher = new AssignmentMatcher(redisClient, {
        redisPrefix: 'exampleApp:', // Good practice to namespace your Redis keys
        maxUserBacklogSize: 5, // Max 5 assignments per user backlog
        enableDefaultMatching: true,
    });

    // Add a user
    await assignmentMatcher.addUser({
        id: 'agent_007',
        tags: ['english', 'technical_support', 'vip_clients'],
    });
    console.log("User 'agent_007' added.");

    // Add an assignment
    await assignmentMatcher.addAssignment({
        id: 'ticket_12345',
        tags: ['english', 'technical_support'],
        createdAt: new Date().getTime(), // Use current time for priority
    });
    console.log("Assignment 'ticket_12345' added.");

    // Run the matching process
    // This will attempt to match pending assignments to available users
    console.log('Running matching process...');
    await assignmentMatcher.matchUsersAssignments();

    // Check current assignments for the user
    const userAssignments = await assignmentMatcher.getCurrentAssignmentsForUser('agent_007');
    console.log(`Assignments for 'agent_007':`, userAssignments);

    if (userAssignments && userAssignments.length > 0) {
        console.log(`User 'agent_007' is matched with assignment '${userAssignments[0].id}'.`);
    } else {
        console.log(`User 'agent_007' has no assignments currently.`);
    }

    // Clean up (optional, depending on your Redis setup)
    // await redisClient.flushDb(); // Be careful with this in production!
    await redisClient.quit();
    console.log('Disconnected from Redis.');
}

runExample().catch(console.error);

3. Workflow Quick Start

Workflows are easiest to use with the builder helpers and the executeWorkflow() convenience method.

import AssignmentMatcher, { workflow } from 'assignment-user-matcher';

const matcher = new AssignmentMatcher(redisClient, {
    enableWorkflows: true,
    redisPrefix: 'exampleApp:',
});

// Optional if your Redis client is already connected.
// Useful when the matcher is created with a closed client.
await matcher.waitUntilReady();

const onboardingWorkflow = workflow('onboarding', 'Onboarding')
    .step('profile')
    .name('Complete profile')
    .assignment({ tags: ['profile'], title: 'Complete your profile' })
    .targetUser('initiator')
    .defaultNext('review')
    .done()
    .step('review')
    .name('Manager review')
    .assignment({ tags: ['review'], title: 'Review onboarding' })
    .targetUser({ tag: 'managers' })
    .defaultNext(null)
    .done()
    .build();

// Registers the definition if needed, then starts the workflow instance.
const instance = await matcher.executeWorkflow(onboardingWorkflow, 'agent_007', {
    source: 'signup',
});

console.log(instance.id, instance.currentStepId);

You can still call registerWorkflow() and startWorkflow() separately if you want explicit lifecycle control.

Escalation ladders (escalateTo)

A step whose timeout expires normally fails the run (after any maxRetries). escalateTo(stepId) turns that timeout into a forward hop instead — the classic page-the-primary-then-the-secondary ladder:

const escalation = workflow('oncall', 'On-call escalation')
    .step('page-primary')
    .assignment({ tags: ['sev:1', 'oncall-primary'] })
    .targetUser({ tag: 'oncall-primary' })
    .timeout(60_000)
    .escalateTo('page-secondary')
    .route('result.acked === true', 'mitigate')
    .done()
    .step('page-secondary')
    .assignment({ tags: ['sev:1', 'oncall-secondary'] })
    .targetUser({ tag: 'oncall-secondary' })
    .timeout(300_000)
    .escalateTo('page-manager')
    .done();
// … 'page-manager' has no escalateTo: the ladder ends and the run fails,
// which is the honest "escalated to the top and nobody answered" state.

When a step escalates, its outstanding assignment is removed so a late responder cannot act on a superseded tier, context._escalatedFrom and context._escalationDepth are set, and a step.escalated transition is emitted (in addition to step.expired). Escalating does not consume maxRetries — a different person getting the work is not another attempt at the same one — and the target step starts with its own full maxRetries. maxEscalationDepth(n) (default 10) stops a mis-wired cycle from climbing forever.

Registration rejects an escalation target that doesn't exist, a step escalating to itself, escalation without a resolvable timeout, and escalation from inside a parallel group.

Targeting matters: targetUser({ tag: '…' }) routes the step's assignment through ordinary tag matching (so fairness, backlog caps, and the rolling-window grant cap all apply), while targetUser('<userId>') makes it workflow-targeted and therefore exempt from the fairness window cap. For tiered escalation you almost always want the tag form.

A workflow-targeted assignment is claimed queued→pending for its target through the same atomic claim gate as organic matching, whether or not the worker's tags/weights would ever have matched it — so acceptAssignment/completeAssignment work identically and the workflow advances. A worker who rejects a targeted assignment is not re-granted it (the standard rejection contract). When the person a step was aimed at by name rejects it, the step treats that as the end of the attempt — it fails, retries or escalates exactly as if they had let a blocking offer lapse. A rejection by one of several eligible people (a tag-routed step) is ordinary matching: the work goes back to the queue for the others.

How long a step waits is the step's own timeoutMs, not the matcher's offer clock. When an offer on a step's assignment lapses (matchExpirationMs / an escalation policy's response deadline) or the assignment is released from a worker (releaseUserAssignments, the idle sweep), the work is requeued for the next person and the run keeps waiting — no step.expired, no retry consumed. The step fails or escalates only when nobody can now take the work through it: the work was parked, its SLA rejection budget ran out (by lapse or by explicit rejection), or the one named person the step was aimed at let a blocking offer lapse or rejected it.

A step with no timeoutMs therefore waits for as long as its work does, and some exits are not reported to the run at all — an operator removing the step's assignment, the named person being removed or never having existed, every eligible person being barred. completeWorkflowStep() accepts the attempt's id (outcome.assignmentId, the assignmentId delivered with step.ready) and refuses a callback that answers an earlier attempt of the same step; without it a late callback is applied to the current attempt. Give human steps a timeoutMs (or the workflow a defaultTimeout()), and poll getStalledWorkflowRuns(idleMs, limit?), which lists active runs nothing has happened to for that long, oldest first.

A parallel group continues from the step that forked it: give the fork step the defaultNext() / route() the group should take once it is done, and where the group goes no longer depends on which branch happens to finish last. Two limits: a fork's route('result.…') conditions still see the payload of the branch that finished last (use context.step_<id>.… for order-independent routing), and a fork that declares no continuation keeps the older behaviour — the finishing branch's own routing decides. Upgrade note: a fork's defaultNext/route used to be ignored; a definition that set one while its branches route elsewhere now follows the fork, including for runs already in flight. waitForAll, failurePolicy and a branch's maxRetries are read from the branch step and fall back to the fork.

A step aimed at one named person (targetUser('<userId>'), 'initiator', 'previous') is found through a per-user index, so matching cost no longer grows with queue depth when workflows are enabled. The index is built automatically the first time an upgraded process matches; upgrade every replica together, or call backfillWorkflowIndexes() once the last old replica is gone — work queued by an old replica after the index was built is not in it until then. In a rolling deploy, upgrade the processes that run the orchestrator before the ones that run matching sweeps: an old orchestrator does not know the requeued marker on lapse events and fails the step on it. Such a step is still ordinary queued work: if someone else wins it through tag matching first, the named person is not given a copy. acceptAssignment() returns false — and changes nothing — when the caller's backlog entry has no pending record behind it (it used to return true having accepted nothing), and throws Assignment not found for user when the pending record belongs to somebody else. 'previous' means whoever the last completed step is recorded against, skipping escalation hops — the worker for an assignment step, the run's initiator for a machine or external step.

maxRetries is a per-step budget: retries one step spends do not reduce the next step's. In a parallel group with waitForAll: false, the first branch to finish moves the run on and the branches still pending are withdrawn (their assignments removed, their timeouts cleared unless the run has already re-entered that step). With failurePolicy: 'retry' a failed branch is retried in place against its own maxRetries, without disturbing the other branches; past that budget the run fails. failurePolicy, waitForAll and a branch's maxRetries fall back to the fork step when the branch declares none. Whenever a branch failure ends the run, the failed branch's work and every branch still waiting are withdrawn, and under 'continue' the failed branch's work is. cancelWorkflow() returns false and changes nothing for a run that has already completed, failed or been cancelled.

Plain object workflow definitions are also accepted. The library now fills in sensible defaults:

  • version defaults to 1
  • initialStepId defaults to the first step ID
  • invalid definitions fail early during registration with clear validation errors

4. Scaling & Reliability for Workflows

The workflow engine is designed to run with many orchestrator replicas over large instance counts. The key building blocks:

  • Indexed step timeouts — step expirations are tracked in a sorted set and claimed atomically, so processExpiredWorkflowSteps() is O(due steps) instead of scanning every instance, and an expiry fires on exactly one replica.
  • In-place conflict retries — optimistic-lock (VERSION_MISMATCH) conflicts are retried immediately with a fresh read instead of waiting for the orphan-reclaim window.
  • Machine steps that cannot strand a run — a machine step with no timeoutMs (and no workflow default) is given a lease (workflowMachineLeaseMs, default 15 minutes, 0 disables). If the process running the handler dies, the timeout sweep fails the step once the lease is up, and maxRetries decides whether it runs again — so a machine step is at-least-once. Upgrade note: the lease is on by default, is not renewed, and does not stop the handler — a handler that legitimately runs past it is failed while still running and, with maxRetries, started again alongside the original. Give long-running handlers a real timeoutMs or raise the lease. In a parallel group machine branches run one after another, so each branch's lease allows for the branches ahead of it (but not for their retries). Handlers receive an AbortSignal (signal) that fires when the step's own timeout does, and an attemptId naming that one execution — a retry, including the one after a crash, is a new attempt with a new id, so key outside effects that must happen once per run on instance.id + step.id. A result that could not be saved is no longer recorded as the handler failing: the step stays timed, and when that timeout comes due the run is settled like any timed-out step — retried under maxRetries, escalated, or failed. The unsaved result itself is lost.
  • Interrupted starts are recovered — a run whose first step was never saved because the process died inside startWorkflow is started by the timeout sweep workflowStartRecoveryMs after creation (default 30s); a per-run lock keeps replicas from recovering the same run together, and after five failed attempts the run is failed. Keep the grace period longer than your slowest startWorkflow, or recovery can race it. Only a crash is recovered. When the first step throws before anything was saved, startWorkflow() throws and the run is left failed (it used to stay active forever) with whatever work the step had already queued removed, so a caller that retries does not end up with two live runs. When something throws after the first step was saved, the run is started: startWorkflow() logs the error and returns the run; if that step has a timeout (or a machine lease), the timeout settles it. run.started is reported when the run is created, before its first step is saved, and again on each recovery attempt.
  • Transitions are reported after they are saved — while an event is being applied (every step.* transition, run.completed, run.failed), onWorkflowEvent is called once the run's save has succeeded, with the run as it was when the transition happened (status, step, context keys, history, branches and failures; nested values and the definition snapshot are shared, not copied); an attempt that loses a version race and is applied again does not report twice.
  • Failed attempts are kept — instance.failures lists attempts that failed or timed out (step, work id, user, time, reason, error; the most recent 200). history still holds only what completed.
  • One replica acts on a lapsed offer — processResponseDeadlines() running on several replicas claims each lapse through the pending record's removal, so the work is requeued and the lapse reported once.
  • Cheap saves — the run's version is kept in its own hash field, so a transition no longer decodes the whole run (definition snapshot, history, context) to compare one number. Runs written before the field existed are read the old way once, then carry it. The field is trusted only while a checksum stored beside it still matches the run, so a save by a replica still on the older release (which updates the run but neither field) is detected and the version read from the run itself — mixed versions during a rolling deploy are safe.
  • Delayed retry queue — failed events are scheduled for retry with exponential backoff (workflowRetryBackoffMs, default 1000ms initial delay) and drained automatically by the orchestrator; retries are claimed atomically across replicas.
  • Flow rate control — tune orchestrator throughput per replica: workflowEventBatchSize (XREADGROUP COUNT, default 10), workflowPollBlockMs (blocking poll wait, default 5000ms), and workflowMaxEventsPerSecond to cap event processing (applies to both stream consumption and retry draining; unlimited when unset).
  • Per-event idempotency markers — processed-event markers carry their own TTL (workflowIdempotencyTtlMs), and replayed step executions generate deterministic assignment IDs so crash-replays never create duplicate assignments.
  • Shared circuit breaker — set circuitBreakerShared: true to converge breaker state across replicas through a shared Redis failure counter (recommended for multi-replica deployments).
  • Instance retention — set workflowInstanceRetentionMs to expire terminal (completed/failed/cancelled) instances and clean their registry/index entries. Unset (the default) keeps them forever, matching previous behavior; a value in the range of days to weeks is recommended for high-volume deployments.
  • Event-stream trimming — set workflowEventStreamAutoTrim: true to keep the events:stream Redis stream bounded. Trimming runs after event processing and on the orchestrator's reclaim interval, and is anchored to the consumption frontier — every entry delivered and acknowledged by every consumer group — so it can never drop an unconsumed event, no matter how far consumers lag (the flip side: the stream still grows while consumers are down). Unset (the default), the stream is never trimmed; trimWorkflowEventStream() exposes the same trim for hosts running their own tick.

Operational helpers:

const matcher = new AssignmentMatcher(redisClient, {
    enableWorkflows: true,
    circuitBreakerShared: true,
    workflowInstanceRetentionMs: 30 * 24 * 60 * 60 * 1000, // 30 days
});

// Machine steps can run through named handlers with timeout enforcement
// (step.timeoutMs / defaultTimeoutMs); falls back to executeMachineTask.
matcher.registerMachineHandler('score-lead', async ({ instance, step }) => {
    return { score: 42 };
});

// One-time migration for deployments created before the indexes existed
await matcher.backfillWorkflowIndexes();

// Periodic maintenance for deployments without retention configured
await matcher.pruneWorkflowInstances(30 * 24 * 60 * 60 * 1000);

// Monitoring: active instances, retry queue depth, DLQ size, stream stats
const metrics = await matcher.getWorkflowMetrics();

API Reference

The main class provided is AssignmentMatcher.

new AssignmentMatcher(redisClient, options?)

Creates a new AssignmentMatcher instance.

  • redisClient: An initialized and connected redis client instance (version 4+).
  • options (Optional): Configuration options for the matcher. See Options below.

addUser(user: User): Promise<void>

Adds or updates a user in the system.

  • user: An object representing the user.
    • id: string: Unique identifier for the user.
    • tags: string[]: Array of tags associated with the user.
    • maxBacklogSize?: number: Optional per-user backlog cap overriding the matcher-wide maxUserBacklogSize in every matching path (0 = receive nothing; negative or non-numeric values are ignored). The cap bounds the user's total pending backlog: a user already holding work is only topped up to the cap, never past it. The fairness rolling-window auto-cap derivation stays team-level and keeps using the global value.

addAssignment(assignment: Assignment): Promise<void>

Adds a new assignment to be matched.

  • assignment: An object representing the assignment.
    • id: string: Unique identifier for the assignment.
    • tags: string[]: Array of tags required for the assignment.
    • createdAt: number: Timestamp (e.g., new Date().getTime()) indicating when the assignment was created. Used for default prioritization (older assignments get higher priority). Can be influenced by prioritizationFunction.
    • priority?: number | string: Optional explicit priority. If prioritizationFunction is used, this might be an input to it.
    • vetoedUsers?: string[]: Optional list of user IDs that must never receive this assignment, regardless of any other matching criteria (tags, routingWeights, priority, or workflow targeting). Vetoed assignments are excluded from a user's candidate pool before scoring, so the veto adds no per-match overhead. To change an assignment's vetoes, remove and re-add the assignment.

matchUsersAssignments(): Promise<void>

Triggers the matching process. This method iterates through pending assignments and tries to match them with suitable, available users based on tags and user backlog capacity. With no userId, every eligible user is evaluated in parallel by default and contested assignments go to whoever's claim resolves first - see the fairness option in Options to make the best-scoring candidate win deterministically ('best-match'), or to additionally balance load across users ('balanced', 'spread-work').

getCurrentAssignmentsForUser(userId: string): Promise<Assignment[]>

Retrieves the current list of assignments that a user is tentatively matched with (i.e., in their backlog).

  • userId: string: The ID of the user.

getPendingAssignmentsWithAge(options?: { limit?: number }): Promise<PendingAssignmentInfo[]>

Retrieves current pending assignments, including who owns each assignment and how long it has been pending. Reads are bounded (the pending hash is paged with HSCAN and each page's lookups are batched), and corrupt entries are skipped. Pass { limit } (clamped to 1000) to hydrate only the top-N longest-pending assignments instead of every one; without options the behavior is unchanged.

  • assignment: The assignment payload.
  • ownerId: The current owner user ID, or null if missing.
  • pendingForMs: Elapsed pending time in milliseconds.
  • pendingSince: Unix timestamp (ms) when the assignment entered pending state (derived from the assignment's own response deadline — escalation.respondWithinMs or matchExpirationMs).
  • expiresAt: Unix timestamp (ms) when pending expiration is scheduled.

getCompletedAssignments(options?: { cursor?, limit? }): Promise<CompletedAssignmentPage>

Lists terminal assignments from the completed store (completions and failures share it), cursor-paged like the other bounded reads. Each entry is stamped _status: 'completed' or 'failed' (the terminal marker also distinguishes them: _completedBy/_completedAt vs _failedBy/_failedAt). The store is only pruned when completedAssignmentsRetentionMs is configured (see Options); pagination is best-effort under a concurrent purge — the cursor is a positional offset, so entries deleted between pages can shift what a later page returns. Loop until hasMore is false and re-page if completeness matters.

User status & workload queries

Three bounded APIs answer "who is in the pool and how loaded are they?" without materializing whole Redis structures:

getUsersPaginated(options?: UserQueryOptions): Promise<UserQueryResult>

Paginated user scan with composable filters (logical AND):

const page = await matcher.getUsersPaginated({
    status: 'active', // 'all' | 'active' | 'paused' | 'idle'
    idleForMs: 10 * 60_000, // last touchUser() older than this
    hasBacklog: true, // pending backlog non-empty
    atCapacity: true, // backlog reached the effective cap
    limit: 100, // clamped to [1, 1000]
    includeAssignments: true, // also return pending/accepted ids
    includeTotal: true, // also return the unfiltered pool size
    cursor: null, // pass nextCursor verbatim to continue
});

Each UserSummary carries userId, the stored user record, paused, lastActiveAt, backlog, acceptedCount, the effective maxBacklogSize (per-user override honored), and atCapacity. status: 'idle' without an explicit idleForMs falls back to the matcher's idleUserTimeoutMs (and matches nobody when neither is set). Two pagination caveats, both consequences of paging the users hash with HSCAN: a scan page is never split, so a returned page may exceed limit by less than one scan page; and filters are applied during the scan, so a page may return fewer than limit users while hasMore is still true. Loop on hasMore until it is false. With includeAssignments, the returned acceptedAssignmentIds come straight from the per-user index and are not verified against the accepted store — a rare stale id can appear; getActiveAssignmentsForUser() is the verified (and self-healing) read.

getUserSummaries(userIds: string[]): Promise<UserSummary[]>

Order-preserving batch version for a known set of ids (chunked pipelined reads). Missing or corrupt user records are omitted.

getActiveAssignmentsForUser(userId: string): Promise<ActiveAssignmentInfo[]>

A user's accepted (in-progress) assignments, newest first, each with its acceptedAt timestamp — the complement to getCurrentAssignmentsForUser()'s pending backlog. Backed by a per-user accepted index (user:{id}:accepted) maintained on accept and on every terminal transition (complete/fail/remove/SLA sweeps). Two freshness notes:

  • The index is maintained from the version that introduced it: accepted work that predates upgrading (or that is in flight during a rolling upgrade) appears only after it cycles.
  • A stale member can survive removeAssignment on a non-SLA accepted assignment (only SLA records carry their owner); reads verify ids against the accepted store and self-heal, so results stay correct.

Crash-safety note. getUsers() (and getQueueStats()'s internal user scan) now skip a corrupt user record instead of throwing on it — the same precedent getAllAssignmentsFromStores already set. One malformed entry can no longer take down a dashboard endpoint.

pauseUser(userId: string): Promise<boolean> / resumeUser(userId: string): Promise<boolean>

Operator availability controls. A paused user stops receiving new assignments in every matching path but keeps their pending backlog and can still accept, complete, or reject work they already hold. Paused users are exempt from idle auto-removal (idleUserTimeoutMs) — pausing is deliberate absence, not idleness. pauseUser returns false when the user is not in the pool; resumeUser returns false when the user was not paused, and records activity (resets the idle clock) when it succeeds. Inspect state with isUserPaused(userId) and getPausedUsers().

When decision traces are enabled, paused users appear struck out in traces with a paused reason, and explainMatch() reports them as ineligible.

releaseUserAssignments(userId: string): Promise<string[]>

The redistribution counterpart to pauseUser: requeue every pending (matched but not yet accepted) assignment the user holds so other users can pick them up — for when a worker is gone rather than briefly away. Accepted assignments (work in progress) are never touched. Requeued assignments keep their original wait clock (getQueueStats().oldestWaitingMs does not reset), workflow subscribers receive an EXPIRED event per released assignment, and a still-paused user cannot win their released work back until resumed. Returns the released assignment ids ([] when the user holds nothing or is unknown). The idle auto-removal path (processIdleUsers) uses the same requeue mechanics internally.

assignToUser(assignmentId: string, userId: string, options?: { force?: boolean }): Promise<{ previousOwnerId: string | null }>

Operator override: hand an assignment directly to a user, bypassing tag/weight selection. Works on queued assignments, on pending assignments held by another user (the previous owner's backlog slot is released and the expiry clock restarts), and on accepted work already in progress. Idempotent when the user already owns the assignment.

Reassigning accepted work lands it as pending, not accepted: the new user gets a fresh offer they still have to answer, because they have agreed to nothing yet and an accepted record under somebody who never said yes is a completion deadline running against a promise nobody made. The previous owner's accepted index entry, their sla.completeWithinMs deadline and the _acceptedAt / _acceptedBy stamps are all cleared; the wait clock restarts at the hand-over, so queue-age dashboards can still see the work as unaccepted. The previous owner gets a released event with reason: 'reassigned' — nothing else names them, and anything mirroring their accepted work needs to hear that it moved. An offer window (schedule.notAfter) that the first acceptance already answered is not re-armed, and for SLA-bearing work the re-offer is counted as an offer so the acceptance rate cannot read above 100%.

Hard rules still apply unless force: true: the user must not be paused, must have backlog headroom, must not be vetoed on the assignment, and must not have previously rejected it. The learning layer is never fed by manual assignments. When tracing is active the override is recorded as a decision trace with mode 'manual', so supervisor actions land in the same audit trail as organic matches.

returnAcceptedToPending(userId: string, assignmentId: string): Promise<boolean>

Undo an acceptance: the worker who accepted the task gets it back as a pending offer of their own. Nothing is refused or requeued for others, so unlike rejectAssignment (which only works on pending work) this works on accepted work, and the worker is not barred from accepting it again. The completion deadline and accept stamps are cleared, and the lifecycle hook sees released (reassigned) for the worker followed by pending. Throws unless userId is the worker who accepted it.

updateAssignment(id: string, patch: AssignmentUpdate): Promise<UpdateAssignmentResult | null>

Edit a task that already exists — including one somebody is holding. The patch may carry tags, priority, title and meta; a field left undefined is untouched, and title / meta accept null to clear them. Policies (escalation, sla, schedule, vetoedUsers) are chosen when the work is created and are not patched piecemeal. Returns null when no live record exists; terminal work is not editable.

tags and priority decide who should have the task, so changing them is not a metadata write. The rule, applied in every state, is retag always, then re-check the holder:

| State | What happens | | --- | --- | | queued | Per-tag sorted sets move: removed tags are evicted, every surviving tag is rescored. | | scheduled / parked | The held record is rewritten in place; no indexes exist yet, and the activation or unpark builds them from the new tags. | | pending / accepted | The record is rewritten, then the current holder is scored against the new tag set exactly as organic matching scores them. |

A holder who still scores above zero keeps the task — including accepted work, because nothing about the job changed for them. A holder who no longer matches (or whom the new tags hard-veto) loses it: the task is taken back, an AssignmentLifecycleEvent of kind released fires with reason: 'retagged', and the record returns to the queue under its new tags with requeued: true in the result. The next matching pass offers it to somebody the new tags actually reach — this method never picks the replacement itself.

The re-check is the judgement the matching pass makes, not a smaller copy of it: a custom matchingFunction, the CIDR allow-list and the geo range all apply, so explainMatch and a retag can never disagree about the same person on the same task. Two holders are exempt. Workflow-targeted work is routed by name rather than by tags, so a tag change cannot un-route it. And a task whose holder accepted it between the read and the write is left where it is rather than requeued into a second copy.

An edit that leaves the tags alone never moves anything, whoever holds the task and however they came by it: fixing a typo in a title is not a reason to pull a job off the person doing it. Restating an identical tag set (in any order) counts as no change. Patch tags are trimmed and de-duplicated but never case-folded, because tags are compared exactly everywhere else — Plumbing and plumbing are two tags at creation, in matching and in an edit alike. An edit that omits priority keeps whatever the task already has, including a priority the engine derived at creation. Note that under enableDefaultMatching every user carries the shared default tag, so a retag can never strand a holder on tags alone — only an explicit zero-weight veto or a skill threshold will.

Like assignToUser, updateAssignment never feeds the learning layer: an operator changing what the work is says nothing about how well the worker was doing it.

const result = await matcher.updateAssignment('job-12', {
    title: 'Leaking kitchen tap',
    tags: ['plumbing', 'urgent'],
});
if (result?.requeued) {
    // the previous holder no longer matches — it is back in the queue
}

Response deadlines & escalation (Assignment.escalation)

By default an assignment nobody responds to is requeued after the matcher-wide matchExpirationMs — and the same user may win it straight back, on the very next pass. Attach an EscalationPolicy to make that behaviour explicit: a per-assignment deadline, a rest period before the same person is asked again, an optional block on the non-responder, a priority climb, and an optional tier ladder that moves the work to a different pool on each hop. No workflow is required.

await matcher.addAssignment({
    id: 'incident-1',
    tags: ['sev:1', 'oncall-primary'],
    priority: 1000,
    escalation: {
        respondWithinMs: 60_000,
        onNoResponse: 'block', // don't offer it back to whoever ignored it
        priorityBoost: 500, // ignored work climbs the queue
        tiers: [['oncall-primary'], ['oncall-secondary'], ['oncall-manager']],
        onExhausted: 'park', // nobody answered, all the way up
    },
});

matcher.startMaintenance(); // deadlines don't fire unless something sweeps them

| Field | Meaning | Default | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------- | | respondWithinMs | Per-assignment response deadline, overriding matchExpirationMs | required | | onNoResponse | 'block' treats a non-response as a soft rejection (same rejected set an explicit reject writes to); 'allow' keeps the historical behaviour | 'allow' | | offerCooldownMs | How long the non-responder rests before this assignment can be offered to them again. Overrides the matcher-wide offerCooldownMs. Ignored under onNoResponse: 'block' | matcher-wide value | | priorityBoost | Priority delta applied on each hop | 0 | | tiers | Tag ladder. Tier tags are swapped per hop; tags not named by any tier survive untouched | none | | maxEscalations | Hop ceiling | tiers.length - 1, else unlimited | | onExhausted | 'queue' keeps recirculating; 'park' holds it out of matching | 'queue' |

The wait clock always survives an escalation: requeues go through addAssignment, whose NX keeps the original first-enqueue time, so getQueueStats().oldestWaitingMs measures the work item rather than the current tier.

Offer cooldowns (offerCooldownMs)

onNoResponse has only two settings, and neither suits work with a small eligible pool: 'allow' hands the assignment straight back to whoever just ignored it, and 'block' bars them permanently — which, when they are the only eligible worker, means the work is never assigned to anybody. A cooldown is the middle ground. The non-responder is held out of matching for that one assignment for a while, so anybody else gets a clear run at it, and they are asked again afterwards.

const matcher = new AssignmentMatcher(redis, {
    matchExpirationMs: 60_000,
    offerCooldownMs: 60_000, // default 0 (off): historical behaviour is unchanged
});

Per assignment, escalation.offerCooldownMs overrides it. The cooldown never applies to operator overrides (assignToUser) or workflow-targeted grants, is skipped entirely under onNoResponse: 'block' (a permanent bar makes a rest period moot), and is cleared when the user accepts the work or an operator hands it to them. A resting candidate is struck out in explainMatch() and in decision traces with { kind: 'offerCooldown', until }, so "nobody is eligible right now" always says why.

Bounding an unanswered-offer loop

Cooldowns slow a loop down; they do not end one. Work that nobody ever answers should eventually stop circulating and become somebody's problem to look at. maxEscalations does not need tiers — with no ladder to climb, it is simply a ceiling on how many times the work is re-offered before onExhausted fires:

escalation: {
    respondWithinMs: 60_000,
    offerCooldownMs: 60_000,
    maxEscalations: 3,   // three unanswered offers is enough
    onExhausted: 'park', // then it is an operator's problem, not a loop
}

Without a maxEscalations ceiling the ladder is unbounded by design, so an assignment with one eligible worker who never responds is re-offered on every sweep for as long as it exists — and every one of those offers is a real decision, with a decision trace to match. Park it instead: getParkedAssignments() lists what nobody answered, and unparkAssignment(id) puts it back.

Subscribe via onAssignmentLifecycle for escalated ({ fromWorkerId, level, blockedPreviousOwner }) and escalationExhausted ({ level, parked }) events; expired is still emitted first, so existing consumers are unaffected. Parked assignments are reachable with getParkedAssignments(), returned to the queue with unparkAssignment(id, { resetEscalation? }), and report _status: 'parked' from getAssignment() — they never read as "not found". getEscalationLevel(id) reports how far an assignment has climbed.

failed — the worker-reported outcome

failAssignment(userId, assignmentId, reason?) now emits { kind: 'failed', taskId, workerId, reason?, failedAt }. It previously emitted nothing at all, so an explicit failure was the one terminal transition invisible to onAssignmentLifecycle (the workflow event stream did hear it). It is deliberately distinct from completionBreached with action: 'fail': that is a deadline a policy acted on, this is a person reporting that the work could not be done. No assignment snapshot rides along — the record stays in the completed store carrying _failedBy / _failureReason, so getAssignment() can still answer for it.

A host that switches exhaustively over AssignmentLifecycleEvent will see a new kind here; the union is additive and every existing branch keeps its shape.

SLA policies (Assignment.sla)

Escalation owns the response side (how long a matched user has to accept). SlaPolicy owns everything after that: how long the accepting user has to finish, how many times the work may be refused before it is pulled from rotation, and an absolute freshness cutoff after which the work is moot.

await matcher.addAssignment({
    id: 'order-42',
    tags: ['fulfillment'],
    sla: {
        completeWithinMs: 30 * 60_000, // finish within 30 min of accepting
        onCompletionBreach: 'requeue', // take it back if they don't
        maxRejections: 3, // after 3 refusals, stop offering it
        expireAfterMs: 24 * 3600_000, // moot after 24h no matter what
    },
});

matcher.startMaintenance(); // SLA clocks are swept by the maintenance tick

| Field | Meaning | Default | | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------- | | completeWithinMs | Completion deadline, measured from acceptAssignment(). Swept by processCompletionDeadlines() | none | | expireAfterMs | Absolute freshness cutoff from first enqueue — survives requeues and applies in every state (queued, pending, accepted). Swept by processSlaExpiries() | none | | maxRejections | Refusal budget. Explicit rejectAssignment() calls and blocking no-response expiries (escalation.onNoResponse: 'block') count; idle/operator releases don't | none | | onCompletionBreach | 'notify' (event only, worker keeps it) / 'requeue' (take back, block breacher) / 'fail' / 'park' | 'notify' | | onMaxRejections | 'park' / 'fail' / 'keep' (keep offering; budget becomes measurement-only) | 'park' | | onExpire | 'drop' (remove entirely) / 'park' (retain for inspection) | 'drop' |

Semantics worth knowing:

  • Fire-once. A breached completion deadline is removed from the deadline index before the action runs, so a 'notify' breach doesn't re-fire every tick; a requeued-after-breach assignment gets a fresh completion clock only on its next accept.
  • The TTL never extends. Rejection ping-pong re-adds the same JSON, whose _enqueuedAt keeps the original first-enqueue time — the freshness cutoff is a hard wall, not a sliding window.
  • Rejection budget outranks escalation. Once maxRejections is exhausted the assignment is parked/failed instead of climbing further tiers.
  • Sweep granularity. Like response deadlines, SLA clocks fire on the maintenance tick, not at the exact deadline.
  • Unparking. unparkAssignment(id, { resetSla: true }) clears the first-enqueue clock and rejection counter; without it an unparked TTL-expired item simply expires again on the next sweep.

Lifecycle events: completionBreached ({ workerId, action }), slaExpired ({ ownerId, action }), rejectionBudgetExhausted ({ rejections, action }).

SLO measurement. getSlaStats(tag?) returns aggregate attainment counters — global, or for one tag: offers, acceptedInTime, acceptanceBreaches, completionBreaches, ttlExpiries, rejectionParked, plus meanAcceptLatencyMs (matched→accepted) and meanCompleteLatencyMs (accepted→completed). Counters are best-effort HINCRBYs piggybacking paths that already touch Redis; only SLA-bearing assignments are measured.

Learning integration. Breach outcomes flow into the contextual bandit as ordinary rewards (TTL expiry and completion breach → expire; completion breach with 'fail' → fail), so per-user/per-tag stats and the automatic routing-weight vetoes pick up chronic breachers with no extra configuration. The default feature extractor also emits sla:hasDeadline and sla:tightness (normalized against learningSlaTightnessReferenceMs, default 1h) for assignments with a completion deadline, letting the model learn that tight-deadline work needs fast finishers. Custom feature extractors are unaffected.

Scheduled assignments (Assignment.schedule)

Escalation owns the response clock and SlaPolicy owns the post-accept contract; SchedulePolicy owns the offer window: when the work becomes visible to matching at all (notBefore), and how long an offer may go un-accepted before it is pulled (notAfter). Acceptance ends the schedule's authority — completion pressure is sla.completeWithinMs's job.

await matcher.addAssignment({
    id: 'callback-42',
    tags: ['callbacks'],
    schedule: {
        notBefore: Date.parse('2026-08-07T09:00:00Z'), // invisible to matching until 9:00
        notAfter: Date.parse('2026-08-07T11:00:00Z'), // parked if nobody accepted by 11:00
        onMiss: 'park', // or 'drop'
    },
});

matcher.startMaintenance(); // schedule clocks are swept by the maintenance tick

| Field | Meaning | Default | | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | notBefore | Epoch ms. Held in a dedicated scheduled store — no matching, no workflow targeting, no wait clock — until the scheduled sweep enqueues it | none | | notAfter | Epoch ms. Absolute offer deadline; applies only while un-accepted (scheduled, queued, or pending). Valid without notBefore. Must be > notBefore when both are set | none | | onMiss | 'park' (retain for inspection) / 'drop' (remove entirely) when notAfter elapses un-accepted | 'park' |

Semantics worth knowing:

  • Clocks anchor at activation. A held assignment has no wait clock and no SLA freshness stamp; both start when the sweep (or a forced early assign) enqueues it. getQueueStats().oldestWaitingMs never counts held work.
  • Acceptance kills the offer clock. Once accepted, a passing notAfter is a non-event — late completion is governed by sla.completeWithinMs alone.
  • A miss beats activation. When one sweep finds both timestamps in the past, the assignment parks/drops directly; it never transits the queue or emits scheduleActivated.
  • The offer deadline never extends. notAfter is absolute, so rejection requeues carry the same deadline — a re-offered assignment can still miss.
  • Fire-once, replica-safe. Sweep entries are claimed with a ZREM before acting, so concurrent replicas can run the sweep in parallel.
  • Sweep granularity. Schedule clocks fire on the maintenance tick (processScheduledAssignments()), not at the exact millisecond.
  • One policy, one window. Repeating work is a recurring assignment: a standing template whose sweep materializes each occurrence as an ordinary scheduled assignment carrying a derived policy. (Hand-materializing occurrences from your own scheduler still works — re-adding an existing id never resets its clocks, so materialization is idempotent — and the scheduling module produces dated occurrences you can feed straight in.)
  • Operator override. assignToUser(id, userId) refuses held assignments; { force: true } early-activates (clocks anchor there). If the user then rejects and notBefore is still in the future, the assignment returns to the scheduled store.
  • Unparking. unparkAssignment(id, { resetSchedule: true }) strips the schedule policy; without it a miss-parked assignment misses again on the next sweep.

Lifecycle events: scheduleActivated ({ taskId, at }) and scheduleMissed ({ ownerId, state, action, assignment } — the snapshot is the last surviving copy on the 'drop' path).

Introspection. Held assignments are listed by getScheduledAssignments(), read as _status: 'scheduled' from getAssignment(), and counted separately in getAssignmentCounts().scheduled and getQueueStats().scheduled (excluded from total and pagination, like parked items). Misses bump the scheduleMisses counter in getSlaStats(tag?).

Learning integration. Misses feed the contextual bandit as expire outcomes — a pending-state miss penalizes the user who sat on the offer, so automatic routing-weight vetoes pick up chronic missers with no extra configuration.

Timeslots and advance booking (Assignment.slot)

SchedulePolicy says when an assignment may be offered; a TimeSlot says when the work is performed and for how long — a fixed appointment, the thing a calendar entry is made of. They are different clocks and deliberately different objects. A task can carry either, both, or neither.

await matcher.addAssignment({
    id: 'boiler-service-42',
    tags: ['gas-safe', 'region:north'],
    slot: {
        startAt: Date.parse('2026-10-08T14:00:00Z'), // Thursday 14:00
        durationMs: 90 * 60_000, // for an hour and a half
        bookAheadMs: 14 * 24 * 3600_000, // reserve an engineer a fortnight out (default: a week)
        onUnbooked: 'queue', // or 'park' / 'drop' if nobody was booked in time
    },
});

matcher.startMaintenance(); // the booking sweep runs on the maintenance tick

Three moments, not one:

startAt − bookAheadMs      the sweep may reserve a worker
        ↓
   reservation             on their calendar; blocks the hour; no backlog place, no clocks
        ↓
     startAt               activation: a pending offer to whoever holds the booking

| Field | Meaning | Default | | ------------- | ------------------------------------------------------------------------------------------ | --------- | | startAt | Epoch ms the work is performed. Holds the assignment out of matching until then. | required | | durationMs | How long it takes. Must be > 0 and at most maxSlotSpanMs. | required | | bookAheadMs | How far ahead of startAt the sweep may book. | 7 days | | onUnbooked | 'queue' (open pool, staffed late) / 'park' / 'drop' when startAt arrives unbooked. | 'queue' |

Semantics worth knowing:

  • A reservation is not live work. Until startAt a booked task occupies no backlog place and starts no clock — accepted keeps meaning "I am working on this". A week of booked appointments cannot fill somebody's backlog cap, and an SLA completion deadline never runs against work that has not started. The booking sweep therefore ignores today's backlog and pause state when ranking people for next Thursday.
  • Two appointments never overlap. The clash check and the write are one Lua script (book-slot.lua); two sweeps cannot both book one person's 14:00. Intervals are half-open, so back-to-back appointments stand. maxSlotSpanMs (default 24h) bounds how far back the probe reaches, which is why a longer slot is refused at addAssignment.
  • The sweep books; the planner reviews. processSlotBookings() reserves the best eligible worker — ranked by the same evaluator explainMatch uses, so routing weights, wildcards, vetoes, thresholds, CIDR and geo all apply — once the book-ahead window opens. A slot nobody can take emits slotUnfillable and is re-examined every slotBookingRetryMs (default 15 min). It never feeds or consumes the learning layer: nobody was offered anything and nobody chose.
  • Availability is your input, not the library's guess. Give slotAvailability(userIds, from, to) and return per-worker blocked intervals (approved leave — refuses the booking) and warnings (outside a rostered shift, a busy personal calendar — allows it and records the reason on the booking). It is called once per pass for the whole candidate set, never per candidate. Without it, the only rule is the overlap rule.
  • Activation goes to the holder. At startAt the task lands as a pending offer on the booked worker, through the same assignToUser(…, { force: true }) path an operator uses — never as an acceptance, because they have not said yes yet. The booking row survives activation and is cleared only on hand-back, removal, completion or failure, so the overlap rule protects in-flight work too.
  • Handing back is not declining. handBackBooking(id, userId, reason) releases the reservation and adds the worker to the assignment's rejected set, so the next sweep books somebody else rather than the same person again.
  • An explicit offer window can delay an appointment, never bring it forward. With both slot and schedule.notBefore, activation is the later of the two.

Public surface: bookSlot(id, userId, { force?, source? }) (the planner's manual booking through the same gate; force skips blocked, never the overlap rule), releaseSlotBooking(id), handBackBooking(id, userId, reason?), getSlotBooking(id), getBookings({ from, to, userId? }) (the calendar read, half-open on both sides), rankSlotCandidates(id) (best first, each with bookable and why not), and processSlotBookings() (also run by runMaintenanceOnce, before the scheduled sweep, so a slot booked in a pass activates onto its holder in the same pass). MaintenanceReport gains slotsBooked / slotsUnfillable; MaintenanceOptions.slotBookings switches the sweep off.

Lifecycle events: slotBooked ({ workerId, startAt, endAt, source, warnings? }), slotBookingReleased ({ workerId, reason: 'hand-back' | 'operator' | 'terminal', detail? }) and slotUnfillable ({ startAt, endAt }).

Recurring assignments (addRecurringAssignment)

A recurring assignment is a standing template, never itself matchable: the recurrence sweep cuts each occurrence from it as an ordinary assignment whose schedule is derived from the policy (notBefore = the slot's open time, notAfter = open + windowMs). Everything else the template carries — tags, priority, SLA, escalation, vetoes, geo — is inherited by every occurrence.

await matcher.addRecurringAssignment({
    id: 'blog-draft',
    tags: ['blog'],
    recurrence: {
        everyMs: 7 * 24 * 3600_000, // the period …
        times: 2, // … and two occurrences in it, spread evenly: twice a week
        startAt: Date.parse('2026-09-07T09:00:00Z'), // first window opens here (default: now)
        windowMs: 3 * 24 * 3600_000, // each occurrence offered for 3 days
        onMiss: 'park', // an unserved window parks the occurrence for inspection
    },
});

matcher.startMaintenance(); // the recurrence sweep rides the maintenance tick

| Field | Meaning | Default | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------- | -------- | | everyMs | The repeating period. With times: 1 this is simply the interval between window opens | required | | times | Occurrences per period, spread evenly across it (gap = everyMs / times). The gap is what must be at least 1000 ms | 1 | | startAt | Epoch ms the first window opens | now | | windowMs | Offer window per occurrence (schedule.notAfter = open + windowMs). Omitted: occurrences never expire off the offer clock | none | | onMiss | Per-occurrence miss policy, as in SchedulePolicy | 'park' | | until | No occurrence opens after this epoch ms; the template retires | none | | maxOccurrences | Retire after this many occurrences materialized | none | | catchUp | Downtime policy: 'skip' materializes only slots whose window is still open; 'all' materializes every elapsed slot (audit trail) | 'skip' |

Semantics worth knowing:

  • Occurrence ids are deterministic — <templateId>@<openEpochMs> — so a crashed sweep re-materializing a slot is an idempotent re-add, and any occurrence traces back to its template with no extra state.
  • Slots never drift. They align to startAt + k × gap whatever the sweep cadence; the tick decides when a slot is noticed, never where it sits.
  • times is sugar with teeth. It is resolved once into the gap, and every other field is then measured in gaps rather than periods: windowMs is one occurrence's offer window, the sweep looks one gap ahead, and until / maxOccurrences stay totals — so a budget can run out part-way through a period. A period that does not divide evenly rounds the gap to the nearest millisecond; slots stay exactly one gap apart rather than re-anchoring to each period.
  • One occurrence ahead. The sweep materializes each occurrence one interval before its window opens, so upcoming work is already visible in the scheduled store (getScheduledAssignments(), getQueueStats().scheduled).
  • Skipped slots are free. Under catchUp: 'skip', slots that fully elapsed during downtime never existed: they don't count against maxOccurrences and don't flood the queue on revival. Under 'all' they materialize and are immediately missed by the schedule sweep (parked/dro