@happyvertical/smrt-jobs 0.60.13 → 0.60.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +13 -6
- package/README.md +68 -0
- package/dist/chunks/{runner-CH-xLt22.js → runner-DucZ0Lvj.js} +306 -22
- package/dist/chunks/runner-DucZ0Lvj.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +306 -153
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +244 -12
- package/dist/runner.d.ts +6 -0
- package/dist/runner.d.ts.map +1 -1
- package/dist/runner.js +1 -1
- package/dist/schedule-admission.d.ts +44 -0
- package/dist/schedule-admission.d.ts.map +1 -0
- package/dist/schedule-runner.d.ts +30 -15
- package/dist/schedule-runner.d.ts.map +1 -1
- package/dist/smrt-job-dedupe-slot.d.ts +19 -0
- package/dist/smrt-job-dedupe-slot.d.ts.map +1 -0
- package/dist/smrt-job.d.ts +31 -6
- package/dist/smrt-job.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +73 -7
- package/dist/smrt-knowledge.okf.md +8 -2
- package/package.json +7 -7
- package/dist/chunks/runner-CH-xLt22.js.map +0 -1
package/dist/smrt-job.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { RetryStrategyConfig } from '@happyvertical/jobs';
|
|
2
2
|
import { SmrtCollection, SmrtObject, type SmrtSaveOptions } from '@happyvertical/smrt-core';
|
|
3
|
+
import type { DatabaseInterface } from '@happyvertical/sql';
|
|
3
4
|
/**
|
|
4
5
|
* Job status type
|
|
5
6
|
*/
|
|
@@ -15,7 +16,7 @@ export type TimeoutBehavior = 'fail' | 'kill' | 'warn';
|
|
|
15
16
|
* Worker claim/recovery state and restored tenant context use string IDs.
|
|
16
17
|
* Both paths use this projection instead of hydrating raw UUIDs from `SELECT *`.
|
|
17
18
|
*/
|
|
18
|
-
export declare const SMRT_JOB_PORTABLE_SELECT_COLUMNS = "\n CAST(id AS VARCHAR) AS id,\n slug, context, created_at, updated_at,\n CAST(tenant_id AS VARCHAR) AS tenant_id, queue,\n object_type, object_id, method, args, run_at,\n priority, status, attempts, max_attempts, timeout,\n timeout_behavior, started_at, completed_at, last_error,\n result_pointer, task_id, task_owner_id, task_result,\n task_input_requests, task_input_responses, retry_strategy,\n worker_id, worker_heartbeat\n";
|
|
19
|
+
export declare const SMRT_JOB_PORTABLE_SELECT_COLUMNS = "\n CAST(id AS VARCHAR) AS id,\n slug, context, created_at, updated_at,\n CAST(tenant_id AS VARCHAR) AS tenant_id, queue,\n object_type, object_id, method, args, run_at,\n priority, status, attempts, max_attempts, timeout,\n timeout_behavior, started_at, completed_at, last_error,\n result_pointer, task_id, task_owner_id, task_result,\n task_input_requests, task_input_responses, retry_strategy,\n worker_id, worker_heartbeat, dedupe_key\n";
|
|
19
20
|
/**
|
|
20
21
|
* Persistent job record stored in the `_smrt_jobs` system table.
|
|
21
22
|
*
|
|
@@ -29,6 +30,8 @@ export declare const SMRT_JOB_PORTABLE_SELECT_COLUMNS = "\n CAST(id AS VARCHAR)
|
|
|
29
30
|
export declare class SmrtJob extends SmrtObject {
|
|
30
31
|
/** Tenant context captured for this job, if any */
|
|
31
32
|
tenantId: string | null | undefined;
|
|
33
|
+
/** Caller key retained as provenance; only pending/running jobs reserve it. */
|
|
34
|
+
dedupeKey: string | null;
|
|
32
35
|
/** Queue name for the job */
|
|
33
36
|
queue: string;
|
|
34
37
|
/** Type of object to invoke method on */
|
|
@@ -106,7 +109,7 @@ export declare class SmrtJob extends SmrtObject {
|
|
|
106
109
|
/**
|
|
107
110
|
* Mark the job for retry
|
|
108
111
|
*/
|
|
109
|
-
retry(): Promise<void>;
|
|
112
|
+
retry(options?: Pick<EnqueueJobOptions, 'transaction'>): Promise<void>;
|
|
110
113
|
/**
|
|
111
114
|
* Cancel the job
|
|
112
115
|
*/
|
|
@@ -120,6 +123,8 @@ export declare class SmrtJob extends SmrtObject {
|
|
|
120
123
|
* Job data type (for create operations)
|
|
121
124
|
*/
|
|
122
125
|
export interface SmrtJobData {
|
|
126
|
+
/** At most one pending/running job per effective tenant and key. */
|
|
127
|
+
dedupeKey?: string | null;
|
|
123
128
|
tenantId?: string | null;
|
|
124
129
|
queue?: string;
|
|
125
130
|
objectType: string;
|
|
@@ -153,6 +158,12 @@ export interface EnqueueJobOptions {
|
|
|
153
158
|
* (no-context / null tenant) jobs are always exempt.
|
|
154
159
|
*/
|
|
155
160
|
tenantJobCap?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Existing caller-owned transaction. All enqueue reads/writes use this handle;
|
|
163
|
+
* the caller must propagate failures and commit/rollback the transaction.
|
|
164
|
+
* Avoids nested transactions on engines without savepoints (DuckDB).
|
|
165
|
+
*/
|
|
166
|
+
transaction?: DatabaseInterface;
|
|
156
167
|
}
|
|
157
168
|
/**
|
|
158
169
|
* Options for listReady
|
|
@@ -160,6 +171,8 @@ export interface EnqueueJobOptions {
|
|
|
160
171
|
export interface ListReadyOptions {
|
|
161
172
|
limit?: number;
|
|
162
173
|
queues?: string[];
|
|
174
|
+
/** Allowed tenant identities; undefined selects all, [] selects none. */
|
|
175
|
+
tenantIds?: readonly (string | null)[];
|
|
163
176
|
}
|
|
164
177
|
/**
|
|
165
178
|
* Options for atomically claiming ready jobs.
|
|
@@ -184,10 +197,7 @@ export declare class SmrtJobCollection extends SmrtCollection<SmrtJob> {
|
|
|
184
197
|
/**
|
|
185
198
|
* List pending jobs ready to run
|
|
186
199
|
*/
|
|
187
|
-
listReady(options?:
|
|
188
|
-
limit?: number;
|
|
189
|
-
queues?: string[];
|
|
190
|
-
}): Promise<SmrtJob[]>;
|
|
200
|
+
listReady(options?: ListReadyOptions): Promise<SmrtJob[]>;
|
|
191
201
|
/**
|
|
192
202
|
* Atomically claim pending jobs ready to run for a worker.
|
|
193
203
|
*
|
|
@@ -248,6 +258,8 @@ export declare class SmrtJobCollection extends SmrtCollection<SmrtJob> {
|
|
|
248
258
|
* dedicated counter row, not an application-level lock.
|
|
249
259
|
*/
|
|
250
260
|
enqueueJob(data: SmrtJobData, options?: EnqueueJobOptions): Promise<SmrtJob>;
|
|
261
|
+
/** Persist once, without a second save racing a consumer's first claim. */
|
|
262
|
+
private createQueuedJob;
|
|
251
263
|
/**
|
|
252
264
|
* Get job statistics
|
|
253
265
|
*/
|
|
@@ -278,4 +290,17 @@ export declare class SmrtJobCollection extends SmrtCollection<SmrtJob> {
|
|
|
278
290
|
}): Promise<number>;
|
|
279
291
|
}
|
|
280
292
|
export default SmrtJob;
|
|
293
|
+
/** Internal SQL predicate shared by ready claims and worker recovery. */
|
|
294
|
+
export declare function jobTenantScope(tenantIds: readonly (string | null)[] | undefined): {
|
|
295
|
+
sql: string;
|
|
296
|
+
params: string[];
|
|
297
|
+
};
|
|
298
|
+
/** @internal Execution target of an AgentSchedule, independent of caller metadata names. */
|
|
299
|
+
export interface ScheduleJobTarget {
|
|
300
|
+
objectType: string;
|
|
301
|
+
objectId: string | null;
|
|
302
|
+
method: string;
|
|
303
|
+
}
|
|
304
|
+
/** @internal Count canonical occurrences and matching legacy target slots for admission/retry. */
|
|
305
|
+
export declare function countScheduleJobs(db: DatabaseInterface, scheduleId: string, tenant: string | null, target: ScheduleJobTarget, excludeJobId?: string): Promise<number>;
|
|
281
306
|
//# sourceMappingURL=smrt-job.d.ts.map
|
package/dist/smrt-job.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"smrt-job.d.ts","sourceRoot":"","sources":["../src/smrt-job.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"smrt-job.d.ts","sourceRoot":"","sources":["../src/smrt-job.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,qBAAqB,CAAC;AAC/D,OAAO,EAKL,cAAc,EACd,UAAU,EACV,KAAK,eAAe,EAErB,MAAM,0BAA0B,CAAC;AASlC,OAAO,KAAK,EAAE,iBA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AE,OAAO,CAAC;KAClB,GAAG,OAAO,CAAC,MAAM,CAAC;CAmDpB;AA6BD,eAAe,OAAO,CAAC;AAQvB,yEAAyE;AACzE,wBAAgB,cAAc,CAC5B,SAAS,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,GAAG,SAAS,GAChD;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAAE,CAiBnC;AAyFD,4FAA4F;AAC5F,MAAM,WAAW,iBAAiB;IAChC,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AA6FD,kGAAkG;AAClG,wBAAsB,iBAAiB,CACrC,EAAE,EAAE,iBAAiB,EACrB,UAAU,EAAE,MAAM,EAClB,MAAM,EAAE,MAAM,GAAG,IAAI,EACrB,MAAM,EAAE,iBAAiB,EACzB,YAAY,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,MAAM,CAAC,CAmBjB"}
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,14 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-jobs",
|
|
6
|
-
"packageVersion": "0.60.
|
|
6
|
+
"packageVersion": "0.60.15",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "d77d13a395ec25a6a8965bf9873bacfff4a7e8daa3aec99ac704f4e34e7c8e2b",
|
|
11
|
+
"packageJson": "f172ec015e4571acb80653c5799a89c122a8b97d0f7d8a81fd93a7206f2a0bba",
|
|
12
|
+
"agents": "c1ff25ca278665bd46d752e9ed562a93d484b07967114b4b772569d4cdea26eb",
|
|
13
|
+
"moduleDoc:agents/scheduling.md": "ac216e8c20d83488305303c27f1d114ca90e1f43a32bb6e085c8acac33c1e4bf"
|
|
13
14
|
},
|
|
14
15
|
"exports": [
|
|
15
16
|
".",
|
|
@@ -340,6 +341,55 @@
|
|
|
340
341
|
"tags": [],
|
|
341
342
|
"risks": []
|
|
342
343
|
},
|
|
344
|
+
{
|
|
345
|
+
"name": "SmrtJobDedupeSlot",
|
|
346
|
+
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobDedupeSlot",
|
|
347
|
+
"collection": "smrtjobdedupeslots",
|
|
348
|
+
"description": "Store-owned serialization row for a tenant-partitioned job deduplication key.",
|
|
349
|
+
"tableName": "_smrt_job_dedupe_slots",
|
|
350
|
+
"packageName": "@happyvertical/smrt-jobs",
|
|
351
|
+
"extends": "SmrtObject",
|
|
352
|
+
"fields": [
|
|
353
|
+
{
|
|
354
|
+
"name": "slotKey",
|
|
355
|
+
"type": "text",
|
|
356
|
+
"required": true,
|
|
357
|
+
"columnType": "TEXT"
|
|
358
|
+
},
|
|
359
|
+
{
|
|
360
|
+
"name": "jobId",
|
|
361
|
+
"type": "text",
|
|
362
|
+
"required": false,
|
|
363
|
+
"columnType": "TEXT"
|
|
364
|
+
}
|
|
365
|
+
],
|
|
366
|
+
"relationships": [],
|
|
367
|
+
"methods": [],
|
|
368
|
+
"surfaces": [],
|
|
369
|
+
"relationshipFeatures": [
|
|
370
|
+
"uuidColumns"
|
|
371
|
+
],
|
|
372
|
+
"tags": [],
|
|
373
|
+
"risks": []
|
|
374
|
+
},
|
|
375
|
+
{
|
|
376
|
+
"name": "SmrtJobDedupeSlotCollection",
|
|
377
|
+
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobDedupeSlotCollection",
|
|
378
|
+
"collection": "smrtjobdedupeslots",
|
|
379
|
+
"description": "Internal collection for provisioning the registered store-owned model.",
|
|
380
|
+
"tableName": "_smrt_job_dedupe_slots",
|
|
381
|
+
"packageName": "@happyvertical/smrt-jobs",
|
|
382
|
+
"extends": "SmrtCollection",
|
|
383
|
+
"fields": [],
|
|
384
|
+
"relationships": [],
|
|
385
|
+
"methods": [],
|
|
386
|
+
"surfaces": [],
|
|
387
|
+
"relationshipFeatures": [
|
|
388
|
+
"uuidColumns"
|
|
389
|
+
],
|
|
390
|
+
"tags": [],
|
|
391
|
+
"risks": []
|
|
392
|
+
},
|
|
343
393
|
{
|
|
344
394
|
"name": "SmrtJobEvent",
|
|
345
395
|
"qualifiedName": "@happyvertical/smrt-jobs:SmrtJobEvent",
|
|
@@ -613,6 +663,12 @@
|
|
|
613
663
|
"required": false,
|
|
614
664
|
"columnType": "UUID"
|
|
615
665
|
},
|
|
666
|
+
{
|
|
667
|
+
"name": "dedupeKey",
|
|
668
|
+
"type": "text",
|
|
669
|
+
"required": false,
|
|
670
|
+
"columnType": "TEXT"
|
|
671
|
+
},
|
|
616
672
|
{
|
|
617
673
|
"name": "queue",
|
|
618
674
|
"type": "text",
|
|
@@ -785,6 +841,9 @@
|
|
|
785
841
|
{
|
|
786
842
|
"name": "retry",
|
|
787
843
|
"async": true,
|
|
844
|
+
"params": [
|
|
845
|
+
"options?: Pick<EnqueueJobOptions, 'transaction'>"
|
|
846
|
+
],
|
|
788
847
|
"returns": "Promise<void>"
|
|
789
848
|
},
|
|
790
849
|
{
|
|
@@ -940,7 +999,7 @@
|
|
|
940
999
|
"name": "listReady",
|
|
941
1000
|
"async": true,
|
|
942
1001
|
"params": [
|
|
943
|
-
"options?:
|
|
1002
|
+
"options?: ListReadyOptions"
|
|
944
1003
|
],
|
|
945
1004
|
"returns": "Promise<SmrtJob[]>"
|
|
946
1005
|
},
|
|
@@ -1279,9 +1338,16 @@
|
|
|
1279
1338
|
"junctionCollections": 0,
|
|
1280
1339
|
"hierarchicalObjects": 0,
|
|
1281
1340
|
"polymorphicAssociations": 0,
|
|
1282
|
-
"uuidColumns":
|
|
1341
|
+
"uuidColumns": 20
|
|
1283
1342
|
},
|
|
1284
|
-
"agentDoc": "# @happyvertical/smrt-jobs\n\nBackground job execution with persistent queue, scheduling, and fluent builder API.\n\n## Architecture\n\n```\nSmrtObject.bg('method') → SmrtJob (in _smrt_jobs) → TaskRunner picks up → executes via ObjectRegistry\nAgentSchedule (cron) → ScheduleRunner creates SmrtJob → TaskRunner executes → ScheduleRunner updates\nTaskRunner.start() → SmrtWorker lease (in _smrt_workers) → recovery keys on worker liveness, not heartbeat\n```\n\n## SmrtJob\n\nPersistent in `_smrt_jobs`. Fields: `queue` (default), `objectType`, `objectId`, `method`, `args`, `runAt`, `priority` (higher=sooner), `status`, `attempts`/`maxAttempts`, `timeout` (default 5min), `retryStrategy`, `workerId` (the owning runner's incarnation key), `workerHeartbeat` (telemetry only — no longer gates recovery).\n\nStatus: `pending → running → completed/failed/cancelled`.\n\n## TaskRunner\n\nPolling-based execution engine. Config: `concurrency` (5), `pollInterval` (1s), `idlePollInterval` (defaults to 20× `pollInterval`), `heartbeatInterval` (30s, telemetry only), `leaseTtlMs` (30s), `leaseTickMs` (10s), `shutdownTimeout` (30s). Empty claims back off exponentially to `idlePollInterval`; any claimed work, capacity pressure, or poll error resets to `pollInterval`. Every delay is capped at the effective worker lease TTL, including an oversized base interval; recovery sweep spacing stays TTL-bounded (plus query/event-loop time). Polling intervals must be finite positive milliseconds within the Node timer range. `stop()` waits (within `shutdownTimeout`) for an in-flight poll as well as active jobs; a poll that resumes after `stop()` began returns before claiming, and over-claimed rows are released both before and after the drain (#3148).\n\n1. `start()` calls `assertReady()` (fail fast if `_smrt_workers` unmigrated), registers a seeded `SmrtWorker` lease, and adds its worker key to the process-global live set — all **before** polling\n2. Polls `claimReady()` to atomically claim at most the free slots (`concurrency - active`) of pending jobs (`runAt <= NOW`, ordered by `priority DESC, runAt ASC, created_at ASC, id ASC`). On PostgreSQL the candidates come from a `MATERIALIZED` CTE joined to the UPDATE; never claim with `WHERE id IN (SELECT … LIMIT n FOR UPDATE SKIP LOCKED)` — a nested-loop semi join rescans it per outer row and takes the whole backlog (#3145). The runner also never starts more than the free slots and returns any surplus claim to `pending` with its attempt restored\n3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`\n4. Resolves class via `ObjectRegistry.getClass(objectType)`. Object-bound jobs\n pass `objectId` to the constructor and let `initialize()` perform the single\n canonical hydration. Runner-owned `db`, `id`, and hydration options cannot be\n overridden by agent config; missing persisted targets fail before method\n dispatch. Jobs without `objectId` construct a static-like instance\n5. **Internal args**: `_agentConfig` and `_scheduleId` stripped from args before calling method. `_agentConfig` goes through `resolveLazyConfig()` with this job's identity as resolver context (`agentId` = `objectId`, qualified `agentClass`, `tenantId`, `scheduleId`, `jobId`; #2806). That identity comes from the job row only, never from scanning other agents. `scheduleId` is echoed from args unverified and is informational only\n6. Calls the requested method on the initialized instance\n7. Terminal/retry writes are **conditional** (`WHERE worker_id=? AND status='running'`) so a recovered row is never stomped\n8. Retry: uses strategy from `@happyvertical/jobs`, schedules future `runAt` on failure. A handler error's own hints win (#3308): `error.retryable === false` fails the job terminally; a positive `error.retryAfterMs` (capped at 24 h) is a floor on the strategy's delay\n9. Events: `job:started`, `job:completed`, `job:failed`, `job:retrying`, `runner:started/stopped`\n\nA rejection from `processJob` can never escape the poll loop: the caller attaches `.catch(e => emit('runner:error', e))` and the error path (`handleJobError`) is itself try/caught, so a failure-path write that rejects is surfaced as a `runner:error` event instead of crashing the worker with an unhandled rejection.\n\n## Timeouts & at-least-once\n\n**Execution is at-least-once, never exactly-once. Make job handlers idempotent.**\n\nA job `timeout` only races the handler's promise — JavaScript cannot preempt an already-running function. When a handler exceeds its timeout:\n\n- The job is **failed terminally and NOT auto-retried** (a timed-out handler is still running; re-queueing it would let a second worker run a concurrent duplicate). This narrows, but does not eliminate, the overlap window — the orphaned handler keeps running until it returns on its own.\n- The orphaned handler's eventual terminal write is dropped by the ownership guard (`WHERE worker_id=? AND status='running'`), so it cannot resurrect the failed row — but any **side effects** it performs (external API calls, writes to other tables) still happen.\n- Key any non-idempotent work by `context.job.jobId` or a caller-supplied idempotency key.\n\n`timeoutBehavior` (persisted + shown in the UI) is now honored:\n\n- **`'fail'`** (default): on timeout the job fails (and, per above, is not retried).\n- **`'warn'`**: the handler is **not** raced against the timeout — it runs to completion, and at the deadline the runner logs a warning and emits a `timeout-warning` job event. A slow-but-successful handler still completes successfully.\n- **`'kill'`**: treated identically to `'fail'`. In-process JavaScript has no thread interruption, so a true \"kill\" of a running handler is impossible without worker isolation; this value is honest that it only fails the job row, it does not stop the handler. Prefer `'fail'` unless you specifically want the label.\n\n## Cooperative cancellation (`context.signal`)\n\nHandlers receive `context.signal`, a plain `AbortSignal` (pass it to `fetch` or an LLM SDK). It aborts when:\n\n- the job row is observed as `cancelled` while the handler runs (reason: exported `JobCancelledError`). The runner polls the owned row every `cancelPollInterval` (default 1s) with one read-only `SELECT status`; unref'd and cleared in `finally`. Poll errors are ignored.\n- the job times out under `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`), so the orphaned handler can stop. `'warn'` never aborts.\n\nCooperative only: aborting changes no lifecycle state, retry policy, terminal-write guard or event. A handler that ignores the signal behaves exactly as before; one that rejects with the abort reason cannot overwrite `cancelled`/`failed` (the `WHERE worker_id=? AND status='running'` guard drops its terminal write). Not aborted on runner shutdown. `isRunnerExecutionContext` and MCP-task invocations are unchanged; they receive the same `signal`.\n\n**Why no dedup key / usage record here:** a caller dedup key and per-attempt usage live in `smrt-education` (generation jobs are unique on `(tenant_id, request_key)` with replay; generation usage records hold input/output tokens, cost and `usageJson`). Jobs only owns execution and cancellation.\n\n## Worker liveness & recovery (#1474)\n\nRecovery keys on **worker-process liveness**, never per-job heartbeat freshness (a CPU-bound synchronous handler used to starve the heartbeat and false-recover its own running jobs).\n\n- **`SmrtWorker` / `_smrt_workers`**: one lease row per runner *incarnation* (`workerId` is per-incarnation unique via `createWorkerKey`, so a restart never looks like it still owns the previous crash's jobs). `leaseExpiresAt` is a `datetime` (an integer epoch-ms column overflows `int4`/`INT32` on Postgres/DuckDB). Stage 1 writes/compares it against the host clock — the same approach the old heartbeat recovery used, so it's no more skew-sensitive than the code it replaced.\n- **`SmrtWorker.queues`** (nullable JSON `string[]`, #3902): the runner's configured `queues`, written at `registerWorker` and re-written on every lease renewal (main-loop and off-loop ticker). `SmrtWorkerCollection.liveWorkerKeysForQueue(queue)` returns fresh-lease workers that poll a queue; rows with `queues = null` (older runners, schedule runners) never match. Existing databases need `smrt db:migrate` (additive column) before an upgraded runner starts.\n- **Process-global live set** (`worker-liveness.ts`, `globalThis.__smrtLiveWorkers`): checked synchronously, so it can't be starved by a blocked loop. Covers all same-process topologies.\n- **Off-loop ticker** (`worker-liveness-ticker.ts` + `worker-liveness-thread.ts`): for engines a second connection can reach (Postgres, file-backed SQLite — `offLoopEligible()`), `start()` spawns a `node:worker_threads` ticker that renews the lease on its own thread, so a CPU-bound synchronous handler on the main loop can't starve it. In-memory SQLite / DuckDB, a thread-spawn failure, a start-handshake timeout, or the thread dying mid-run all fall back to main-loop renewal; the in-process live set keeps same-process correct regardless. The worker entry is a separate build entry resolved via `import.meta.resolve('@happyvertical/smrt-jobs/worker-liveness-thread')`. On PostgreSQL the ticker opens a bounded one-client pool (`livenessConnectionOptions()`: `max: 1`, core's runtime timeouts, no `dbid`), never a second default-sized pool (#3046).\n- **Recovery rule** (both runners): a `running` job is orphaned iff its worker is *not alive* = not in the live set **and** no fresh `_smrt_workers` lease. The live set takes precedence over a stale lease. TaskRunner also never recovers a job in its own `activeJobs`. If `_smrt_workers` is absent, recovery skips lease checks (never mass-recovers). Recovery is swept at most once per lease tick, and terminal/recovery writes use `RETURNING id` (not `rowCount`, which DuckDB/JSON adapters always report as ≥1).\n- **Lease clock**: the lease is compared against the host clock (same as the old heartbeat; fine with NTP + a 30s TTL). A dead process stops renewing and the lease expires within its TTL — that is how recovery detects death. (Instant cross-process detection via Postgres session advisory locks was prototyped on `@happyvertical/sql`'s `acquireSession()` but deferred — treating a free lock as proof-of-death false-recovers any worker legitimately in main-loop fallback mode.)\n\n## ScheduleRunner\n\nPolls `_smrt_agent_schedules` every 60s for due entries. Creates SmrtJob with `queue='agents'`, `priority=75`. Wires to TaskRunner events for completion/failure tracking. Slot reconciliation keys on worker liveness (it has no in-process active-job set, so the lease/live-set is its whole mechanism).\n\nThe job is enqueued **before** `next_run` is advanced and `running_count` is incremented: a transient enqueue failure (tenant-cap hit, DB blip) therefore leaves `next_run` and `status='active'` untouched so the same due slot is retried on the next poll, rather than losing the slot and disabling the schedule.\n\n`next_run` is always recomputed from *now*, never from the previous `next_run` — this is **fire-once-forward**: runs that came due while the runner was down are not caught up, only the next future occurrence fires. There is no missed-run backfill.\n\nCustom cron parser (`getNextCronDate(cron, timezone?)`): 5-field (minute hour dom month dow); `*`, ranges, lists, steps supported, each list term matched on its own. Fields match the wall clock of the schedule's IANA `timezone` (`Intl.DateTimeFormat`, DST-correct, no dependency); the re-arm passes the row's `timezone`, and a NULL/blank zone falls back to the column default `UTC`. Unknown zones throw `Invalid cron timezone`; the runner moves a row whose cron or zone is invalid to `status='error'` with `last_error`, since retrying it every poll cannot succeed. Only an omitted argument uses the host process zone (legacy; `smrt-reports` still relies on it). DST follows Vixie cron: fixed-time crons (no `*` in minute or hour) run once per day, a gap-skipped wall time runs shifted forward by the gap, a repeated one only at its first occurrence; wildcard crons follow elapsed time (gap minutes skipped, the repeated hour runs again) (#3859).\n\n## JobBuilder — Fluent API\n\n```typescript\nconst handle = await doc.background('analyze', { detailed: true })\n .delay('5m').priority('high').retries(5).queue('analysis').timeout(600000).enqueue();\n\nawait handle.wait({ timeout: 60000, pollInterval: 100 }); // polling-based\n```\n\n## Durable forge projections\n\n`ForgeDeliveryCollection` owns the provider-neutral delivery inbox in\n`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter\ntransitions and monotonic checkpoints in\n`_smrt_forge_projection_checkpoints`.\n\n- Inbox identity is `(tenant_id, provider, delivery_id)`.\n- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or\n `claimReady`) so each claims and dead-letters only its own deliveries;\n unfiltered claims take every provider (smrt-commerce billing uses\n `<name>-billing:<sellerTenantId>`, #3060).\n- `claimReady` leases exactly one delivery; PostgreSQL uses the same\n `MATERIALIZED` CTE claim as jobs (#3105).\n- Tenant-facing accept/replay requires ambient tenant context. Worker claim is\n cross-tenant, then runtime restores the captured context before observation.\n Reads in the accept path go through the tenant-scoped collection (`list()`),\n so intake works under the interceptor's `rawQueryPolicy: 'throw'` production\n default without a bypass (#3100); keep new tenant-facing reads that way.\n- Projection callbacks must write through `ForgeProjectionContext.db`; the\n application projection, checkpoint, and inbox completion share one\n transaction.\n- Observation identity is tracker-independent\n `(projection, subjectKey, version)`. Equal or older versions are acknowledged\n without reapplying.\n- Lease-token conditions guard every terminal/failure write. Expired final\n attempts become replayable `dead_letter` rows, and persisted errors are\n redacted.\n- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit\n tenant-scoped operator action.\n\n`bg()` is shorthand: `await doc.bg('analyze', args)` → enqueues immediately, returns JobHandle.\n\n## withBackgroundJobs(Class)\n\nMixin that adds `bg()` and `background()` to any SmrtObject. Uses WeakMap for collection caching per DB instance.\n\n## Background policy (`background-policy.ts`, S5 audit #1402)\n\nThree opt-in guards, all owned **and enforced here**. Other packages apply the\neligibility marker (`reports`, `support`, `fields`, the MCP conformance\nfixture), but nothing outside this package acts on it — `TaskRunner` is the only\nreader. In particular `@happyvertical/smrt-agents` has no reference to any of\nthese guards and does not depend on this package, so marking a method does not\nchange what the agents runtime will dispatch.\n\n- `clampRetries()` / `MAX_JOB_RETRIES` (25): a requested retry count above the\n ceiling is clamped, not rejected.\n- `assertWithinTenantCreationCap(tenantId, current, cap)` /\n `DEFAULT_TENANT_JOB_CAP` (10 000): throws `TenantJobCapExceededError` when the\n tenant's count of non-terminal jobs is already at or above the cap. Applied in\n `SmrtJobCollection.enqueueJob()` (`smrt-job.ts`), which is the single choke\n point for the builder and `ScheduleRunner`; a `null` tenant and a `cap <= 0`\n both skip the check. Deliberately not serialized — concurrent enqueues can\n overshoot by the number of in-flight creators (see the method's own comment).\n- `@backgroundEligible()` / `markBackgroundEligible()` /\n `isBackgroundEligibleMethod()`: an allowlist of methods `TaskRunner` may\n dispatch, enforced at exactly one call site (`runner.ts`, after the method\n lookup). **Restrictive, not enabling** — a class with no marked methods allows\n any of its methods, and the first mark makes the set exhaustive, excluding\n every sibling method. Adding the decorator to one method of an existing class\n is therefore a behaviour change for the rest of it.\n\n## Terminal outcomes (#3696)\n\nTerminal state is authoritative together with its versioned event. Completion,\npermanent failure, timeout, stale-worker recovery, and cancellation update the\nowned `_smrt_jobs` row and append the safe `_smrt_job_events` projection in one\ndatabase transaction. If either write fails, neither commits. Conditional\nownership/status predicates prevent a lost race from appending an event.\nBuild the event from the conditional update's returned row, not a caller\nsnapshot, and bind that update to the row's tenant. Public cancellation must\nretain ambient-tenant isolation; only explicit bypass contexts may cross it.\nRetries are deliberately excluded until a later terminal transition. Ordinary\nprogress, logs, start, and retry telemetry remain best-effort.\n\n`SmrtJobEventCollection.listTerminalOutcomes()` requires an explicit tenant\n(`null` means global), reads newest-first, scans at most 1,000 candidates, and\nreturns only the safe versioned terminal shape. Never add job arguments,\nobject IDs, results, raw errors, or stacks to that shape. Applications must\nintersect job IDs with their own authorized ownership records; queue/object\ntype/method filters narrow the projection but do not authorize it.\n\n## Retention (#2375)\n\n`_smrt_jobs` and `_smrt_job_events` are append-only in practice — `cleanup()`\nexisted but nothing ever called it, and job events (one row per log line and\nprogress tick) had no prune path at all. `src/retention.ts` contributes both to\nthe framework retention sweep in `@happyvertical/smrt-core`.\n\n- `TaskRunner` starts a sweeper by default. `retention: false` opts out;\n `retention: { intervalMs, policy, jobs }` tunes it. The **first sweep is one\n interval after `start()`, never at start** — a crash-looping worker must not\n become a delete loop, and a short-lived runner must exit having deleted\n nothing. `stop()` only clears the timer — it does **not** unregister the job\n tasks. The package entry point (`index.ts`) registers them unconditionally\n on import, so \"this process loaded `@happyvertical/smrt-jobs`\" is the\n contract that contributes them, not \"a sweeper happens to be running\";\n `unregisterJobRetentionTasks()` is the explicit opt-out for callers that\n want a clean registry (tests, teardown).\n- Windows (`DEFAULT_JOB_RETENTION`): completed/cancelled 7 days, failed 30\n days, events 30 days, 10 000 job rows per sweep. Events deliberately outlive\n the jobs they describe, so a job row removed at 7 days still has a readable\n log for another three weeks. `SmrtJobEvent.jobId` is therefore the explicit\n same-package archival exception: `@foreignKey('SmrtJob', { constraint:\n false })` retains runtime relationship metadata and its index without a\n physical database constraint that would block parent pruning.\n- `cleanup()` counts before deleting (`rowCount` is unreliable across engines)\n and honours `dryRun`, which is what makes `smrt db:prune --dry-run` an exact\n preview. Its `(status, completed_at)` predicate is indexed by\n `ensureJobsSystemTableCompatibility()`, which this collection runs on every\n `initialize()` — bootstrap cannot do it, because `_smrt_jobs` does not exist\n yet when bootstrap runs.\n- `cleanup({})` with no cutoff returns 0. It must never be read as \"delete\n everything\".\n\n## Gotchas\n\n- The shared claim/recovery projection casts both job and tenant UUIDs to strings; DuckDB otherwise returns native UUID objects. Preserve NULL for global jobs.\n\n- **Cron zone comes from the row**: `_smrt_agent_schedules.timezone` (default `UTC`), not the host `TZ`; no missed-run catch-up (fire-once-forward)\n- **At-least-once execution**: a timeout cannot preempt a running handler; timed-out jobs fail without retry but the handler keeps running — make handlers idempotent (see \"Timeouts & at-least-once\")\n- **No dead letter queue**: failed jobs stay in DB with `status='failed'` — manual intervention\n- **Forge deliveries are not SmrtJobs**: they use their own replayable\n dead-letter inbox and projection checkpoint contract. Do not enqueue provider\n deliveries as generic background jobs.\n- **Result storage**: `resultPointer` is just a string — app must implement result backend\n- **Lazy builder**: `background()` returns builder — nothing happens until `enqueue()`\n- **wait() is polling**: JobHandle.wait() polls DB every 100ms (configurable)\n- **Migrate before start()**: `TaskRunner.start()` throws if `_smrt_workers` is missing — run `smrt db:migrate` after upgrading. Tables are never created at runtime.\n- **Recovery is liveness-based**: don't reintroduce heartbeat-threshold recovery; a blocked event loop must not look dead (see Worker liveness section, #1474)\n",
|
|
1343
|
+
"agentDoc": "# @happyvertical/smrt-jobs\n\nBackground job execution with persistent queue, scheduling, and fluent builder API.\n\n## Architecture\n\n```\nSmrtObject.bg('method') → SmrtJob (in _smrt_jobs) → TaskRunner picks up → executes via ObjectRegistry\nAgentSchedule (cron) → ScheduleRunner creates SmrtJob → TaskRunner executes → ScheduleRunner updates\nTaskRunner.start() → SmrtWorker lease (in _smrt_workers) → recovery keys on worker liveness, not heartbeat\n```\n\n## SmrtJob\n\nPersistent in `_smrt_jobs`. Fields: `queue` (default), `objectType`, `objectId`, `method`, `args`, `runAt`, `priority` (higher=sooner), `status`, `attempts`/`maxAttempts`, `timeout` (default 5min), `retryStrategy`, `workerId` (the owning runner's incarnation key), `workerHeartbeat` (telemetry only — no longer gates recovery).\n\nStatus: `pending → running → completed/failed/cancelled`.\n\n## TaskRunner\n\nPolling-based execution engine. Config: `concurrency` (5), `pollInterval` (1s), `idlePollInterval` (defaults to 20× `pollInterval`), `heartbeatInterval` (30s, telemetry only), `leaseTtlMs` (30s), `leaseTickMs` (10s), `shutdownTimeout` (30s). Empty claims back off exponentially to `idlePollInterval`; any claimed work, capacity pressure, or poll error resets to `pollInterval`. Every delay is capped at the effective worker lease TTL, including an oversized base interval; recovery sweep spacing stays TTL-bounded (plus query/event-loop time). Polling intervals must be finite positive milliseconds within the Node timer range. `stop()` waits (within `shutdownTimeout`) for an in-flight poll as well as active jobs; a poll that resumes after `stop()` began returns before claiming, and over-claimed rows are released both before and after the drain (#3148).\n\nOptional `tenantIds` scopes both atomic ready claims and orphan recovery before\nownership or terminal-state writes (`undefined` means all; `[]` means none;\n`null` includes global jobs). Recovery also respects configured queues. Scoped\nrunners default `retention` to `false`, since the system-wide maintenance sweep\nhas no tenant filter; opt into that sweep only in an authorized maintenance host.\n`ClaimReadyOptions` and `ListReadyOptions` accept the same tenant scope. Queue\nlease advertising remains queue-level; it does not prove per-tenant availability.\n\n1. `start()` calls `assertReady()` (fail fast if `_smrt_workers` unmigrated), registers a seeded `SmrtWorker` lease, and adds its worker key to the process-global live set — all **before** polling\n2. Polls `claimReady()` to atomically claim at most the free slots (`concurrency - active`) of pending jobs (`runAt <= NOW`, ordered by `priority DESC, runAt ASC, created_at ASC, id ASC`). On PostgreSQL the candidates come from a `MATERIALIZED` CTE joined to the UPDATE; never claim with `WHERE id IN (SELECT … LIMIT n FOR UPDATE SKIP LOCKED)` — a nested-loop semi join rescans it per outer row and takes the whole backlog (#3145). The runner also never starts more than the free slots and returns any surplus claim to `pending` with its attempt restored\n3. Claim sets `status='running'`, `workerId=<incarnation key>`, heartbeat/start timestamps, and increments `attempts`\n4. Resolves class via `ObjectRegistry.getClass(objectType)`. Object-bound jobs\n pass `objectId` to the constructor and let `initialize()` perform the single\n canonical hydration. Runner-owned `db`, `id`, and hydration options cannot be\n overridden by agent config; missing persisted targets fail before method\n dispatch. Jobs without `objectId` construct a static-like instance\n5. **Internal args**: `_agentConfig` and `_scheduleId` stripped from args before calling method. `_agentConfig` goes through `resolveLazyConfig()` with this job's identity as resolver context (`agentId` = `objectId`, qualified `agentClass`, `tenantId`, `scheduleId`, `jobId`; #2806). That identity comes from the job row only, never from scanning other agents. `scheduleId` is echoed from args unverified and is informational only\n6. Calls the requested method on the initialized instance\n7. Terminal/retry writes are **conditional** (`WHERE worker_id=? AND status='running'`) so a recovered row is never stomped\n8. Retry: uses strategy from `@happyvertical/jobs`, schedules future `runAt` on failure. A handler error's own hints win (#3308): `error.retryable === false` fails the job terminally; a positive `error.retryAfterMs` (capped at 24 h) is a floor on the strategy's delay\n9. Events: `job:started`, `job:completed`, `job:failed`, `job:retrying`, `runner:started/stopped`\n\nA rejection from `processJob` can never escape the poll loop: the caller attaches `.catch(e => emit('runner:error', e))` and the error path (`handleJobError`) is itself try/caught, so a failure-path write that rejects is surfaced as a `runner:error` event instead of crashing the worker with an unhandled rejection.\n\n## Timeouts & at-least-once\n\n**Execution is at-least-once, never exactly-once. Make job handlers idempotent.**\n\nA job `timeout` only races the handler's promise — JavaScript cannot preempt an already-running function. When a handler exceeds its timeout:\n\n- The job is **failed terminally and NOT auto-retried** (a timed-out handler is still running; re-queueing it would let a second worker run a concurrent duplicate). This narrows, but does not eliminate, the overlap window — the orphaned handler keeps running until it returns on its own.\n- The orphaned handler's eventual terminal write is dropped by the ownership guard (`WHERE worker_id=? AND status='running'`), so it cannot resurrect the failed row — but any **side effects** it performs (external API calls, writes to other tables) still happen.\n- Key any non-idempotent work by `context.job.jobId` or a caller-supplied idempotency key.\n\n`timeoutBehavior` (persisted + shown in the UI) is now honored:\n\n- **`'fail'`** (default): on timeout the job fails (and, per above, is not retried).\n- **`'warn'`**: the handler is **not** raced against the timeout — it runs to completion, and at the deadline the runner logs a warning and emits a `timeout-warning` job event. A slow-but-successful handler still completes successfully.\n- **`'kill'`**: treated identically to `'fail'`. In-process JavaScript has no thread interruption, so a true \"kill\" of a running handler is impossible without worker isolation; this value is honest that it only fails the job row, it does not stop the handler. Prefer `'fail'` unless you specifically want the label.\n\n## Cooperative cancellation (`context.signal`)\n\nHandlers receive `context.signal`, a plain `AbortSignal` (pass it to `fetch` or an LLM SDK). It aborts when:\n\n- the job row is observed as `cancelled` while the handler runs (reason: exported `JobCancelledError`). The runner polls the owned row every `cancelPollInterval` (default 1s) with one read-only `SELECT status`; unref'd and cleared in `finally`. Poll errors are ignored.\n- the job times out under `timeoutBehavior` `'fail'`/`'kill'` (reason: `JobTimeoutError`), so the orphaned handler can stop. `'warn'` never aborts.\n\nCooperative only: aborting changes no lifecycle state, retry policy, terminal-write guard or event. A handler that ignores the signal behaves exactly as before; one that rejects with the abort reason cannot overwrite `cancelled`/`failed` (the `WHERE worker_id=? AND status='running'` guard drops its terminal write). Not aborted on runner shutdown. `isRunnerExecutionContext` and MCP-task invocations are unchanged; they receive the same `signal`.\n\n**Domain request identity / usage:** `smrt-education` still owns generation request replay and per-attempt usage. The generic store dedupe key below only reserves one nonterminal job; it never replaces domain idempotency or usage records.\n\n## Worker liveness & recovery (#1474)\n\nRecovery keys on **worker-process liveness**, never per-job heartbeat freshness (a CPU-bound synchronous handler used to starve the heartbeat and false-recover its own running jobs).\n\n- **`SmrtWorker` / `_smrt_workers`**: one lease row per runner *incarnation* (`workerId` is per-incarnation unique via `createWorkerKey`, so a restart never looks like it still owns the previous crash's jobs). `leaseExpiresAt` is a `datetime` (an integer epoch-ms column overflows `int4`/`INT32` on Postgres/DuckDB). Stage 1 writes/compares it against the host clock — the same approach the old heartbeat recovery used, so it's no more skew-sensitive than the code it replaced.\n- **`SmrtWorker.queues`** (nullable JSON `string[]`, #3902): the runner's configured `queues`, written at `registerWorker` and re-written on every lease renewal (main-loop and off-loop ticker). `SmrtWorkerCollection.liveWorkerKeysForQueue(queue)` returns fresh-lease workers that poll a queue; rows with `queues = null` (older runners, schedule runners) never match. Existing databases need `smrt db:migrate` (additive column) before an upgraded runner starts.\n- **Process-global live set** (`worker-liveness.ts`, `globalThis.__smrtLiveWorkers`): checked synchronously, so it can't be starved by a blocked loop. Covers all same-process topologies.\n- **Off-loop ticker** (`worker-liveness-ticker.ts` + `worker-liveness-thread.ts`): for engines a second connection can reach (Postgres, file-backed SQLite — `offLoopEligible()`), `start()` spawns a `node:worker_threads` ticker that renews the lease on its own thread, so a CPU-bound synchronous handler on the main loop can't starve it. In-memory SQLite / DuckDB, a thread-spawn failure, a start-handshake timeout, or the thread dying mid-run all fall back to main-loop renewal; the in-process live set keeps same-process correct regardless. The worker entry is a separate build entry resolved via `import.meta.resolve('@happyvertical/smrt-jobs/worker-liveness-thread')`. On PostgreSQL the ticker opens a bounded one-client pool (`livenessConnectionOptions()`: `max: 1`, core's runtime timeouts, no `dbid`), never a second default-sized pool (#3046).\n- **Recovery rule** (both runners): a `running` job is orphaned iff its worker is *not alive* = not in the live set **and** no fresh `_smrt_workers` lease. The live set takes precedence over a stale lease. TaskRunner also never recovers a job in its own `activeJobs`. If `_smrt_workers` is absent, recovery skips lease checks (never mass-recovers). Recovery is swept at most once per lease tick, and terminal/recovery writes use `RETURNING id` (not `rowCount`, which DuckDB/JSON adapters always report as ≥1).\n- **Lease clock**: the lease is compared against the host clock (same as the old heartbeat; fine with NTP + a 30s TTL). A dead process stops renewing and the lease expires within its TTL — that is how recovery detects death. (Instant cross-process detection via Postgres session advisory locks was prototyped on `@happyvertical/sql`'s `acquireSession()` but deferred — treating a free lock as proof-of-death false-recovers any worker legitimately in main-loop fallback mode.)\n\n## ScheduleRunner\n\nTransactional schedule admission, tenant/type scopes, dedicated queues,\noccurrence metadata, retry/slot semantics, graceful drain, and tenant-partitioned\nnonterminal job keys are documented in [safe scheduling](agents/scheduling.md).\nRun `smrt db:migrate` before using the new job provenance and dedupe-slot schema.\n\nCustom cron parser (`getNextCronDate(cron, timezone?)`): 5-field (minute hour dom month dow); `*`, ranges, lists, steps supported, each list term matched on its own. Fields match the wall clock of the schedule's IANA `timezone` (`Intl.DateTimeFormat`, DST-correct, no dependency); the re-arm passes the row's `timezone`, and a NULL/blank zone falls back to the column default `UTC`. Unknown zones throw `Invalid cron timezone`; the runner moves a row whose cron or zone is invalid to `status='error'` with `last_error`, since retrying it every poll cannot succeed. Only an omitted argument uses the host process zone (legacy; `smrt-reports` still relies on it). DST follows Vixie cron: fixed-time crons (no `*` in minute or hour) run once per day, a gap-skipped wall time runs shifted forward by the gap, a repeated one only at its first occurrence; wildcard crons follow elapsed time (gap minutes skipped, the repeated hour runs again) (#3859).\n\n## JobBuilder — Fluent API\n\n```typescript\nconst handle = await doc.background('analyze', { detailed: true })\n .delay('5m').priority('high').retries(5).queue('analysis').timeout(600000).enqueue();\n\nawait handle.wait({ timeout: 60000, pollInterval: 100 }); // polling-based\n```\n\n## Durable forge projections\n\n`ForgeDeliveryCollection` owns the provider-neutral delivery inbox in\n`_smrt_forge_deliveries`; `ForgeProjectionRuntime` owns lease/retry/dead-letter\ntransitions and monotonic checkpoints in\n`_smrt_forge_projection_checkpoints`.\n\n- Inbox identity is `(tenant_id, provider, delivery_id)`.\n- Runtimes sharing the inbox pass `providers` (to `ForgeProjectionRuntime` or\n `claimReady`) so each claims and dead-letters only its own deliveries;\n unfiltered claims take every provider (smrt-commerce billing uses\n `<name>-billing:<sellerTenantId>`, #3060).\n- `claimReady` leases exactly one delivery; PostgreSQL uses the same\n `MATERIALIZED` CTE claim as jobs (#3105).\n- Tenant-facing accept/replay requires ambient tenant context. Worker claim is\n cross-tenant, then runtime restores the captured context before observation.\n Reads in the accept path go through the tenant-scoped collection (`list()`),\n so intake works under the interceptor's `rawQueryPolicy: 'throw'` production\n default without a bypass (#3100); keep new tenant-facing reads that way.\n- Projection callbacks must write through `ForgeProjectionContext.db`; the\n application projection, checkpoint, and inbox completion share one\n transaction.\n- Observation identity is tracker-independent\n `(projection, subjectKey, version)`. Equal or older versions are acknowledged\n without reapplying.\n- Lease-token conditions guard every terminal/failure write. Expired final\n attempts become replayable `dead_letter` rows, and persisted errors are\n redacted.\n- Generated API, CLI, and MCP surfaces stay disabled; replay is an explicit\n tenant-scoped operator action.\n\n`bg()` is shorthand: `await doc.bg('analyze', args)` → enqueues immediately, returns JobHandle.\n\n## withBackgroundJobs(Class)\n\nMixin that adds `bg()` and `background()` to any SmrtObject. Uses WeakMap for collection caching per DB instance.\n\n## Background policy (`background-policy.ts`, S5 audit #1402)\n\nThree opt-in guards, all owned **and enforced here**. Other packages apply the\neligibility marker (`reports`, `support`, `fields`, the MCP conformance\nfixture), but nothing outside this package acts on it — `TaskRunner` is the only\nreader. In particular `@happyvertical/smrt-agents` has no reference to any of\nthese guards and does not depend on this package, so marking a method does not\nchange what the agents runtime will dispatch.\n\n- `clampRetries()` / `MAX_JOB_RETRIES` (25): a requested retry count above the\n ceiling is clamped, not rejected.\n- `assertWithinTenantCreationCap(tenantId, current, cap)` /\n `DEFAULT_TENANT_JOB_CAP` (10 000): throws `TenantJobCapExceededError` when the\n tenant's count of non-terminal jobs is already at or above the cap. Applied in\n `SmrtJobCollection.enqueueJob()` (`smrt-job.ts`), which is the single choke\n point for the builder and `ScheduleRunner`; a `null` tenant and a `cap <= 0`\n both skip the check. Deliberately not serialized — concurrent enqueues can\n overshoot by the number of in-flight creators (see the method's own comment).\n- `@backgroundEligible()` / `markBackgroundEligible()` /\n `isBackgroundEligibleMethod()`: an allowlist of methods `TaskRunner` may\n dispatch, enforced at exactly one call site (`runner.ts`, after the method\n lookup). **Restrictive, not enabling** — a class with no marked methods allows\n any of its methods, and the first mark makes the set exhaustive, excluding\n every sibling method. Adding the decorator to one method of an existing class\n is therefore a behaviour change for the rest of it.\n\n## Terminal outcomes (#3696)\n\nTerminal state is authoritative together with its versioned event. Completion,\npermanent failure, timeout, stale-worker recovery, and cancellation update the\nowned `_smrt_jobs` row and append the safe `_smrt_job_events` projection in one\ndatabase transaction. If either write fails, neither commits. Conditional\nownership/status predicates prevent a lost race from appending an event.\nBuild the event from the conditional update's returned row, not a caller\nsnapshot, and bind that update to the row's tenant. Public cancellation must\nretain ambient-tenant isolation; only explicit bypass contexts may cross it.\nRetries are deliberately excluded until a later terminal transition. Ordinary\nprogress, logs, start, and retry telemetry remain best-effort.\n\n`SmrtJobEventCollection.listTerminalOutcomes()` requires an explicit tenant\n(`null` means global), reads newest-first, scans at most 1,000 candidates, and\nreturns only the safe versioned terminal shape. Never add job arguments,\nobject IDs, results, raw errors, or stacks to that shape. Applications must\nintersect job IDs with their own authorized ownership records; queue/object\ntype/method filters narrow the projection but do not authorize it.\n\n## Retention (#2375)\n\n`_smrt_jobs` and `_smrt_job_events` are append-only in practice — `cleanup()`\nexisted but nothing ever called it, and job events (one row per log line and\nprogress tick) had no prune path at all. `src/retention.ts` contributes both to\nthe framework retention sweep in `@happyvertical/smrt-core`.\n\n- `TaskRunner` starts a sweeper by default. `retention: false` opts out;\n `retention: { intervalMs, policy, jobs }` tunes it. The **first sweep is one\n interval after `start()`, never at start** — a crash-looping worker must not\n become a delete loop, and a short-lived runner must exit having deleted\n nothing. `stop()` only clears the timer — it does **not** unregister the job\n tasks. The package entry point (`index.ts`) registers them unconditionally\n on import, so \"this process loaded `@happyvertical/smrt-jobs`\" is the\n contract that contributes them, not \"a sweeper happens to be running\";\n `unregisterJobRetentionTasks()` is the explicit opt-out for callers that\n want a clean registry (tests, teardown).\n- Windows (`DEFAULT_JOB_RETENTION`): completed/cancelled 7 days, failed 30\n days, events 30 days, 10 000 job rows per sweep. Events deliberately outlive\n the jobs they describe, so a job row removed at 7 days still has a readable\n log for another three weeks. `SmrtJobEvent.jobId` is therefore the explicit\n same-package archival exception: `@foreignKey('SmrtJob', { constraint:\n false })` retains runtime relationship metadata and its index without a\n physical database constraint that would block parent pruning.\n- `cleanup()` counts before deleting (`rowCount` is unreliable across engines)\n and honours `dryRun`, which is what makes `smrt db:prune --dry-run` an exact\n preview. Its `(status, completed_at)` predicate is indexed by\n `ensureJobsSystemTableCompatibility()`, which this collection runs on every\n `initialize()` — bootstrap cannot do it, because `_smrt_jobs` does not exist\n yet when bootstrap runs.\n- `cleanup({})` with no cutoff returns 0. It must never be read as \"delete\n everything\".\n\n## Gotchas\n\n- The shared claim/recovery projection casts both job and tenant UUIDs to strings; DuckDB otherwise returns native UUID objects. Preserve NULL for global jobs.\n\n- **Cron zone comes from the row**: `_smrt_agent_schedules.timezone` (default `UTC`), not the host `TZ`; no missed-run catch-up (fire-once-forward)\n- **At-least-once execution**: a timeout cannot preempt a running handler; timed-out jobs fail without retry but the handler keeps running — make handlers idempotent (see \"Timeouts & at-least-once\")\n- **No dead letter queue**: failed jobs stay in DB with `status='failed'` — manual intervention\n- **Forge deliveries are not SmrtJobs**: they use their own replayable\n dead-letter inbox and projection checkpoint contract. Do not enqueue provider\n deliveries as generic background jobs.\n- **Result storage**: `resultPointer` is just a string — app must implement result backend\n- **Lazy builder**: `background()` returns builder — nothing happens until `enqueue()`\n- **wait() is polling**: JobHandle.wait() polls DB every 100ms (configurable)\n- **Migrate before start()**: `TaskRunner.start()` throws if `_smrt_workers` is missing — run `smrt db:migrate` after upgrading. Tables are never created at runtime.\n- **Recovery is liveness-based**: don't reintroduce heartbeat-threshold recovery; a blocked event loop must not look dead (see Worker liveness section, #1474)\n",
|
|
1344
|
+
"moduleDocs": [
|
|
1345
|
+
{
|
|
1346
|
+
"path": "agents/scheduling.md",
|
|
1347
|
+
"module": "scheduling",
|
|
1348
|
+
"content": "# Safe scheduling and job deduplication\n\nPolls `_smrt_agent_schedules` every 60s. Due selection and the transactional\nclaim both apply optional `agentTypes` and `tenantIds` scopes (`[]` admits none;\n`undefined` preserves system-wide operation). `queue` defaults to `agents`.\nConfigure a dedicated task-worker queue and exact scopes for a host that must\nonly run its own scheduled operation.\n\nAdmission locks and re-reads the authoritative schedule row, rechecks enabled /\nactive / due occurrence / capacity, then inserts the job and advances `next_run`\nin the same transaction. Competing runners cannot consume the same occurrence.\nA failed enqueue or process crash before commit rolls everything back; the next\npoll can retry the unchanged due slot. After commit the durable job belongs to\nTaskRunner's existing lease/retry/terminal recovery contract. ScheduleRunner\nnever independently fails a TaskRunner-owned job. Pending jobs (including delayed\nretries) and running jobs both occupy `maxConcurrent` slots. Reconciliation takes\nthe same schedule-row lock, so a stale count cannot erase a new admission.\n\n`args._scheduledFor` is the admitted original `next_run` as a UTC ISO instant,\nretained across task attempts and passed to the handler. `_scheduleId` remains\ninternal metadata; neither field grants authority. `method_args` may not supply\n`_scheduledFor`, `_scheduleId`, or `_agentConfig`. The handler must resolve current\nauthority and implement domain idempotency. `stop()` prevents new admissions and\nwaits for the in-flight poll/transaction before resolving; stop the scheduler\nbefore draining its TaskRunner.\n\n`next_run` is recomputed from *now*, never from the previous slot: this is\n**fire-once-forward**. One overdue occurrence is admitted, then the next future\nzoned cron time is armed. There is no missed-run backfill. One admission per\noccurrence differs from no overlapping executions: `maxConcurrent = 1` prevents\nmultiple pending/running jobs for that schedule; a job dedupe key can serialize\na broader caller-defined resource. Neither promise preempts an orphaned timed-out\nhandler (see the at-least-once contract above).\n\n### Store deduplication (#2994)\n\n`SmrtJobCollection.enqueueJob({ ..., dedupeKey })` reserves at most one\npending/running job per effective tenant and nonblank key (at most 512 chars).\nConcurrent calls return the existing job unchanged, even if the later arguments\ndiffer. Terminal completion/failure/cancellation permits the next enqueue.\nOrdinary retry delays retain the reservation; manual retry of an older terminal\njob refuses while a newer job reserves its key. This is in-flight suppression,\nnot permanent occurrence/request replay or an authorization boundary.\n\nThe registered `_smrt_job_dedupe_slots` model owns the database uniqueness and\nrow lock; the opaque hash partitions keys by tenant, including global NULL.\nThe nullable indexed `SmrtJob.dedupeKey` retains provenance. Migrate before using\nupgraded workers (`smrt db:migrate`); no partial-index dependency on DuckDB.\nSlots retain one pointer per distinct key, including after terminal-job retention\nprunes the referenced row. Use stable resource keys rather than one-shot tokens.\nGenerated slot API/CLI/MCP access is disabled. Callers must use `enqueueJob` and\npublic retry/cancel APIs; direct model/SQL lifecycle writes bypass store guards.\n\n`enqueueJob(data, { transaction: tx })` uses an existing caller-owned transaction\nfor every read/write and opens no nested transaction (DuckDB has no savepoints).\nThe caller must propagate failures and commit/roll back `tx`. Without that option\na keyed enqueue opens its own transaction. Returned models use the caller's\nconnection, never an ended internal transaction. Enqueue persists once; a second\nsave must never race a consumer's first claim.\n\n## Exact occurrence integrity\n\nA trusted host can opt into `ScheduleRunnerConfig.occurrenceSigner` using a\n`DurableJobPayloadSigner`; omitted or `null` preserves legacy unsigned runners.\nThe host configuration is the only source of that signer, never schedule or job\narguments. `ScheduleRunner.capabilities.occurrenceIntegrity` lets hosts reject an\nolder runtime before enabling schedules that require this contract.\n\nDuring the same atomic occurrence transaction, after the real job ID exists,\nthe runner signs and saves `args._scheduleAdmission` before commit. A signer,\nverification, or protected-save failure rolls back both job and consumed slot.\nThere is no post-commit signing/save or visible unsigned protected job. Row\n`method_args` cannot supply the reserved `_scheduleAdmission` name.\n\nThe exact envelope is `{ purpose: 'smrt.schedule-admission', version: 1, keyId,\njobId, tenantId, scheduleId, scheduledFor, queue, objectType, objectId, method,\nargs }`. The args snapshot uses the existing signer's canonical persisted JSON\nrepresentation and excludes **only** top-level `_scheduleAdmission`; static\nconsent, constructor config and all other arguments remain bound. Metadata is\nexactly `{ version: 1, keyId, signature }`. The tenant is explicit (`null` for\nglobal); occurrence time must be a canonical UTC ISO instant.\n\n`getScheduleAdmissionPayload(job, keyId)` is a pure payload builder, not a signer\nor public minting endpoint. `verifyScheduleAdmission(job, signer)` returns false\non missing/unknown/malformed metadata, unknown/retired keys, tampered arguments,\nor a copied signature on a different job, period, schedule, tenant or execution\ntarget. Handlers requiring protected admission must verify the authoritative job\nrow even if a legacy unsigned runner could enqueue it. Actual worker execution\nalone does not prove scheduler admission.\n\nLegitimate retries preserve the same job ID, args and signature; lifecycle fields\nare excluded. For key rotation a trusted keyring can mint with its current\n`keyId` while retaining older verification keys for existing jobs. Retiring an old\nkey denies those retries until an explicit host reconciliation policy resolves\nit. Never put keys in arguments or logs. This signature proves admitted identity,\nnot current actor grants, policy, database uniqueness, handler exactly-once\nexecution, or safety against trusted code that holds a signing key. Hosts must\nstill recheck current authority and use normal claims/domain idempotency.\n\n## Public retry capacity and lock order\n\n`job.retry()` reads canonical persisted tenant, schedule association, key and\narguments. Caller-edited model fields cannot choose another schedule/key or\nrewrite business arguments/signatures. It validates current tenant ownership\nbefore taking write locks, then locks **schedule → dedupe slot → job** in one\ntransaction. Admission and reconciliation use the same physical schedule row and\npending/running count. A pending retry's own slot is excluded; other pending,\ndelayed-retry and running occurrences count toward `maxConcurrent`, including\nvalues greater than 1. Full capacity denies without resetting attempts, changing\nstatus or reassigning the key. A later retry can proceed once a slot is free.\nRunning/completed jobs cannot be retried. Missing/foreign/malformed persisted\ncanonical occurrence associations fail closed.\n\n`_scheduleId` alone is compatibility metadata shared by independent producers,\nnot an AgentSchedule discriminator. Persisted `_scheduledFor` or\n`_scheduleAdmission` marks a canonical agent occurrence and requires its\nsame-tenant schedule even if that schedule's target was later reconfigured.\nA legacy job without those markers occupies agent capacity only when its stored\nexecution type/object ID/method matches the actual same-tenant AgentSchedule.\nOther producer metadata neither requires an agent table nor changes an unrelated\nschedule, including a coincident ID. Table availability is checked portably on\nthe caller executor before SQL, without catching a missing-table error inside\nan already-aborted PostgreSQL transaction. Admission/reconciliation count marked\nprior occurrences across target reconfiguration and matching legacy agent jobs,\nnot unrelated producers' same-named metadata. Retry rechecks the canonical stored\narguments, tenant, target and association after its locks before lifecycle writes.\n\nThe transition changes lifecycle fields only, then hydrates the authoritative\nrow/revision back into the model, including keyed retries. It preserves the exact\nstored args and signature. `retry({ transaction: tx })` joins an existing caller\ntransaction without nesting (DuckDB has no savepoints); the caller must propagate\nerrors and roll back on failure. That caller must not acquire lower-order locks\nbefore this API. Completion's job transaction commits before its separate schedule\ncallback, so it never holds a job lock while waiting for a schedule lock. Automatic\nhandler retry keeps its existing nonterminal slot; no new admission is made.\nThis remains a nonterminal-row concurrency guarantee, not preemption of an orphan\nJavaScript handler or a substitute for handler authority/idempotency.\n\nKeyed enqueue requires canonical lowercase hyphenated UUID tenant identities,\nincluding ambient context. Valid alternate UUID spellings (uppercase, braces or\ncompact form) fail before any slot/job write; load the canonical tenant identity\nfirst. This prevents native PostgreSQL/DuckDB UUID hydration from changing the\nidentity used to hash a slot. Opaque non-UUID tenant strings remain exact and case\nsensitive; no global case folding or relaxed tenant guard is applied. Nonkeyed\nlegacy enqueue behavior is unchanged. The keyed API is unreleased: private\nuppercase development fixtures are not an existing-public-data migration case.\n\n## Durable required admission (#3346)\n\nA schedule that must never be consumed by an unsigned or differently routed host\npersists this public requirement in `AgentSchedule.methodArgs`:\n\n```ts\nconst policy: ScheduleAdmissionPolicy = {\n version: 1,\n requireIntegrity: true,\n queue: 'protected-agents',\n keyId: 'current-host-key',\n};\nschedule.methodArgs = { ...consentedArguments, _scheduleAdmissionPolicy: policy };\n```\n\n`getScheduleAdmissionPolicy(args)` returns a validated copy, or `null` only when\nabsent. A present malformed/unknown policy blocks. `ScheduleRunner` requires a\ntrusted `occurrenceSigner` whose current `keyId` matches and the exact `queue`.\nIt checks before reconciliation/claim writes and again under the occurrence\nlock. A blocked schedule keeps its due time, counts, errors and jobs unchanged;\n`schedule:blocked` emits only `{ scheduleId, reason }` with a bounded reason code\n(`INVALID_ADMISSION_POLICY`, `MISSING_OCCURRENCE_SIGNER`, `WRONG_OCCURRENCE_KEY`,\n`WRONG_OCCURRENCE_QUEUE`). This diagnostic is not persisted on the schedule.\nHosts must require both `ScheduleRunner.capabilities.requiredOccurrenceIntegrity`\nand `AgentSchedule.capabilities.requiredAdmissionPolicy`, plus the public\n`AgentSchedule.prototype.reconfigureAdmissionPolicy` method, before enabling\nprotected schedules. New jobs with old agents is an unsupported mixed cohort.\nAbsent policy retains legacy unsigned scheduling behavior. Full immutable job\narguments, including this policy, participate in admission signing. Verification\nalso rejects a policy inconsistent with the signed job queue or signature key.\n\nOrdinary public `AgentSchedule.save()`/generated updates cannot remove or replace\nan existing policy through mutated arguments, including fresh-object natural-key\nupserts. An agents-owned mandatory write predicate binds the canonical stored\nJSON; late collisions fail closed and callers reload/retry. This uses core's\npublic `GlobalInterceptors.writeGuard` seam without replacing tenant predicates.\nOrdinary sequential same-policy and unprotected upserts keep their existing API.\n\nA trusted host explicitly rotates/removes policy through the loaded model's\n`reconfigureAdmissionPolicy(nextPolicyOrNull, { authorize: async context => ... })`.\nThe callback must check the **current** authenticated operator/tenant permission;\nits context contains persisted schedule ID/tenant and previous/next policy.\nThrowing denies without a write. Generated CRUD never supplies this callback.\nCurrent tenant ownership and normal loaded revision CAS still apply. The same\ninstance must not be concurrently saved/rebound during this operation. This is\nan explicit authorization boundary, not a serialized bypass flag.\n\nFor rotation, first retain old verification keys in the trusted keyring while\nselecting a new current minting key, then authorize the durable policy key change.\nExisting jobs retain their original exact arguments/signature on retry; unknown\nor retired verification keys deny. Integrity does not replace current authority,\njob/schedule locking or downstream command idempotency. Code holding trusted keys\nand authorization callbacks remains trusted; this does not defend against it.\n\nOwning focused tests cover SQLite and native DuckDB policy blocking, locked\nrecheck, exact protected retry/rotation, public save/CAS and late collision.\n`packages/jobs/src/__tests__/retry-admission-postgres.optional.test.ts` additionally\ncovers real separate-connection retry/admission commit and rollback with signature\npreservation. Coordinator integration owns PostgreSQL and the complete gates.\n"
|
|
1349
|
+
}
|
|
1350
|
+
],
|
|
1285
1351
|
"browser": {
|
|
1286
1352
|
"status": "server-only",
|
|
1287
1353
|
"issues": [
|
|
@@ -5,10 +5,10 @@ description: "Background job processing for SMRT objects with persistence and sc
|
|
|
5
5
|
status: "stable"
|
|
6
6
|
generated:
|
|
7
7
|
by: "smrt/scripts/generate-knowledge-okf.ts"
|
|
8
|
-
at: "2026-11-
|
|
8
|
+
at: "2026-11-08T11:50:49Z"
|
|
9
9
|
audience: "internal"
|
|
10
10
|
evidence_level: "source-inspected"
|
|
11
|
-
source_revision: "sha256:
|
|
11
|
+
source_revision: "sha256:350fca00191c16de2357992320a352ce93971dc2432ad36cb1b6477fc39c3ae0"
|
|
12
12
|
sources:
|
|
13
13
|
- id: "manifest"
|
|
14
14
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/package.json"
|
|
@@ -16,6 +16,9 @@ sources:
|
|
|
16
16
|
- id: "agents"
|
|
17
17
|
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/AGENTS.md"
|
|
18
18
|
title: "@happyvertical/smrt-jobs packages/jobs/AGENTS.md"
|
|
19
|
+
- id: "agents-2"
|
|
20
|
+
resource: "https://github.com/happyvertical/smrt/blob/main/packages/jobs/agents/scheduling.md"
|
|
21
|
+
title: "@happyvertical/smrt-jobs packages/jobs/agents/scheduling.md"
|
|
19
22
|
---
|
|
20
23
|
|
|
21
24
|
# @happyvertical/smrt-jobs
|
|
@@ -30,6 +33,7 @@ sources:
|
|
|
30
33
|
## Documentation
|
|
31
34
|
|
|
32
35
|
- `packages/jobs/AGENTS.md`
|
|
36
|
+
- `packages/jobs/agents/scheduling.md`
|
|
33
37
|
|
|
34
38
|
## Framework dependencies
|
|
35
39
|
|
|
@@ -65,6 +69,8 @@ sources:
|
|
|
65
69
|
- `ForgeProjectionCheckpoint` (collection `forgeprojectioncheckpoints`, extends `SmrtObject`)
|
|
66
70
|
- `SmrtJob` (collection `smrtjobs`, extends `SmrtObject`)
|
|
67
71
|
- `SmrtJobCollection` (collection `smrtjobs`, extends `SmrtCollection`)
|
|
72
|
+
- `SmrtJobDedupeSlot` (collection `smrtjobdedupeslots`, extends `SmrtObject`)
|
|
73
|
+
- `SmrtJobDedupeSlotCollection` (collection `smrtjobdedupeslots`, extends `SmrtCollection`)
|
|
68
74
|
- `SmrtJobEvent` (collection `smrtjobevents`, extends `SmrtObject`)
|
|
69
75
|
- `SmrtJobEventCollection` (collection `smrtjobevents`, extends `SmrtCollection`)
|
|
70
76
|
- `SmrtWorker` (collection `smrtworkers`, extends `SmrtObject`)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@happyvertical/smrt-jobs",
|
|
3
|
-
"version": "0.60.
|
|
3
|
+
"version": "0.60.15",
|
|
4
4
|
"smrtJsdoc": "strict",
|
|
5
5
|
"description": "Background job processing for SMRT objects with persistence and scheduling",
|
|
6
6
|
"author": "HappyVertical",
|
|
@@ -53,16 +53,16 @@
|
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@happyvertical/jobs": "^0.111.6",
|
|
55
55
|
"@happyvertical/logger": "^0.111.6",
|
|
56
|
-
"@happyvertical/smrt-config": "0.60.
|
|
57
|
-
"@happyvertical/smrt-core": "0.60.
|
|
58
|
-
"@happyvertical/smrt-tenancy": "0.60.
|
|
59
|
-
"@happyvertical/smrt-types": "0.60.
|
|
60
|
-
"@happyvertical/smrt-ui": "0.60.
|
|
56
|
+
"@happyvertical/smrt-config": "0.60.15",
|
|
57
|
+
"@happyvertical/smrt-core": "0.60.15",
|
|
58
|
+
"@happyvertical/smrt-tenancy": "0.60.15",
|
|
59
|
+
"@happyvertical/smrt-types": "0.60.15",
|
|
60
|
+
"@happyvertical/smrt-ui": "0.60.15",
|
|
61
61
|
"@happyvertical/sql": "^0.111.6",
|
|
62
62
|
"@happyvertical/utils": "^0.111.6"
|
|
63
63
|
},
|
|
64
64
|
"devDependencies": {
|
|
65
|
-
"@happyvertical/smrt-vitest": "0.60.
|
|
65
|
+
"@happyvertical/smrt-vitest": "0.60.15",
|
|
66
66
|
"@sveltejs/package": "^2.5.8",
|
|
67
67
|
"@sveltejs/vite-plugin-svelte": "^7.3.0",
|
|
68
68
|
"@types/node": "24.13.6",
|