@ancientpantheon/khronoton-core 0.1.0

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/CHANGELOG.md ADDED
@@ -0,0 +1,13 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@ancientpantheon/khronoton-core`.
4
+
5
+ The engine's pre-extraction history lives in the AncientHoldings hub, whose inline scheduler ("Cronoton") this package extracts and generalises.
6
+
7
+ ## 0.1.0 — 2026-07-04
8
+
9
+ First public version. The schedule engine was lifted from the AncientHoldings hub's inline scheduler ("Cronoton") and generalised into pure, framework-agnostic functions — the 7-mode `ScheduleMode`/`ScheduleConfig` model, `computeNextFire` (TOTAL / MONOTONIC / PURE), `summariseSchedule`, `InvalidScheduleConfigError`, and an in-tree 5-field UTC cron parser — locked by four contract suites. The injectable `tickOnce(now, deps)` tick engine was generalised from the hub's tick loop: three host-injected hooks (`loadDue` / `enqueueFire` / `persistNextFire`), enqueue-strictly-before-persist firing, per-row isolation, an engine-enforced batch cap (default 100, `RangeError` on a non-positive-integer override), and disjoint `{ firedIds, skippedIds }` membership — locked by two more contract suites. Zero runtime dependencies, plain-`tsc` ESM build to `dist/`. Consumed by the AncientHoldings hub, which injects storage and firing through the three hooks.
10
+
11
+ ## 0.0.1 — 2026-07-04
12
+
13
+ Initial package skeleton — empty but buildable. ESM-only package with an `export {};` entry point, plain-`tsc` emit to `dist/` (`.js` + `.d.ts`), vitest wired with `--passWithNoTests`, and a publish-eligible manifest (public access, `sideEffects: false`). No public API yet; the schedule math and the injectable `tickOnce` tick engine arrive in later phases. Unpublished.
package/LICENSE ADDED
@@ -0,0 +1,39 @@
1
+ Copyright (c) 2026 AncientHoldings. All rights reserved.
2
+
3
+ PROPRIETARY AND CONFIDENTIAL — NO LICENSE GRANTED
4
+
5
+ This software and all associated source code, documentation, and other
6
+ materials in this repository and in any distributed package derived from
7
+ it (including `@ancientpantheon/khronoton-core`) are the exclusive
8
+ property of AncientHoldings, operator of ancientholdings.eu, and are part
9
+ of the AncientPantheon infrastructure family of the StoaChain / Ouronet
10
+ ecosystem.
11
+
12
+ NO rights are granted to any person or entity. Without the prior explicit
13
+ written permission of AncientHoldings you may NOT, in whole or in part:
14
+
15
+ - use, execute, or run the software;
16
+ - copy, reproduce, or download it other than as incidental to authorized
17
+ access;
18
+ - modify, adapt, translate, or create derivative works;
19
+ - merge, publish, distribute, redistribute, sublicense, rent, lease,
20
+ lend, or sell it; or
21
+ - remove or alter this notice.
22
+
23
+ The only party permitted to use this software is AncientHoldings
24
+ (ancientholdings.eu) and the systems it operates. Any other use,
25
+ reproduction, or distribution is strictly prohibited and constitutes
26
+ infringement of AncientHoldings' rights.
27
+
28
+ If this package is published to a public package registry, that
29
+ publication is for the operational convenience of AncientHoldings and its
30
+ own systems only; it does NOT grant any license or right to any third
31
+ party, and public availability of the code shall not be construed as a
32
+ waiver of any right reserved herein.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
35
+ IMPLIED. IN NO EVENT SHALL ANCIENTHOLDINGS BE LIABLE FOR ANY CLAIM,
36
+ DAMAGES, OR OTHER LIABILITY ARISING FROM OR IN CONNECTION WITH THE
37
+ SOFTWARE OR ITS USE.
38
+
39
+ For licensing inquiries: ancientholdings.eu
package/README.md ADDED
@@ -0,0 +1,159 @@
1
+ # @ancientpantheon/khronoton-core
2
+
3
+ The headless scheduler engine of the AncientPantheon stack — pure 7-mode schedule math plus an injectable `tickOnce` tick engine. Extracted from the AncientHoldings hub's inline scheduler ("Cronoton"), generalised into a framework-agnostic library: **no database, no job queue, no framework**. Hosts inject storage and firing behaviour via hooks; the engine only decides *when* things are due and *what* to fire.
4
+
5
+ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — the heartbeat that separates an autonomous Automaton from a human-triggered Daimon. See the [repo README](https://github.com/AncientPantheon/Khronoton) for the full positioning.
6
+
7
+ ## Status
8
+
9
+ **`0.1.0` on public npmjs** — first published version of the headless scheduler engine. Both engines are implemented and locked by contract suites in `tests/`: the schedule math (the 7-mode model, `computeNextFire`, `summariseSchedule`, and the in-tree cron parser) and the injectable `tickOnce(now, deps)` tick engine. Consumed by the AncientHoldings hub, which injects storage and firing through the three hooks.
10
+
11
+ ## Schedule engine
12
+
13
+ The engine exports pure functions over a discriminated `ScheduleConfig` union — no side effects, no clock reads, no randomness. You pass in the current time (`now`) explicitly; two calls with identical arguments always return identical results.
14
+
15
+ ### The 7 schedule modes
16
+
17
+ `ScheduleMode` is one of seven string literals, each paired with its own config shape:
18
+
19
+ | Mode | Config fields | Fires |
20
+ | --- | --- | --- |
21
+ | `daily-at-utc` | `hours: number[]`, `minute: number` | At each listed UTC hour every day |
22
+ | `every-n-minutes` | `startDate: string` (ISO), `intervalMinutes: number` | Every N minutes, anchored to `startDate` |
23
+ | `weekly` | `daysOfWeek: number[]` (0–6), `hour`, `minute` | At the given UTC time on each listed weekday |
24
+ | `monthly` | `daysOfMonth: number[]` (1–31), `hour`, `minute` | At the given UTC time on each listed day of month |
25
+ | `cron-expression` | `expression: string` | Per the 5-field UTC cron expression (see below) |
26
+ | `one-time` | `fireAt: string` (ISO) | Exactly once, then terminal |
27
+ | `several-times-per-day` | `times: { hour; minute }[]` | At each listed UTC time-of-day, every day |
28
+
29
+ ### `computeNextFire(mode, config, now)`
30
+
31
+ ```ts
32
+ computeNextFire(mode: ScheduleMode, config: ScheduleConfig, now: Date): Date | null
33
+ ```
34
+
35
+ Returns the next instant strictly after `now` at which the schedule is due. The contract is **TOTAL**, **MONOTONIC**, and **PURE**:
36
+
37
+ - **TOTAL** — a valid `(mode, config, now)` triple never throws; a malformed config throws `InvalidScheduleConfigError`. Recurring modes always yield a future `Date`. The terminal `one-time` mode yields `null` once its single fire is in the past (a valid result, not an error).
38
+ - **MONOTONIC** — for the same recurring schedule, a later `now` yields an equal-or-later next-fire; every recurring mode iterates strictly forward from `now`.
39
+ - **PURE** — no `Math.random`, no `Date.now()`; `now` is the explicit input.
40
+
41
+ ```ts
42
+ import { computeNextFire } from '@ancientpantheon/khronoton-core';
43
+
44
+ computeNextFire(
45
+ 'daily-at-utc',
46
+ { mode: 'daily-at-utc', hours: [12], minute: 0 },
47
+ new Date('2026-06-01T00:00:00.000Z'),
48
+ ); // → Date 2026-06-01T12:00:00.000Z
49
+ ```
50
+
51
+ ### `summariseSchedule(mode, config)`
52
+
53
+ ```ts
54
+ summariseSchedule(mode: ScheduleMode, config: ScheduleConfig): string
55
+ ```
56
+
57
+ Returns a short human-readable description of a schedule (e.g. `"One-time at 2026-07-01T12:00:00.000Z UTC"`). Pure — it never reads `Date.now()` or the system locale.
58
+
59
+ ### In-tree cron parser
60
+
61
+ The `cron-expression` mode is backed by a pruned in-tree parser — **no `cron-parser` dependency is added**. It accepts the standard 5-field UTC shape `minute hour dayOfMonth month dayOfWeek`, with this per-field syntax:
62
+
63
+ | Syntax | Meaning |
64
+ | --- | --- |
65
+ | `*` | any value |
66
+ | `N` | a literal integer |
67
+ | `N,M,...` | a comma list |
68
+ | `N-M` | an inclusive range |
69
+ | `*/STEP` | step from the field's start |
70
+ | `N/M` | step from `N` |
71
+
72
+ Explicitly **rejected** (throws `InvalidScheduleConfigError`): `@hourly`/`@daily` and other `@macro` shorthands, a seconds field (6-field expressions), and the Quartz extensions `L`, `W`, and `#`.
73
+
74
+ `dayOfMonth` and `dayOfWeek` follow standard cron **OR-matching** when both are restricted: a day matches if it satisfies *either* field. A field written as its full range (`1-31` for dayOfMonth, `0-6` for dayOfWeek) is detected as a wildcard, so the OR only applies when both fields are genuinely restricted.
75
+
76
+ ### Errors
77
+
78
+ `InvalidScheduleConfigError` is the single typed reject for malformed configs (out-of-range values, non-integer times, unparseable ISO instants, malformed cron expressions). Well-formed inputs never throw.
79
+
80
+ ## Tick engine
81
+
82
+ `tickOnce(now, deps)` walks the rows that are due at `now` and fires each once, delegating all host coupling to three injected hooks. It performs no storage, queue, clock, or framework access of its own — the host supplies those through `deps`. It calls `computeNextFire` internally to decide each row's next instant.
83
+
84
+ ```ts
85
+ import { tickOnce } from '@ancientpantheon/khronoton-core';
86
+ import type { TickRow, TickResult, TickDeps } from '@ancientpantheon/khronoton-core';
87
+
88
+ tickOnce(now: Date, deps: TickDeps): TickResult
89
+ ```
90
+
91
+ ### The three injected hooks
92
+
93
+ | Hook | Signature | Role |
94
+ | --- | --- | --- |
95
+ | `loadDue` | `(now: Date) => TickRow[]` | Return the rows due at `now`. A throw here propagates out of `tickOnce` (isolation is per-row, not batch-level). |
96
+ | `enqueueFire` | `(row: TickRow) => void` | Dispatch the fire (queue/audit). Receives the host's **full** row object — the generic engine reads only `id`/`mode`/`config`, so any extra host fields ride along untouched. |
97
+ | `persistNextFire` | `(id: string, nextDate: Date, firedAt: Date) => void` | Durably record the advance. `firedAt` is the tick's explicit `now` — never a clock read. |
98
+
99
+ A `TickRow` is `{ id: string; mode: ScheduleMode; config: ScheduleConfig | string }`. Its `config` accepts **both host forms**: a typed `ScheduleConfig` object, or a JSON string that the engine parses per-row inside the isolated try (so one unparseable row is skipped, not the whole batch).
100
+
101
+ ### Result semantics
102
+
103
+ `tickOnce` returns `{ firedIds: string[]; skippedIds: string[] }`:
104
+
105
+ - **Fired** — a row's id lands in `firedIds` only when **both** `enqueueFire` and `persistNextFire` returned without throwing.
106
+ - **Skipped** — every other processed outcome lands in `skippedIds`: an unparseable config, a `computeNextFire` rejection, a throwing hook, or a spent `one-time` schedule (`computeNextFire` → `null`, a valid terminal state, not an error and not logged).
107
+ - The two sets are disjoint and together cover exactly the rows that were processed.
108
+
109
+ ### Guarantees
110
+
111
+ - **Enqueue strictly before persist**, and persist runs **only after** enqueue succeeds. A crash between the two re-fires the row on the next tick rather than silently dropping it. An `enqueueFire` throw leaves `persistNextFire` uncalled for that row.
112
+ - **Per-row isolation** — each row is processed in its own `try`; one bad row is logged and skipped, and the tick continues. No status or row mutation: the engine's only write channel is `persistNextFire`, whose signature cannot express a status change.
113
+ - **Batch cap** — at most `maxBatch` rows are processed per tick (default **100**), regardless of how many `loadDue` returns. Overflow rows appear in **neither** result set; they stay due and are re-read next tick. A provided `maxBatch` that is not a positive integer (`0`, negative, fractional, `NaN`) throws a `RangeError` **before** any hook runs — never a silent zero-batch or dropped-tail.
114
+ - **Synchronous** — `tickOnce` returns a plain object, not a Promise. The engine holds no in-memory timers and carries no state across calls, so it is restart-safe: the host re-reads due state via `loadDue` each tick.
115
+
116
+ ### Optional deps
117
+
118
+ - `maxBatch?: number` — override the default 100 (positive integer only; see above).
119
+ - `logError?: (message: string) => void` — redirect skip logging; defaults to `console.error`.
120
+
121
+ ### Host preconditions
122
+
123
+ 1. **The three hooks must themselves be synchronous.** TypeScript's `=> void` contextual typing silently accepts an `async` hook, but its returned Promise is neither awaited nor error-handled — an async hook voids the enqueue-before-persist ordering and the per-row-isolation guarantees. Async hosts are a future, separate additive API.
124
+ 2. **`loadDue` must return at most one row per id.** The fired/skipped disjoint-set semantics assume unique ids; behavior under duplicate ids is unspecified.
125
+
126
+ ```ts
127
+ const result = tickOnce(new Date('2026-05-24T12:00:00.500Z'), {
128
+ loadDue: () => [
129
+ { id: 'r1', mode: 'daily-at-utc', config: { mode: 'daily-at-utc', hours: [12], minute: 0 } },
130
+ ],
131
+ enqueueFire: (row) => queue.push(row.id),
132
+ persistNextFire: (id, nextDate, firedAt) => db.advance(id, nextDate, firedAt),
133
+ });
134
+ // → { firedIds: ['r1'], skippedIds: [] }; nextDate = 2026-05-25T12:00:00.000Z, firedAt = the passed now
135
+ ```
136
+
137
+ ## What this package does NOT contain
138
+
139
+ Persistence, queues, timers, HTTP, or any framework binding — those stay in the host (the AncientHoldings hub keeps its own glue and imports this package for the scheduling logic). The `tickOnce` tick engine walks due schedules and invokes host hooks, but it never touches storage, queues, or clocks itself — the host injects all coupling through `loadDue`/`enqueueFire`/`persistNextFire`.
140
+
141
+ ## Install
142
+
143
+ Not yet installable — the package is unpublished. Once released:
144
+
145
+ ```bash
146
+ npm install @ancientpantheon/khronoton-core
147
+ ```
148
+
149
+ ## Version history
150
+
151
+ **v0.1.0** — First published version: 7-mode schedule engine + injectable tickOnce tick engine.
152
+
153
+ **v0.0.1** — Initial package skeleton, then the pure schedule engine: the 7-mode `ScheduleMode`/`ScheduleConfig` model, `computeNextFire` (TOTAL / MONOTONIC / PURE), `summariseSchedule`, `InvalidScheduleConfigError`, and an in-tree 5-field UTC cron parser — lifted faithfully from the AncientHoldings hub and locked by four contract suites. Then the injectable `tickOnce(now, deps)` tick engine: three host-injected hooks (`loadDue`/`enqueueFire`/`persistNextFire`), enqueue-before-persist firing, per-row isolation, an engine-enforced batch cap, and `{ firedIds, skippedIds }` membership — generalised from the hub's tick loop and locked by two more contract suites. Zero runtime dependencies, plain-`tsc` ESM build to `dist/`. Still unpublished.
154
+
155
+ ## License
156
+
157
+ Proprietary — **all rights reserved** by AncientHoldings (ancientholdings.eu). See [LICENSE](./LICENSE).
158
+
159
+ This package is published for the operational convenience of AncientHoldings and its own systems. Public availability on the registry grants **no** license or right to any third party: no use, copying, modification, or distribution is permitted without the prior explicit written consent of AncientHoldings. Not open source.
@@ -0,0 +1,4 @@
1
+ export { computeNextFire, summariseSchedule, InvalidScheduleConfigError } from "./schedule.js";
2
+ export type { ScheduleMode, ScheduleConfig, DailyAtUtcConfig, EveryNMinutesConfig, WeeklyConfig, MonthlyConfig, CronExpressionConfig, OneTimeConfig, SeveralTimesPerDayConfig } from "./schedule.js";
3
+ export { tickOnce } from "./tick.js";
4
+ export type { TickRow, TickResult, TickDeps } from "./tick.js";
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export { computeNextFire, summariseSchedule, InvalidScheduleConfigError } from "./schedule.js";
2
+ export { tickOnce } from "./tick.js";
@@ -0,0 +1,102 @@
1
+ /**
2
+ * schedule — pure schedule model and timing math for @ancientpantheon/khronoton-core.
3
+ *
4
+ * Public surface:
5
+ * - ScheduleMode (7 literal values)
6
+ * - ScheduleConfig (discriminated union by `.mode`)
7
+ * - InvalidScheduleConfigError (typed reject)
8
+ * - computeNextFire(mode, config, now): Date | null
9
+ * - summariseSchedule(mode, config): string
10
+ *
11
+ * Contract:
12
+ * - TOTAL — a valid (mode, config, now) triple never throws;
13
+ * InvalidScheduleConfigError is reserved for malformed
14
+ * configs. Recurring modes always yield a future Date; the
15
+ * terminal `one-time` mode legitimately yields `null` once
16
+ * its single fire is in the past (a valid result, not an
17
+ * error).
18
+ * - MONOTONIC — for the same RECURRING schedule, later `now` ->
19
+ * equal-or-later next-fire (when both `now`s sit
20
+ * at-or-after the same prior fire). Enforced by the
21
+ * algorithm shape: every recurring mode iterates strictly
22
+ * forward from `now`. (`one-time` is exempt: once spent it
23
+ * returns `null`, which is the monotonic terminal state.)
24
+ * - PURE — no `Math.random`, no `Date.now()`. `now` is the
25
+ * explicit input. Two calls with identical args return
26
+ * identical results.
27
+ *
28
+ * Cron mode (5-field UTC):
29
+ * - Pruned in-tree parser; no `cron-parser` dependency added.
30
+ * - Standard 5-field shape: `minute hour dayOfMonth month dayOfWeek`.
31
+ * - Syntax supported per field:
32
+ * * (any)
33
+ * N (literal int)
34
+ * N,M,... (comma list)
35
+ * N-M (inclusive range)
36
+ * *<NN (step from start)
37
+ * N/M (step from N)
38
+ * - Out of scope (explicitly rejected): `@hourly` / `@daily` macros,
39
+ * seconds field, `L`/`W`/`#` Quartz extensions.
40
+ *
41
+ * The behavior of this engine is locked by the contract suites in
42
+ * `tests/`: schedule-compute-next-fire.test.ts, schedule-extended-modes.test.ts,
43
+ * schedule-new-modes.test.ts, and schedule-cron-dom-dow-or.test.ts.
44
+ */
45
+ export type ScheduleMode = 'daily-at-utc' | 'every-n-minutes' | 'weekly' | 'monthly' | 'cron-expression' | 'one-time' | 'several-times-per-day';
46
+ export type DailyAtUtcConfig = {
47
+ mode: 'daily-at-utc';
48
+ hours: number[];
49
+ minute: number;
50
+ };
51
+ export type EveryNMinutesConfig = {
52
+ mode: 'every-n-minutes';
53
+ startDate: string;
54
+ intervalMinutes: number;
55
+ };
56
+ export type WeeklyConfig = {
57
+ mode: 'weekly';
58
+ daysOfWeek: number[];
59
+ hour: number;
60
+ minute: number;
61
+ };
62
+ export type MonthlyConfig = {
63
+ mode: 'monthly';
64
+ daysOfMonth: number[];
65
+ hour: number;
66
+ minute: number;
67
+ };
68
+ export type CronExpressionConfig = {
69
+ mode: 'cron-expression';
70
+ expression: string;
71
+ };
72
+ export type OneTimeConfig = {
73
+ mode: 'one-time';
74
+ /** ISO8601 instant at which the schedule fires exactly once. */
75
+ fireAt: string;
76
+ };
77
+ export type SeveralTimesPerDayConfig = {
78
+ mode: 'several-times-per-day';
79
+ /** Per-entry UTC time-of-day; fires at each one, every day. */
80
+ times: {
81
+ hour: number;
82
+ minute: number;
83
+ }[];
84
+ };
85
+ export type ScheduleConfig = DailyAtUtcConfig | EveryNMinutesConfig | WeeklyConfig | MonthlyConfig | CronExpressionConfig | OneTimeConfig | SeveralTimesPerDayConfig;
86
+ export declare class InvalidScheduleConfigError extends Error {
87
+ constructor(message: string);
88
+ }
89
+ /**
90
+ * computeNextFire — pure helper. Returns the next Date strictly after
91
+ * `now` at which the schedule fires. Throws InvalidScheduleConfigError
92
+ * on malformed config. Returns `null` ONLY for the terminal `one-time`
93
+ * mode once its single `fireAt` instant is at-or-before `now` (the fire
94
+ * is spent/past). All recurring modes always return a future Date.
95
+ */
96
+ export declare function computeNextFire(mode: ScheduleMode, config: ScheduleConfig, now: Date): Date | null;
97
+ /**
98
+ * Human-readable one-line summary of a schedule, so an operator sees
99
+ * `Daily at 12:00 UTC` instead of the raw JSON config. Pure (no
100
+ * Date.now() or system locale).
101
+ */
102
+ export declare function summariseSchedule(mode: ScheduleMode, config: ScheduleConfig): string;
@@ -0,0 +1,419 @@
1
+ /**
2
+ * schedule — pure schedule model and timing math for @ancientpantheon/khronoton-core.
3
+ *
4
+ * Public surface:
5
+ * - ScheduleMode (7 literal values)
6
+ * - ScheduleConfig (discriminated union by `.mode`)
7
+ * - InvalidScheduleConfigError (typed reject)
8
+ * - computeNextFire(mode, config, now): Date | null
9
+ * - summariseSchedule(mode, config): string
10
+ *
11
+ * Contract:
12
+ * - TOTAL — a valid (mode, config, now) triple never throws;
13
+ * InvalidScheduleConfigError is reserved for malformed
14
+ * configs. Recurring modes always yield a future Date; the
15
+ * terminal `one-time` mode legitimately yields `null` once
16
+ * its single fire is in the past (a valid result, not an
17
+ * error).
18
+ * - MONOTONIC — for the same RECURRING schedule, later `now` ->
19
+ * equal-or-later next-fire (when both `now`s sit
20
+ * at-or-after the same prior fire). Enforced by the
21
+ * algorithm shape: every recurring mode iterates strictly
22
+ * forward from `now`. (`one-time` is exempt: once spent it
23
+ * returns `null`, which is the monotonic terminal state.)
24
+ * - PURE — no `Math.random`, no `Date.now()`. `now` is the
25
+ * explicit input. Two calls with identical args return
26
+ * identical results.
27
+ *
28
+ * Cron mode (5-field UTC):
29
+ * - Pruned in-tree parser; no `cron-parser` dependency added.
30
+ * - Standard 5-field shape: `minute hour dayOfMonth month dayOfWeek`.
31
+ * - Syntax supported per field:
32
+ * * (any)
33
+ * N (literal int)
34
+ * N,M,... (comma list)
35
+ * N-M (inclusive range)
36
+ * *<NN (step from start)
37
+ * N/M (step from N)
38
+ * - Out of scope (explicitly rejected): `@hourly` / `@daily` macros,
39
+ * seconds field, `L`/`W`/`#` Quartz extensions.
40
+ *
41
+ * The behavior of this engine is locked by the contract suites in
42
+ * `tests/`: schedule-compute-next-fire.test.ts, schedule-extended-modes.test.ts,
43
+ * schedule-new-modes.test.ts, and schedule-cron-dom-dow-or.test.ts.
44
+ */
45
+ export class InvalidScheduleConfigError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = 'InvalidScheduleConfigError';
49
+ }
50
+ }
51
+ function assertNever(x) {
52
+ throw new InvalidScheduleConfigError(`unknown schedule mode: ${String(x)}`);
53
+ }
54
+ function isValidHour(h) {
55
+ return Number.isInteger(h) && h >= 0 && h <= 23;
56
+ }
57
+ function isValidMinute(m) {
58
+ return Number.isInteger(m) && m >= 0 && m <= 59;
59
+ }
60
+ function isValidDayOfWeek(d) {
61
+ return Number.isInteger(d) && d >= 0 && d <= 6;
62
+ }
63
+ function isValidDayOfMonth(d) {
64
+ return Number.isInteger(d) && d >= 1 && d <= 31;
65
+ }
66
+ /**
67
+ * computeNextFire — pure helper. Returns the next Date strictly after
68
+ * `now` at which the schedule fires. Throws InvalidScheduleConfigError
69
+ * on malformed config. Returns `null` ONLY for the terminal `one-time`
70
+ * mode once its single `fireAt` instant is at-or-before `now` (the fire
71
+ * is spent/past). All recurring modes always return a future Date.
72
+ */
73
+ export function computeNextFire(mode, config, now) {
74
+ if (config.mode !== mode) {
75
+ throw new InvalidScheduleConfigError(`mode/config mismatch: mode=${mode} config.mode=${config.mode}`);
76
+ }
77
+ switch (config.mode) {
78
+ case 'daily-at-utc':
79
+ return nextDailyAtUtc(config, now);
80
+ case 'every-n-minutes':
81
+ return nextEveryNMinutes(config, now);
82
+ case 'weekly':
83
+ return nextWeekly(config, now);
84
+ case 'monthly':
85
+ return nextMonthly(config, now);
86
+ case 'cron-expression':
87
+ return nextCronExpression(config, now);
88
+ case 'one-time':
89
+ return nextOneTime(config, now);
90
+ case 'several-times-per-day':
91
+ return nextSeveralTimesPerDay(config, now);
92
+ default:
93
+ return assertNever(config);
94
+ }
95
+ }
96
+ function nextOneTime(config, now) {
97
+ const fireMs = Date.parse(config.fireAt);
98
+ if (Number.isNaN(fireMs)) {
99
+ throw new InvalidScheduleConfigError(`one-time: fireAt is not a valid ISO8601 string: ${config.fireAt}`);
100
+ }
101
+ // Terminal: a single fire that has already elapsed yields no future fire.
102
+ if (fireMs <= now.getTime())
103
+ return null;
104
+ return new Date(fireMs);
105
+ }
106
+ /** Dedup + sort times by the composite key hour*60+minute. */
107
+ function sortedTimesOfDay(times) {
108
+ const seen = new Set();
109
+ const unique = [];
110
+ for (const t of times) {
111
+ const key = t.hour * 60 + t.minute;
112
+ if (seen.has(key))
113
+ continue;
114
+ seen.add(key);
115
+ unique.push(t);
116
+ }
117
+ return unique.sort((a, b) => a.hour * 60 + a.minute - (b.hour * 60 + b.minute));
118
+ }
119
+ function nextSeveralTimesPerDay(config, now) {
120
+ if (!Array.isArray(config.times) || config.times.length === 0) {
121
+ throw new InvalidScheduleConfigError('several-times-per-day requires a non-empty times array');
122
+ }
123
+ if (!config.times.every((t) => isValidHour(t.hour) && isValidMinute(t.minute))) {
124
+ throw new InvalidScheduleConfigError('several-times-per-day: each time must have hour in [0..23] and minute in [0..59] (integers)');
125
+ }
126
+ const times = sortedTimesOfDay(config.times);
127
+ // Try today, then tomorrow. One of them is guaranteed to be > now.
128
+ for (let dayOffset = 0; dayOffset <= 1; dayOffset++) {
129
+ for (const t of times) {
130
+ const candidate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + dayOffset, t.hour, t.minute, 0, 0));
131
+ if (candidate.getTime() > now.getTime()) {
132
+ return candidate;
133
+ }
134
+ }
135
+ }
136
+ // Unreachable — the two-day sweep covers every possibility.
137
+ throw new InvalidScheduleConfigError('several-times-per-day: failed to find next-fire within 48h sweep');
138
+ }
139
+ function nextDailyAtUtc(config, now) {
140
+ if (!Array.isArray(config.hours) || config.hours.length === 0) {
141
+ throw new InvalidScheduleConfigError('daily-at-utc requires a non-empty hours array');
142
+ }
143
+ if (!config.hours.every(isValidHour)) {
144
+ throw new InvalidScheduleConfigError('daily-at-utc hours must be integers in [0..23]');
145
+ }
146
+ if (!isValidMinute(config.minute)) {
147
+ throw new InvalidScheduleConfigError('daily-at-utc minute must be an integer in [0..59]');
148
+ }
149
+ const sortedHours = [...new Set(config.hours)].sort((a, b) => a - b);
150
+ // Try today, then tomorrow. One of them is guaranteed to be > now.
151
+ for (let dayOffset = 0; dayOffset <= 1; dayOffset++) {
152
+ for (const h of sortedHours) {
153
+ const candidate = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + dayOffset, h, config.minute, 0, 0));
154
+ if (candidate.getTime() > now.getTime()) {
155
+ return candidate;
156
+ }
157
+ }
158
+ }
159
+ // Unreachable — the two-day sweep covers every possibility.
160
+ throw new InvalidScheduleConfigError('daily-at-utc: failed to find next-fire within 48h sweep');
161
+ }
162
+ function nextEveryNMinutes(config, now) {
163
+ if (!Number.isInteger(config.intervalMinutes) ||
164
+ config.intervalMinutes <= 0) {
165
+ throw new InvalidScheduleConfigError('every-n-minutes: intervalMinutes must be a positive integer');
166
+ }
167
+ const startMs = Date.parse(config.startDate);
168
+ if (Number.isNaN(startMs)) {
169
+ throw new InvalidScheduleConfigError(`every-n-minutes: startDate is not a valid ISO8601 string: ${config.startDate}`);
170
+ }
171
+ const intervalMs = config.intervalMinutes * 60000;
172
+ const nowMs = now.getTime();
173
+ if (nowMs < startMs)
174
+ return new Date(startMs);
175
+ // Ceiling: strictly future fire after `now`.
176
+ const elapsed = nowMs - startMs;
177
+ const nextMs = startMs + (Math.floor(elapsed / intervalMs) + 1) * intervalMs;
178
+ return new Date(nextMs);
179
+ }
180
+ function nextWeekly(config, now) {
181
+ if (!Array.isArray(config.daysOfWeek) || config.daysOfWeek.length === 0) {
182
+ throw new InvalidScheduleConfigError('weekly: daysOfWeek must be a non-empty array');
183
+ }
184
+ if (!config.daysOfWeek.every(isValidDayOfWeek)) {
185
+ throw new InvalidScheduleConfigError('weekly: daysOfWeek values must be integers in [0..6]');
186
+ }
187
+ if (!isValidHour(config.hour)) {
188
+ throw new InvalidScheduleConfigError('weekly: hour must be an integer in [0..23]');
189
+ }
190
+ if (!isValidMinute(config.minute)) {
191
+ throw new InvalidScheduleConfigError('weekly: minute must be an integer in [0..59]');
192
+ }
193
+ const dows = new Set(config.daysOfWeek);
194
+ for (let i = 0; i < 8; i++) {
195
+ const probe = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + i, config.hour, config.minute, 0, 0));
196
+ if (!dows.has(probe.getUTCDay()))
197
+ continue;
198
+ if (probe.getTime() > now.getTime())
199
+ return probe;
200
+ }
201
+ throw new InvalidScheduleConfigError('weekly: failed to find next-fire within 8-day sweep');
202
+ }
203
+ function nextMonthly(config, now) {
204
+ if (!Array.isArray(config.daysOfMonth) || config.daysOfMonth.length === 0) {
205
+ throw new InvalidScheduleConfigError('monthly: daysOfMonth must be a non-empty array');
206
+ }
207
+ if (!config.daysOfMonth.every(isValidDayOfMonth)) {
208
+ throw new InvalidScheduleConfigError('monthly: daysOfMonth values must be integers in [1..31]');
209
+ }
210
+ if (!isValidHour(config.hour)) {
211
+ throw new InvalidScheduleConfigError('monthly: hour must be an integer in [0..23]');
212
+ }
213
+ if (!isValidMinute(config.minute)) {
214
+ throw new InvalidScheduleConfigError('monthly: minute must be an integer in [0..59]');
215
+ }
216
+ // 33 days covers the worst case (31-of-month -> end-of-next-month).
217
+ for (let i = 0; i < 33; i++) {
218
+ const probe = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + i, config.hour, config.minute, 0, 0));
219
+ const probeDay = probe.getUTCDate();
220
+ if (!config.daysOfMonth.includes(probeDay))
221
+ continue;
222
+ if (probe.getTime() > now.getTime())
223
+ return probe;
224
+ }
225
+ throw new InvalidScheduleConfigError('monthly: failed to find next-fire within 33-day sweep');
226
+ }
227
+ /**
228
+ * Parse one field of a 5-field UTC cron expression into the set of
229
+ * matching integers in [min..max]. Supports `*`, `N`, `N,M,...`, `N-M`,
230
+ * `* /STEP`, and `N/M`. Anything else throws.
231
+ */
232
+ function parseCronField(raw, min, max) {
233
+ const out = new Set();
234
+ if (!raw || typeof raw !== 'string') {
235
+ throw new InvalidScheduleConfigError(`cron-expression: empty field`);
236
+ }
237
+ for (const piece of raw.split(',')) {
238
+ const p = piece.trim();
239
+ if (!p) {
240
+ throw new InvalidScheduleConfigError(`cron-expression: empty list slot`);
241
+ }
242
+ // Step syntax: BASE/STEP where BASE is `*` or `N` or `N-M`.
243
+ if (p.includes('/')) {
244
+ const [basePart, stepPart] = p.split('/');
245
+ const step = Number(stepPart);
246
+ if (!Number.isInteger(step) || step <= 0) {
247
+ throw new InvalidScheduleConfigError(`cron-expression: invalid step '${stepPart}'`);
248
+ }
249
+ let rangeStart = min;
250
+ let rangeEnd = max;
251
+ if (basePart === '*') {
252
+ // already min..max
253
+ }
254
+ else if (basePart.includes('-')) {
255
+ const [s, e] = basePart.split('-').map(Number);
256
+ if (!Number.isInteger(s) ||
257
+ !Number.isInteger(e) ||
258
+ s < min ||
259
+ e > max ||
260
+ s > e) {
261
+ throw new InvalidScheduleConfigError(`cron-expression: invalid range '${basePart}'`);
262
+ }
263
+ rangeStart = s;
264
+ rangeEnd = e;
265
+ }
266
+ else {
267
+ const n = Number(basePart);
268
+ if (!Number.isInteger(n) || n < min || n > max) {
269
+ throw new InvalidScheduleConfigError(`cron-expression: invalid base '${basePart}'`);
270
+ }
271
+ rangeStart = n;
272
+ rangeEnd = max;
273
+ }
274
+ for (let v = rangeStart; v <= rangeEnd; v += step) {
275
+ out.add(v);
276
+ }
277
+ continue;
278
+ }
279
+ if (p === '*') {
280
+ for (let v = min; v <= max; v++)
281
+ out.add(v);
282
+ continue;
283
+ }
284
+ if (p.includes('-')) {
285
+ const [s, e] = p.split('-').map(Number);
286
+ if (!Number.isInteger(s) ||
287
+ !Number.isInteger(e) ||
288
+ s < min ||
289
+ e > max ||
290
+ s > e) {
291
+ throw new InvalidScheduleConfigError(`cron-expression: invalid range '${p}'`);
292
+ }
293
+ for (let v = s; v <= e; v++)
294
+ out.add(v);
295
+ continue;
296
+ }
297
+ const n = Number(p);
298
+ if (!Number.isInteger(n) || n < min || n > max) {
299
+ throw new InvalidScheduleConfigError(`cron-expression: invalid literal '${p}'`);
300
+ }
301
+ out.add(n);
302
+ }
303
+ if (out.size === 0) {
304
+ throw new InvalidScheduleConfigError(`cron-expression: parsed an empty value set from '${raw}'`);
305
+ }
306
+ return out;
307
+ }
308
+ function parseCronExpression(expression) {
309
+ if (typeof expression !== 'string') {
310
+ throw new InvalidScheduleConfigError('cron-expression: expression must be a string');
311
+ }
312
+ const fields = expression.trim().split(/\s+/);
313
+ if (fields.length !== 5) {
314
+ throw new InvalidScheduleConfigError(`cron-expression: expected 5 fields, got ${fields.length} ('${expression}')`);
315
+ }
316
+ return {
317
+ minutes: parseCronField(fields[0], 0, 59),
318
+ hours: parseCronField(fields[1], 0, 23),
319
+ daysOfMonth: parseCronField(fields[2], 1, 31),
320
+ months: parseCronField(fields[3], 1, 12),
321
+ daysOfWeek: parseCronField(fields[4], 0, 6),
322
+ };
323
+ }
324
+ function nextCronExpression(config, now) {
325
+ const parsed = parseCronExpression(config.expression);
326
+ // Step minute-by-minute up to ~1 year. For repeating standard cron
327
+ // expressions, a match always exists within ~366 days.
328
+ const MAX_MINUTES = 366 * 24 * 60;
329
+ // Start one minute past `now` (strictly future).
330
+ const start = new Date(now.getTime());
331
+ start.setUTCSeconds(0, 0);
332
+ start.setUTCMinutes(start.getUTCMinutes() + 1);
333
+ for (let i = 0; i < MAX_MINUTES; i++) {
334
+ const probe = new Date(start.getTime() + i * 60000);
335
+ const minute = probe.getUTCMinutes();
336
+ const hour = probe.getUTCHours();
337
+ const dom = probe.getUTCDate();
338
+ const month = probe.getUTCMonth() + 1;
339
+ const dow = probe.getUTCDay();
340
+ if (!parsed.minutes.has(minute))
341
+ continue;
342
+ if (!parsed.hours.has(hour))
343
+ continue;
344
+ if (!parsed.months.has(month))
345
+ continue;
346
+ // Cron semantics: when both dayOfMonth and dayOfWeek are
347
+ // restricted (not *), match either. When at least one is `*`,
348
+ // require all set fields. We approximate "is this field *?" by
349
+ // checking whether the parsed set covers the entire allowed range.
350
+ const domAny = parsed.daysOfMonth.size === 31;
351
+ const dowAny = parsed.daysOfWeek.size === 7;
352
+ if (domAny && dowAny) {
353
+ return probe;
354
+ }
355
+ if (domAny) {
356
+ if (parsed.daysOfWeek.has(dow))
357
+ return probe;
358
+ continue;
359
+ }
360
+ if (dowAny) {
361
+ if (parsed.daysOfMonth.has(dom))
362
+ return probe;
363
+ continue;
364
+ }
365
+ // Both restricted -> match either.
366
+ if (parsed.daysOfMonth.has(dom) || parsed.daysOfWeek.has(dow)) {
367
+ return probe;
368
+ }
369
+ }
370
+ throw new InvalidScheduleConfigError(`cron-expression: no future fire found within ${MAX_MINUTES} minutes`);
371
+ }
372
+ /**
373
+ * Human-readable one-line summary of a schedule, so an operator sees
374
+ * `Daily at 12:00 UTC` instead of the raw JSON config. Pure (no
375
+ * Date.now() or system locale).
376
+ */
377
+ export function summariseSchedule(mode, config) {
378
+ if (config.mode !== mode)
379
+ return `${mode} (config mismatch)`;
380
+ switch (config.mode) {
381
+ case 'daily-at-utc': {
382
+ const hours = [...new Set(config.hours)].sort((a, b) => a - b);
383
+ const pad = (n) => String(n).padStart(2, '0');
384
+ const hourList = hours.map((h) => `${pad(h)}:${pad(config.minute)}`).join(', ');
385
+ return `Daily at ${hourList} UTC`;
386
+ }
387
+ case 'every-n-minutes':
388
+ return `Every ${config.intervalMinutes} minute${config.intervalMinutes === 1 ? '' : 's'} from ${config.startDate}`;
389
+ case 'weekly': {
390
+ const names = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
391
+ const days = [...new Set(config.daysOfWeek)]
392
+ .sort((a, b) => a - b)
393
+ .map((d) => names[d])
394
+ .join('/');
395
+ const pad = (n) => String(n).padStart(2, '0');
396
+ return `Weekly ${days} at ${pad(config.hour)}:${pad(config.minute)} UTC`;
397
+ }
398
+ case 'monthly': {
399
+ const days = [...new Set(config.daysOfMonth)]
400
+ .sort((a, b) => a - b)
401
+ .join(', ');
402
+ const pad = (n) => String(n).padStart(2, '0');
403
+ return `Monthly day(s) ${days} at ${pad(config.hour)}:${pad(config.minute)} UTC`;
404
+ }
405
+ case 'cron-expression':
406
+ return `Cron '${config.expression}' (UTC)`;
407
+ case 'one-time':
408
+ return `One-time at ${config.fireAt} UTC`;
409
+ case 'several-times-per-day': {
410
+ const pad = (n) => String(n).padStart(2, '0');
411
+ const list = sortedTimesOfDay(config.times)
412
+ .map((t) => `${pad(t.hour)}:${pad(t.minute)}`)
413
+ .join(', ');
414
+ return `Several times daily at ${list} UTC`;
415
+ }
416
+ default:
417
+ return assertNever(config);
418
+ }
419
+ }
package/dist/tick.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ /**
2
+ * tick — the pure, injectable single-tick engine for
3
+ * @ancientpantheon/khronoton-core.
4
+ *
5
+ * Public surface:
6
+ * - TickRow / TickResult / TickDeps
7
+ * - tickOnce(now, deps): TickResult
8
+ *
9
+ * Contract (generalized from the AncientHoldings hub's lib/cronoton-tick.ts —
10
+ * the three host couplings are inverted into injected hooks, every operational
11
+ * invariant preserved):
12
+ * - THREE injected hooks carry all host coupling:
13
+ * loadDue(now) -> the due-rows read
14
+ * enqueueFire(row) -> the fire dispatch (queue/audit)
15
+ * persistNextFire(id, nextDate, at) -> the durable next-fire advance
16
+ * The engine itself touches no storage, queue, clock, or framework.
17
+ * - ENQUEUE STRICTLY BEFORE PERSIST, and persist runs ONLY after enqueue
18
+ * succeeds: the fire is dispatched first, then the advance is durably
19
+ * recorded, so a crash between the two re-fires the row (never silently
20
+ * drops it).
21
+ * - firedIds = both-hooks-succeeded ONLY. A row lands in firedIds only when
22
+ * enqueueFire AND persistNextFire both returned without throwing; every
23
+ * other processed outcome lands in skippedIds. The two sets are disjoint
24
+ * and together cover exactly the processed rows.
25
+ * - PER-ROW ISOLATION: each row is processed inside its own try; a single
26
+ * bad row (unparseable config, computeNextFire rejection, a throwing
27
+ * hook) is logged and skipped, and the tick continues to the next row.
28
+ * - BATCH CAP: at most `maxBatch` rows (default 100) are processed per tick,
29
+ * regardless of how many loadDue returns. Overflow rows appear in NEITHER
30
+ * result set — they were never processed and stay due for the next tick.
31
+ * - SPENT ONE-TIME -> SKIPPED, NOT AN ERROR: when computeNextFire yields
32
+ * null (a terminal schedule with no future fire), the row is skipped
33
+ * without enqueue, persist, or a log — it is a valid terminal outcome.
34
+ * - firedAt IS THE TICK'S EXPLICIT `now`: persistNextFire's third argument
35
+ * is always the `now` passed to tickOnce, never a clock read — the engine
36
+ * performs no Date.now().
37
+ * - RESTART-SAFE: the engine holds no in-memory timers and carries no state
38
+ * across calls; the host re-reads due state (via loadDue) each tick.
39
+ *
40
+ * HOST PRECONDITIONS (the host, not the engine, must uphold these):
41
+ * 1. The three hooks MUST be synchronous. TypeScript's `=> void` contextual
42
+ * typing silently accepts an `async` hook, but its returned Promise is
43
+ * neither awaited nor error-handled here — an async hook voids the
44
+ * enqueue-before-persist ordering and the per-row-isolation guarantees.
45
+ * Async hosts are a future, separate additive API, not this engine.
46
+ * 2. loadDue MUST return at most one row per id. The fired/skipped
47
+ * disjoint-set semantics assume unique ids; behavior under duplicate ids
48
+ * is unspecified.
49
+ */
50
+ import { type ScheduleConfig, type ScheduleMode } from "./schedule.js";
51
+ export type TickRow = {
52
+ id: string;
53
+ mode: ScheduleMode;
54
+ config: ScheduleConfig | string;
55
+ };
56
+ export type TickResult = {
57
+ firedIds: string[];
58
+ skippedIds: string[];
59
+ };
60
+ export type TickDeps<TRow extends TickRow = TickRow> = {
61
+ loadDue: (now: Date) => TRow[];
62
+ enqueueFire: (row: TRow) => void;
63
+ persistNextFire: (id: string, nextDate: Date, firedAt: Date) => void;
64
+ maxBatch?: number;
65
+ logError?: (message: string) => void;
66
+ };
67
+ export declare function tickOnce<TRow extends TickRow>(now: Date, deps: TickDeps<TRow>): TickResult;
package/dist/tick.js ADDED
@@ -0,0 +1,81 @@
1
+ /**
2
+ * tick — the pure, injectable single-tick engine for
3
+ * @ancientpantheon/khronoton-core.
4
+ *
5
+ * Public surface:
6
+ * - TickRow / TickResult / TickDeps
7
+ * - tickOnce(now, deps): TickResult
8
+ *
9
+ * Contract (generalized from the AncientHoldings hub's lib/cronoton-tick.ts —
10
+ * the three host couplings are inverted into injected hooks, every operational
11
+ * invariant preserved):
12
+ * - THREE injected hooks carry all host coupling:
13
+ * loadDue(now) -> the due-rows read
14
+ * enqueueFire(row) -> the fire dispatch (queue/audit)
15
+ * persistNextFire(id, nextDate, at) -> the durable next-fire advance
16
+ * The engine itself touches no storage, queue, clock, or framework.
17
+ * - ENQUEUE STRICTLY BEFORE PERSIST, and persist runs ONLY after enqueue
18
+ * succeeds: the fire is dispatched first, then the advance is durably
19
+ * recorded, so a crash between the two re-fires the row (never silently
20
+ * drops it).
21
+ * - firedIds = both-hooks-succeeded ONLY. A row lands in firedIds only when
22
+ * enqueueFire AND persistNextFire both returned without throwing; every
23
+ * other processed outcome lands in skippedIds. The two sets are disjoint
24
+ * and together cover exactly the processed rows.
25
+ * - PER-ROW ISOLATION: each row is processed inside its own try; a single
26
+ * bad row (unparseable config, computeNextFire rejection, a throwing
27
+ * hook) is logged and skipped, and the tick continues to the next row.
28
+ * - BATCH CAP: at most `maxBatch` rows (default 100) are processed per tick,
29
+ * regardless of how many loadDue returns. Overflow rows appear in NEITHER
30
+ * result set — they were never processed and stay due for the next tick.
31
+ * - SPENT ONE-TIME -> SKIPPED, NOT AN ERROR: when computeNextFire yields
32
+ * null (a terminal schedule with no future fire), the row is skipped
33
+ * without enqueue, persist, or a log — it is a valid terminal outcome.
34
+ * - firedAt IS THE TICK'S EXPLICIT `now`: persistNextFire's third argument
35
+ * is always the `now` passed to tickOnce, never a clock read — the engine
36
+ * performs no Date.now().
37
+ * - RESTART-SAFE: the engine holds no in-memory timers and carries no state
38
+ * across calls; the host re-reads due state (via loadDue) each tick.
39
+ *
40
+ * HOST PRECONDITIONS (the host, not the engine, must uphold these):
41
+ * 1. The three hooks MUST be synchronous. TypeScript's `=> void` contextual
42
+ * typing silently accepts an `async` hook, but its returned Promise is
43
+ * neither awaited nor error-handled here — an async hook voids the
44
+ * enqueue-before-persist ordering and the per-row-isolation guarantees.
45
+ * Async hosts are a future, separate additive API, not this engine.
46
+ * 2. loadDue MUST return at most one row per id. The fired/skipped
47
+ * disjoint-set semantics assume unique ids; behavior under duplicate ids
48
+ * is unspecified.
49
+ */
50
+ import { computeNextFire } from "./schedule.js";
51
+ /** Cap the per-tick batch so a coincidence storm can't run forever. */
52
+ const DEFAULT_MAX_BATCH = 100;
53
+ export function tickOnce(now, deps) {
54
+ if (deps.maxBatch !== undefined && (!Number.isInteger(deps.maxBatch) || deps.maxBatch <= 0)) {
55
+ throw new RangeError(`[khronoton] maxBatch must be a positive integer, got ${deps.maxBatch}`);
56
+ }
57
+ const cap = deps.maxBatch ?? DEFAULT_MAX_BATCH;
58
+ const logError = deps.logError ?? ((message) => console.error(message));
59
+ const firedIds = [];
60
+ const skippedIds = [];
61
+ const due = deps.loadDue(now).slice(0, cap);
62
+ for (const row of due) {
63
+ try {
64
+ const config = typeof row.config === "string" ? JSON.parse(row.config) : row.config;
65
+ const nextDate = computeNextFire(row.mode, config, now);
66
+ if (!nextDate) {
67
+ skippedIds.push(row.id);
68
+ continue;
69
+ }
70
+ deps.enqueueFire(row);
71
+ deps.persistNextFire(row.id, nextDate, now);
72
+ firedIds.push(row.id);
73
+ }
74
+ catch (err) {
75
+ const msg = err instanceof Error ? err.message : String(err);
76
+ logError(`[khronoton] tick skipping ${row.id}: ${msg}`);
77
+ skippedIds.push(row.id);
78
+ }
79
+ }
80
+ return { firedIds, skippedIds };
81
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@ancientpantheon/khronoton-core",
3
+ "version": "0.1.0",
4
+ "description": "Headless framework-agnostic scheduler engine: pure schedule math plus an injectable tick engine. No database, no job queue, no framework — hosts inject storage and firing via hooks.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "CHANGELOG.md",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "sideEffects": false,
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "scripts": {
25
+ "build": "tsc -p tsconfig.build.json",
26
+ "typecheck": "tsc --noEmit",
27
+ "test": "vitest run --passWithNoTests",
28
+ "test:watch": "vitest",
29
+ "clean": "rimraf dist"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/AncientPantheon/Khronoton.git",
34
+ "directory": "packages/khronoton-core"
35
+ },
36
+ "publishConfig": {
37
+ "registry": "https://registry.npmjs.org",
38
+ "access": "public"
39
+ },
40
+ "license": "UNLICENSED"
41
+ }