@gate-forge/pack-task

中文文档
0.19.2发布于 2026/11/10Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 2461

Background-task discovery pack: TS-only AST-light detector (GPP/3) for BullMQ / Bee-Queue / custom queues / message handlers / recurring jobs / @Task @Queue decorators, idempotency + retry-policy + terminal-on + observability contracts, audit-run entity-a

原始使用文档
文档目录14 节
  1. Engine-level proof: the queue observer
  2. What a deliver case does
  3. What an attempts rule settles
  4. Proving it
  5. How discovery works
  6. Classification signals (phase 4): none
  7. Detector vocabulary
  8. Obligation contract vocabulary
  9. Setup
  10. Entity adapter schema + audit trail
  11. Example app
  12. Adversarial coverage
  13. Determinism
  14. Development

@gate-forge/pack-task

Background-task discovery pack: a pure-TypeScript GPP/3 in-process detector that finds background-task signatures in .ts/.js/.mjs source — no Python subprocess, no execution, no external deps — plus an audit-trail entity-adapter schema and an example server that proves the five obligation contracts the pack claims.

Engine-level proof: the queue observer

A background job's attempts, terminal state and idempotency live in the QUEUE, so the engine reads the queue itself. A test's own "the job succeeded" is never proof — exactly like a test's own HTTP status. A repository opts in with an engine-owned queueObserver block in .gateforge.yml:

queueObserver:
  kind: bullmq                       # or a module path whose default export is a factory
  connection:
    urlEnv: GATEFORGE_QUEUE_REDIS_URL   # host/port form: {host, port}
  queues:
    - name: mailer                   # the queue the engine reads
      taskResourceId: task.email.send
  pollIntervalMs: 100                # transition-sampling interval (default 200)
  terminalTimeoutMs: 30000           # bound on waiting for the delivery to settle
  • The block lives in .gateforge.yml, so it is inside the trusted policy digest: a candidate cannot point the engine at a queue it controls.
  • Connection material never carries a secret inline — the URL form names an environment variable the WITNESS process resolves privately; the value is never sealed into a record, a report or argv.
  • kind: bullmq reads the queue with the project's own bullmq and ioredis (optional peers of @gate-forge/witness: install them next to the app, npm install --save-dev bullmq ioredis). A project that declares no BullMQ observer never installs or loads them; one that declares it without them fails closed with that install command.
  • WITHOUT the block the task namespace is unavailable (every task:* contract fails closed, cause VERIFIER_UNSUPPORTED) and every engine-task case blocks with a naming diagnostic. gateforge init therefore recommends this pack's cases only when the block is configured.
  • test-gates hands the declaration to the witness it spawns (GATEFORGE_QUEUE_OBSERVER + GATEFORGE_QUEUE_OBSERVER_CONFIG); a repository without the block passes nothing and its spawn environment is byte-identical.

What a deliver case does

The engine produces the delivery, not the suite: it stamps the delivery identity, the idempotency key and the attempt bound (taken from the case's own attempts rule, so the policy declares the retry bound exactly once), then polls the queue until every produced job settles and seals what it read. count deliveries of one case share ONE idempotency key — that is what makes a duplicate-key case a duplicate — while each delivery gets its own identity.

What an attempts rule settles

FieldMeaning
resourceIdthe task resource the case delivers to (must match the action)
countthe declared attempt bound: no job may exceed it, and the queue's own declared bound may not exceed it
terminalsucceeded (every job completed), failed (every job failed), rejected (every job failed on its FIRST attempt)
minAttempts (optional)every job used at least this many attempts — "retries up to N" cannot be satisfied by a queue that never retried
recoveredFromStall (optional)the engine's own timeline must show a lost-worker reclaim: the same job handed out again with UNCHANGED attempts and no failure reason (an error retry raises both) — and the delivery still settles

A delivery case that declares no attempts rule settles nothing and is blocked (BEHAVIOR_BINDING_MISMATCH), and a case that carries HTTP attempts or a browser observation is rejected outright: those prove a transport claim, not a background job.

Proving it

packages/cli/test/task-queue-behavior-e2e.test.ts runs the real CLI, the real witness and a REAL BullMQ application (example/task-bullmq/: a queue plus worker processes, one of which is genuinely lost mid-job) against a disposable Redis. Each contract ships a fail variant the engine must block. The suite SKIPS unless GATEFORGE_TEST_REDIS_URL names a live Redis — the engine's queue reader needs a real queue, and a fake one would be a mock as proof:

docker run -d --rm --name gateforge-queue-redis -p 127.0.0.1:6379 redis:7-alpine
GATEFORGE_TEST_REDIS_URL=redis://127.0.0.1:6379 npm test -- task-queue-behavior-e2e

How discovery works

The detector scans .ts/.tsx/.js/.mjs files with regex-based AST-light patterns (matching pack-auth's strategy). It recognizes the task constructs below and reports its verdict through the discovery outcome's typed blocking vocabulary — the pack emits no resources and no classification signals of its own:

Source constructRecognized as
new Queue('email.send', ...) / new BullMQ.Queue(...)BullMQ task + retry policy from defaultJobOptions
new Bee('image.resize', ...)Bee-Queue task
register('webhook.dispatch', handler)custom-queue task (single-line)
new CustomQueue({ name, handler, ... })custom-queue task (multi-line, balanced-brace walk)
navigator.serviceWorker.register(...) / *.serviceWorker.register(...) / serviceWorkerRegistration.register(...) / workbox.* / caches.* / window.* / document.*nothing — browser/platform registration APIs, never task queues (excluded before matching). The receiver chain is rebuilt across MULTI-LINE call expressions too, so navigator.serviceWorker on its own line above the register(...) continuation line is still excluded (the exact unified-dogfood false positive)
onmessage = handler / .on('message', ...) / addEventListener('message', ...)message-handler task
setInterval(handler, ms, ...) / setImmediate(handler, ...)recurring task
@Task(...) / @Queue(...) decorator annotationsdecorator task

Classification signals (phase 4): none

The pack mints no classificationSignals. It once emitted internality/worker reachability signals targeted at model names GUESSED from the worker file (model/repository import-path segments, every PascalCase identifier, stripped task-name fragments). Those targets are guesses about OTHER detectors' resources — this pack discovers no resources itself — so in real repos they mostly matched nothing and every miss surfaced as a STALE_SIGNAL_TARGET blocker (236 in the unified dogfood) while adding no information: unknown exposure already defaults user-facing and unknown lifecycle already defaults enabled (ADR 0003 D5), so removal flips no classification and shrinks no obligation set. Core's STALE_SIGNAL_TARGET detection remains for genuinely stale authority signals. The trustedInternalEntryPoints worker category binding (detector: gateforge.pack-task) stays syntactically valid but is unexercised: internality certification that relied on guessed worker reachability is now honestly unavailable (INCOMPLETE_PROOF_SCOPE, conservative user-facing default) instead of guess-based.

Detector vocabulary

  • Recognized task inventory — each recognized construct carries:

    • retryPolicy: { maxAttempts: number, backoff: 'fixed' | 'exponential' } — extracted from defaultJobOptions.attempts / .backoff.type, defaults to {maxAttempts: 1, backoff: 'fixed'}.
    • idempotencyKey: boolean — true if jobId / dedupKey / idempotencyKey / dedupe appears in source.
    • terminalOn: string[] — error types from terminalOn: [...] (terminal = no retry).
    • observability: boolean — true if metrics / tracing / .on('completed'|'failed'|'stalled', ...) appears.
    • source: { file, line, col } — declaration location.
    • framework: 'bullmq' | 'bee-queue' | 'custom-queue' | 'message-handler' | 'recurring' | 'decorator'.

    The inventory itself is not emitted on the wire (no resources, no signals — phase 4); it drives the blocking vocabulary below and the obligation contracts the pack claims.

  • Findings

    • DUPLICATE_TASK_ID — same id discovered twice; first wins.
    • AMBIGUOUS_HANDLER — register(...) or new CustomQueue(...) with no resolvable handler reference. For the single-line register(...) shape this fires only when the file shows real queue evidence (an import from a known queue library — bullmq, bull, bee-queue, celery, kue, agenda, pg-boss, sidekiq — a queue-named module, or a queue constructor such as new Queue(...) / new CustomQueue(...)).
    • PARSE_ERROR — file could not be read.
  • Unresolved

    • UNPROVEN_QUEUE_REGISTRATION — a handler-less register('name') in a file with no queue evidence: the shape is not provably a task registration, so the detector emits no worker signal and reports this typed blocking reason instead of the vague AMBIGUOUS_HANDLER finding (a browser service-worker registration produces nothing at all).

Obligation contract vocabulary

Five contracts, every detected task generates all of them:

ContractMeaningExample test in example/task/
task:retry-policy-enforcedflaky task retries up to maxAttempts before final failureflaky profile, 5 attempts before success
task:idempotentsame idempotency key is deduplicatedduplicate profile, side-effect runs once
task:terminal-handlederrors whose type is in terminalOn are NOT retriedterminal profile, 1 attempt only
task:observability-recordedevery execution (success + failure) emits an audit row in runs.jsonevery profile
task:duplicate-delivery-handledduplicate deliveries produce exactly one side effectduplicate profile

The full obligation id is <resourceId>:<contract> — e.g. task.email.send:task:retry-policy-enforced.

Setup

# .gateforge.yml
plugins:
  - id: gateforge.pack-task
    version: 0.1.0
    transport: in-process
    module: '@gate-forge/pack-task'

The pack's default export is the pinned { discover(paths) } contract.

Entity adapter schema + audit trail

Every detected task generates runs.json audit rows when run against the example server. The witness reads them via the adapter contract:

{
  resourceId: 'task.runs',
  read(ctx, id)         -> Promise<{ runId, attempts, sideEffectCount, terminal, ... }>,
  normalize(body)       -> { entityId, fields: { id, retries, sideEffectCount, terminal } },
  deletion: 'archive',
  environmentFingerprint: 'task-loopback-v1',
}

TaskAuditAdapterSchema + validateTaskAuditAdapter (mirrors pack-sqlalchemy's EntityAdapterSchema) enforce the contract fail-closed.

Example app

example/task/server.js (port 3004, node:http only):

RouteMethodBehaviour
/healthGET{ ok: true }
/tasksGETlist of registered task names
/enqueuePOST{ name, key?, profile, payload } — enqueues a task
/runsGETaudit trail (runs.json)

Profiles:

  • flaky — fails on attempts 1..maxAttempts-1, succeeds on the last
  • duplicate — always succeeds; same key is deduped
  • terminal — throws AuthError immediately; no retry
  • normal — always succeeds

Usage:

node example/task/server.js --port 3004

Adversarial coverage

CaseBehaviour asserted in test/e2e.test.ts
(a) flaky5 attempts, last attempt succeeds, 4 retry rows + 1 success row
(b + e) duplicatesame key deduped, sideEffectCount stays at 1 across two calls
(c) terminal1 attempt only, no retry, terminal: true
(d) observabilityevery enqueue appends to runs.json
(i) fake-green idempotentsideEffectCount ≠ 2 on duplicate key (regression line)
(ii) fake-green terminal-handledterminal does NOT retry (regression line)

Determinism

Same input paths + same file bytes → byte-identical discovery output: no Date.now() / Math.random(); every array sorted; every name a literal from the source; fixed key order on the wire.

Development

npm test                    # vitest run
npm run typecheck
npm run build               # tsc → dist/
node ../example/task/server.js --port 3004  # ad-hoc serve

版本与发布记录

@gate-forge/pack-task 共发布 46 个版本,首次发布于 2026/09/17;过去 12 个月发布了 46 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.19.2latest2026/11/105 天前
0.19.12026/11/106 天前
0.19.02026/10/2917 天前
0.18.32026/10/2522 天前
0.18.22026/10/2125 天前
0.18.12026/10/2125 天前

关于 @gate-forge/pack-task 的常见问题

@gate-forge/pack-task 是什么?

Background-task discovery pack: TS-only AST-light detector (GPP/3) for BullMQ / Bee-Queue / custom queues / message handlers / recurring jobs / @Task @Queue decorators, idempotency + retry-policy + terminal-on + observability contracts, audit-run entity-a

如何安装 @gate-forge/pack-task?

在项目目录运行 npm install @gate-forge/pack-task,或使用 pnpm add / yarn add / bun add。

@gate-forge/pack-task 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@gate-forge/pack-task 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@gate-forge/pack-task 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@gate-forge/pack-task 可以商用吗?

@gate-forge/pack-task 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@gate-forge/pack-task 的下载量有多少?

根据 npm 官方下载统计,@gate-forge/pack-task 在 2026/10/16 – 2026/11/14 这 30 天内被下载 2,461 次,日均约 82 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@gate-forge/pack-task 还在维护吗?

最新版本 0.19.2 发布于 2026/11/10(5 天前);至今共发布 46 个版本,其中过去 12 个月发布了 46 个;首次发布于 2026/09/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。