@ancientpantheon/khronoton-core 0.1.1 → 0.2.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +75 -3
  3. package/dist/server/executor-signers.d.ts +29 -0
  4. package/dist/server/executor-signers.js +60 -0
  5. package/dist/server/executor.d.ts +53 -0
  6. package/dist/server/executor.js +280 -0
  7. package/dist/server/index.d.ts +27 -0
  8. package/dist/server/index.js +51 -0
  9. package/dist/server/loop.d.ts +36 -0
  10. package/dist/server/loop.js +51 -0
  11. package/dist/server/pure/capability.d.ts +31 -0
  12. package/dist/server/pure/capability.js +63 -0
  13. package/dist/server/pure/fingerprint.d.ts +8 -0
  14. package/dist/server/pure/fingerprint.js +44 -0
  15. package/dist/server/pure/runtime-args.d.ts +34 -0
  16. package/dist/server/pure/runtime-args.js +99 -0
  17. package/dist/server/resolvers.d.ts +140 -0
  18. package/dist/server/resolvers.js +200 -0
  19. package/dist/server/schema.d.ts +31 -0
  20. package/dist/server/schema.js +93 -0
  21. package/dist/server/seams.d.ts +231 -0
  22. package/dist/server/seams.js +34 -0
  23. package/dist/server/store/claim.d.ts +59 -0
  24. package/dist/server/store/claim.js +97 -0
  25. package/dist/server/store/cronoton.d.ts +79 -0
  26. package/dist/server/store/cronoton.js +268 -0
  27. package/dist/server/store/errors.d.ts +26 -0
  28. package/dist/server/store/errors.js +40 -0
  29. package/dist/server/store/fires.d.ts +77 -0
  30. package/dist/server/store/fires.js +170 -0
  31. package/dist/server/store/index.d.ts +26 -0
  32. package/dist/server/store/index.js +33 -0
  33. package/dist/server/store/manual-batch.d.ts +38 -0
  34. package/dist/server/store/manual-batch.js +110 -0
  35. package/dist/server/store/mappers.d.ts +21 -0
  36. package/dist/server/store/mappers.js +62 -0
  37. package/dist/server/tick.d.ts +83 -0
  38. package/dist/server/tick.js +235 -0
  39. package/dist/server/types.d.ts +220 -0
  40. package/dist/server/types.js +14 -0
  41. package/package.json +14 -2
@@ -0,0 +1,97 @@
1
+ import { TICK_BATCH_LIMIT } from "../seams.js";
2
+ import { computeNextFire, } from "../../schedule.js";
3
+ // ── Terminal / advance writes ────────────────────────────────────────────────
4
+ /**
5
+ * Write the computed terminal intent: non-null → status + clear next_fire_at;
6
+ * null → no-op (recurring). The executor owns the COMPUTE; the store owns the
7
+ * WRITE.
8
+ */
9
+ export function applyTerminalIntent(id, terminalIntent, dep) {
10
+ if (terminalIntent == null)
11
+ return;
12
+ dep.db
13
+ .prepare(`UPDATE codex_cronotons SET status = ?, next_fire_at = NULL, modified_at = ? WHERE id = ?`)
14
+ .run(terminalIntent.status, new Date().toISOString(), id);
15
+ }
16
+ /** Recurring counterpart of applyTerminalIntent — advance next_fire_at + last_fire_at. */
17
+ export function advanceRecurring(id, nextDate, firedAt, dep) {
18
+ const now = new Date().toISOString();
19
+ dep.db
20
+ .prepare(`UPDATE codex_cronotons SET next_fire_at = ?, last_fire_at = ?, modified_at = ? WHERE id = ?`)
21
+ .run(nextDate.toISOString(), firedAt.toISOString(), now, id);
22
+ }
23
+ // ── Due selection + atomic claim ─────────────────────────────────────────────
24
+ /**
25
+ * Candidate due rows for the tick: active, with a non-null next_fire_at at or
26
+ * before `now`, oldest-first, capped at the batch limit. Each candidate must
27
+ * still be CLAIMED (claimDueCodexCronoton) before firing.
28
+ *
29
+ * EXCLUDES runtime-arg cronotons (`runtime_arg_keys IS NOT NULL`): their tx
30
+ * needs trigger-supplied string args, so the scheduler must never auto-fire
31
+ * them (a fire without the args would fail). They stay `active` so an external
32
+ * trigger endpoint can fire them WITH args; the scheduler simply skips them.
33
+ */
34
+ export function fetchDueCodexCronotons(now, limit = TICK_BATCH_LIMIT, dep) {
35
+ return dep.db
36
+ .prepare(`SELECT * FROM codex_cronotons
37
+ WHERE status = 'active' AND next_fire_at IS NOT NULL AND next_fire_at <= ?
38
+ AND runtime_arg_keys IS NULL
39
+ ORDER BY next_fire_at ASC LIMIT ?`)
40
+ .all(now.toISOString(), limit);
41
+ }
42
+ /**
43
+ * The atomic claim that closes the double-fire window. A single conditional
44
+ * UPDATE advances (recurring) or clears (one-time) `next_fire_at` BEFORE the
45
+ * caller's inline fire, so the row is no longer due/re-selectable the instant
46
+ * the claim commits. The caller fires ONLY when this returns `true`
47
+ * (changes === 1); `false` means another overlapping tick or a manual
48
+ * Execute-Now already claimed the row — skip it (no fire).
49
+ *
50
+ * Branch selection:
51
+ * - RECURRING → SET next_fire_at = computeNextFire(mode, config, now) at the
52
+ * FRESH `now` (avoids stale-now drift). The recurring row stays active with
53
+ * its advanced next-fire.
54
+ * - ONE-TIME → SET next_fire_at = NULL (un-re-selectable); the caller applies
55
+ * the terminal intent after the fire.
56
+ * - RECURRING whose computeNextFire returns null or throws mid-life (corrupt
57
+ * schedule_config_json) → SET next_fire_at = NULL so it stops re-selecting.
58
+ * A corrupt-config row cannot both stay-active AND not-fire-storm.
59
+ *
60
+ * The WHERE clause re-asserts the due predicate (status='active' AND
61
+ * next_fire_at IS NOT NULL AND next_fire_at <= now) so two racing claimers see
62
+ * exactly one win.
63
+ */
64
+ export function claimDueCodexCronoton(row, now, dep) {
65
+ const db = dep.db;
66
+ const nowIso = now.toISOString();
67
+ let computedNextIso;
68
+ if (row.schedule_mode === "one-time") {
69
+ computedNextIso = null;
70
+ }
71
+ else {
72
+ // Recurring: compute the next fire at the fresh `now`. A null (or a corrupt
73
+ // config that throws JSON.parse/computeNextFire) means clear next_fire_at so
74
+ // the row stops re-selecting. The parse MUST stay inside the try so a corrupt
75
+ // config is routed to the NULL branch, never thrown uncaught.
76
+ let next = null;
77
+ try {
78
+ next = computeNextFire(row.schedule_mode, JSON.parse(row.schedule_config_json), now);
79
+ }
80
+ catch {
81
+ next = null;
82
+ }
83
+ computedNextIso = next ? next.toISOString() : null;
84
+ }
85
+ // Literal `next_fire_at = NULL` for one-time + corrupt-recurring so the issued
86
+ // SQL self-documents the clear; a parameterized `= ?` for the recurring
87
+ // advance. The WHERE clause re-asserts the due predicate either way.
88
+ const whereDue = `WHERE id = ? AND status = 'active' AND next_fire_at IS NOT NULL AND next_fire_at <= ?`;
89
+ const result = computedNextIso === null
90
+ ? db
91
+ .prepare(`UPDATE codex_cronotons SET next_fire_at = NULL, last_fire_at = ?, modified_at = ? ${whereDue}`)
92
+ .run(nowIso, nowIso, row.id, nowIso)
93
+ : db
94
+ .prepare(`UPDATE codex_cronotons SET next_fire_at = ?, last_fire_at = ?, modified_at = ? ${whereDue}`)
95
+ .run(computedNextIso, nowIso, nowIso, row.id, nowIso);
96
+ return result.changes === 1;
97
+ }
@@ -0,0 +1,79 @@
1
+ import { type ScheduleConfig, type ScheduleMode } from "../../schedule.js";
2
+ import type { DbDep } from "../seams.js";
3
+ import type { CodexCronotonListItem, CodexCronotonRow, CodexTxConfig, CodexTxDefinition } from "../types.js";
4
+ export interface CommitCodexCronotonInput {
5
+ name: string;
6
+ description: string | null;
7
+ pactCode: string;
8
+ config: CodexTxConfig;
9
+ payload: Record<string, unknown>;
10
+ gasPayer: CodexTxDefinition["gasPayer"];
11
+ signers: CodexTxDefinition["signers"];
12
+ scheduleMode: ScheduleMode;
13
+ scheduleConfig: ScheduleConfig;
14
+ createdBy: string;
15
+ /** Optional fire-time server payload resolver name (e.g. 'stoicism-mint'). */
16
+ serverResolver?: string;
17
+ /** When true, the row may be fired by the external HMAC endpoint (default false). */
18
+ externalFireable?: boolean;
19
+ /** env-data keys supplied by a trigger at fire time (default none). Must be
20
+ * DISJOINT from the fixed payload keys — a runtime arg must never override a keyset. */
21
+ runtimeArgKeys?: string[];
22
+ }
23
+ interface CommitOpts extends DbDep {
24
+ now?: Date;
25
+ }
26
+ export declare function commitCodexCronoton(input: CommitCodexCronotonInput, opts: CommitOpts): {
27
+ id: string;
28
+ nextFireAt: string | null;
29
+ };
30
+ export declare function getCodexCronoton(id: string, dep: DbDep): CodexCronotonRow | null;
31
+ /**
32
+ * Find the id of the (single) cronoton bound to a given `server_resolver` name,
33
+ * or null. A provisioner for a server-resolved cronoton uses this for its
34
+ * idempotency key: a second provision finds the existing row instead of
35
+ * inserting a duplicate. Returns the most-recently-created match if (unexpectedly)
36
+ * more than one exists.
37
+ */
38
+ export declare function findCodexCronotonIdByServerResolver(serverResolver: string, dep: DbDep): string | null;
39
+ export declare function listCodexCronotons(params: {
40
+ limit?: number;
41
+ offset?: number;
42
+ status?: CodexCronotonRow["status"];
43
+ }, dep: DbDep): CodexCronotonListItem[];
44
+ export interface EditCodexCronotonPatch {
45
+ name?: string;
46
+ description?: string | null;
47
+ pactCode?: string;
48
+ config?: CodexTxConfig;
49
+ payload?: Record<string, unknown> | null;
50
+ gasPayer?: CodexTxDefinition["gasPayer"];
51
+ signers?: CodexTxDefinition["signers"];
52
+ scheduleMode?: ScheduleMode;
53
+ scheduleConfig?: ScheduleConfig;
54
+ /** Set/clear the fire-time server resolver. `null` clears it. */
55
+ serverResolver?: string | null;
56
+ }
57
+ /**
58
+ * Apply-at-next-fire edit. Recomputes next_fire_at when the schedule changes,
59
+ * re-gates AUTO-gas when config changes, and NEVER touches status (an edit
60
+ * never pauses or resumes). Returns the changed-field list + the (possibly
61
+ * recomputed) nextFireAt.
62
+ */
63
+ export declare function editCodexCronoton(id: string, patch: EditCodexCronotonPatch, opts: CommitOpts): {
64
+ changedFields: string[];
65
+ nextFireAt: string | null;
66
+ };
67
+ export declare function pauseCodexCronoton(id: string, dep: DbDep): {
68
+ status: "paused";
69
+ nextFireAt: string | null;
70
+ };
71
+ /** Resume recomputes next_fire_at from NOW so a stale paused row never fire-storms. */
72
+ export declare function resumeCodexCronoton(id: string, opts: CommitOpts): {
73
+ status: "active";
74
+ nextFireAt: string | null;
75
+ };
76
+ export declare function deleteCodexCronoton(id: string, dep: DbDep): {
77
+ fireCountAtDelete: number;
78
+ };
79
+ export {};
@@ -0,0 +1,268 @@
1
+ /**
2
+ * cronoton — the commit/read/find/list/edit/pause/resume/delete lifecycle for
3
+ * `codex_cronotons`.
4
+ *
5
+ * This is the plain (non-claim) CRUD half of the store: it validates and writes
6
+ * a definition, projects rows for the list view, applies at-next-fire edits, and
7
+ * moves a row through the pause/resume/delete transitions. The atomic
8
+ * claim-before-fire lives in `./claim.js`.
9
+ *
10
+ * Schedule math is imported, never reimplemented (REQ-16): {@link computeNextFire}
11
+ * runs at commit/edit/resume time through {@link computeNextOrReject}, which maps
12
+ * an {@link InvalidScheduleConfigError} to a typed {@link CodexCronotonValidationError}
13
+ * and treats a null next-fire as a "no future fires" reject. A TRIGGER-ONLY row
14
+ * (externally fireable OR declaring runtime args) carries NO schedule at all — its
15
+ * `next_fire_at` stays NULL and the schedule engine is never consulted for it.
16
+ */
17
+ import crypto from "node:crypto";
18
+ import { computeNextFire, InvalidScheduleConfigError, } from "../../schedule.js";
19
+ import { runtimeArgKeysCollide } from "../pure/runtime-args.js";
20
+ import { CodexCronotonValidationError, TerminalCronotonError } from "./errors.js";
21
+ import { assertAutoGasGate, rowExternalFireable, rowRuntimeArgKeys, } from "./mappers.js";
22
+ /** Compute the first next-fire, mapping engine errors to a typed reject. */
23
+ function computeNextOrReject(mode, config, now) {
24
+ let next;
25
+ try {
26
+ next = computeNextFire(mode, config, now);
27
+ }
28
+ catch (err) {
29
+ if (err instanceof InvalidScheduleConfigError) {
30
+ throw new CodexCronotonValidationError(err.message);
31
+ }
32
+ throw err;
33
+ }
34
+ if (!next) {
35
+ throw new CodexCronotonValidationError("schedule has no future fires");
36
+ }
37
+ return next;
38
+ }
39
+ export function commitCodexCronoton(input, opts) {
40
+ if (typeof input.name !== "string" || input.name.trim() === "") {
41
+ throw new CodexCronotonValidationError("name must be a non-empty string");
42
+ }
43
+ if (typeof input.pactCode !== "string") {
44
+ throw new CodexCronotonValidationError("pactCode must be a string");
45
+ }
46
+ if (!input.config || typeof input.config.chainId !== "string") {
47
+ throw new CodexCronotonValidationError("config.chainId must be a string");
48
+ }
49
+ if (!Array.isArray(input.signers)) {
50
+ throw new CodexCronotonValidationError("signers must be an array");
51
+ }
52
+ if (!input.gasPayer || typeof input.gasPayer.type !== "string") {
53
+ throw new CodexCronotonValidationError("gasPayer.type must be a string");
54
+ }
55
+ assertAutoGasGate(input.config);
56
+ // Runtime-arg keys must be DISJOINT from the fixed payload — a trigger-supplied
57
+ // arg must never be able to clobber a fixed key (e.g. a keyset).
58
+ const runtimeArgKeys = input.runtimeArgKeys ?? [];
59
+ if (runtimeArgKeysCollide(input.payload ?? {}, runtimeArgKeys)) {
60
+ throw new CodexCronotonValidationError("runtimeArgKeys must be disjoint from payload keys");
61
+ }
62
+ // Runtime-arg + server-resolver are mutually exclusive: both inject payload at
63
+ // fire time, so a server-resolver row can never also carry runtime args.
64
+ if (input.serverResolver && runtimeArgKeys.length > 0) {
65
+ throw new CodexCronotonValidationError("server-resolver rows cannot declare runtime args");
66
+ }
67
+ const now = opts.now ?? new Date();
68
+ // A TRIGGER-ONLY cronoton (externally fireable OR declaring runtime args) fires
69
+ // on demand — never on a timer — so it carries NO schedule: skip the next-fire
70
+ // computation and store next_fire_at = NULL. The scheduler's
71
+ // `next_fire_at IS NOT NULL` gate then skips it.
72
+ const triggerOnly = input.externalFireable === true || runtimeArgKeys.length > 0;
73
+ const nextFireAt = triggerOnly
74
+ ? null
75
+ : computeNextOrReject(input.scheduleMode, input.scheduleConfig, now).toISOString();
76
+ const id = crypto.randomUUID();
77
+ const nowIso = now.toISOString();
78
+ opts.db
79
+ .prepare(`INSERT INTO codex_cronotons
80
+ (id, name, description, pact_code, config_json, payload_json,
81
+ gas_payer_json, signers_json, schedule_mode, schedule_config_json,
82
+ server_resolver, external_fireable, runtime_arg_keys, status,
83
+ next_fire_at, last_fire_at, created_at, modified_at, created_by)
84
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`)
85
+ .run(id, input.name.trim(), input.description, input.pactCode, JSON.stringify(input.config), input.payload ? JSON.stringify(input.payload) : null, JSON.stringify(input.gasPayer), JSON.stringify(input.signers), input.scheduleMode, JSON.stringify(input.scheduleConfig), input.serverResolver ?? null, input.externalFireable ? 1 : 0, runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null, nextFireAt, nowIso, nowIso, input.createdBy);
86
+ return { id, nextFireAt };
87
+ }
88
+ export function getCodexCronoton(id, dep) {
89
+ const row = dep.db
90
+ .prepare("SELECT * FROM codex_cronotons WHERE id = ?")
91
+ .get(id);
92
+ return row ?? null;
93
+ }
94
+ /**
95
+ * Find the id of the (single) cronoton bound to a given `server_resolver` name,
96
+ * or null. A provisioner for a server-resolved cronoton uses this for its
97
+ * idempotency key: a second provision finds the existing row instead of
98
+ * inserting a duplicate. Returns the most-recently-created match if (unexpectedly)
99
+ * more than one exists.
100
+ */
101
+ export function findCodexCronotonIdByServerResolver(serverResolver, dep) {
102
+ const row = dep.db
103
+ .prepare(`SELECT id FROM codex_cronotons WHERE server_resolver = ?
104
+ ORDER BY created_at DESC LIMIT 1`)
105
+ .get(serverResolver);
106
+ return row?.id ?? null;
107
+ }
108
+ export function listCodexCronotons(params, dep) {
109
+ const limit = Math.min(Math.max(params.limit ?? 50, 1), 200);
110
+ const offset = Math.max(params.offset ?? 0, 0);
111
+ const db = dep.db;
112
+ const rows = (params.status
113
+ ? db
114
+ .prepare(`SELECT id, name, schedule_mode, status, next_fire_at, last_fire_at,
115
+ created_at, modified_at, created_by
116
+ FROM codex_cronotons WHERE status = ?
117
+ ORDER BY created_at DESC LIMIT ? OFFSET ?`)
118
+ .all(params.status, limit, offset)
119
+ : db
120
+ .prepare(`SELECT id, name, schedule_mode, status, next_fire_at, last_fire_at,
121
+ created_at, modified_at, created_by
122
+ FROM codex_cronotons
123
+ ORDER BY created_at DESC LIMIT ? OFFSET ?`)
124
+ .all(limit, offset));
125
+ return rows.map((r) => ({
126
+ id: r.id,
127
+ name: r.name,
128
+ scheduleMode: r.schedule_mode,
129
+ status: r.status,
130
+ nextFireAt: r.next_fire_at,
131
+ lastFireAt: r.last_fire_at,
132
+ createdAt: r.created_at,
133
+ modifiedAt: r.modified_at,
134
+ createdBy: r.created_by,
135
+ }));
136
+ }
137
+ /**
138
+ * Apply-at-next-fire edit. Recomputes next_fire_at when the schedule changes,
139
+ * re-gates AUTO-gas when config changes, and NEVER touches status (an edit
140
+ * never pauses or resumes). Returns the changed-field list + the (possibly
141
+ * recomputed) nextFireAt.
142
+ */
143
+ export function editCodexCronoton(id, patch, opts) {
144
+ const db = opts.db;
145
+ const row = getCodexCronoton(id, { db });
146
+ if (!row)
147
+ throw new CodexCronotonValidationError("not found");
148
+ const changedFields = [];
149
+ let nextName = row.name;
150
+ let nextDescription = row.description;
151
+ let nextPactCode = row.pact_code;
152
+ let nextConfigJson = row.config_json;
153
+ let nextPayloadJson = row.payload_json;
154
+ let nextGasPayerJson = row.gas_payer_json;
155
+ let nextSignersJson = row.signers_json;
156
+ let nextScheduleMode = row.schedule_mode;
157
+ let nextScheduleConfigJson = row.schedule_config_json;
158
+ let nextServerResolver = row.server_resolver;
159
+ let nextFireAt = row.next_fire_at;
160
+ if (typeof patch.name === "string" &&
161
+ patch.name.trim() !== "" &&
162
+ patch.name.trim() !== row.name) {
163
+ nextName = patch.name.trim();
164
+ changedFields.push("name");
165
+ }
166
+ if (patch.description !== undefined && patch.description !== row.description) {
167
+ nextDescription = patch.description;
168
+ changedFields.push("description");
169
+ }
170
+ if (typeof patch.pactCode === "string" && patch.pactCode !== row.pact_code) {
171
+ nextPactCode = patch.pactCode;
172
+ changedFields.push("pactCode");
173
+ }
174
+ if (patch.config) {
175
+ assertAutoGasGate(patch.config);
176
+ nextConfigJson = JSON.stringify(patch.config);
177
+ changedFields.push("config");
178
+ }
179
+ if (patch.payload !== undefined) {
180
+ // Re-assert the runtime-arg disjointness invariant at EDIT time (mirrors
181
+ // commit). runtime_arg_keys is immutable via edit, but payload is mutable —
182
+ // without this, a payload key equal to a declared runtime-arg key could slip
183
+ // in and make every fire throw at applyRuntimeArgs.
184
+ if (runtimeArgKeysCollide(patch.payload ?? {}, rowRuntimeArgKeys(row))) {
185
+ throw new CodexCronotonValidationError("payload keys must be disjoint from runtimeArgKeys");
186
+ }
187
+ nextPayloadJson = patch.payload ? JSON.stringify(patch.payload) : null;
188
+ changedFields.push("payload");
189
+ }
190
+ if (patch.gasPayer) {
191
+ nextGasPayerJson = JSON.stringify(patch.gasPayer);
192
+ changedFields.push("gasPayer");
193
+ }
194
+ if (patch.signers) {
195
+ nextSignersJson = JSON.stringify(patch.signers);
196
+ changedFields.push("signers");
197
+ }
198
+ if (patch.serverResolver !== undefined) {
199
+ nextServerResolver = patch.serverResolver;
200
+ changedFields.push("serverResolver");
201
+ }
202
+ let scheduleChanged = false;
203
+ if (patch.scheduleMode && patch.scheduleConfig) {
204
+ nextScheduleMode = patch.scheduleMode;
205
+ nextScheduleConfigJson = JSON.stringify(patch.scheduleConfig);
206
+ scheduleChanged = true;
207
+ changedFields.push("schedule");
208
+ }
209
+ // A trigger-only row (externally fireable OR runtime-arg) has NO schedule (its
210
+ // next_fire_at is NULL and the scheduler skips it) — never resurrect a next-fire
211
+ // for it, even if a schedule patch slips through. Keep next_fire_at as-is (NULL).
212
+ const rowTriggerOnly = rowExternalFireable(row) || rowRuntimeArgKeys(row).length > 0;
213
+ if (scheduleChanged && !rowTriggerOnly) {
214
+ const next = computeNextOrReject(nextScheduleMode, JSON.parse(nextScheduleConfigJson), opts.now ?? new Date());
215
+ nextFireAt = next.toISOString();
216
+ }
217
+ if (changedFields.length === 0) {
218
+ return { changedFields, nextFireAt };
219
+ }
220
+ db.prepare(`UPDATE codex_cronotons
221
+ SET name = ?, description = ?, pact_code = ?, config_json = ?,
222
+ payload_json = ?, gas_payer_json = ?, signers_json = ?,
223
+ schedule_mode = ?, schedule_config_json = ?, server_resolver = ?,
224
+ next_fire_at = ?, modified_at = ?
225
+ WHERE id = ?`).run(nextName, nextDescription, nextPactCode, nextConfigJson, nextPayloadJson, nextGasPayerJson, nextSignersJson, nextScheduleMode, nextScheduleConfigJson, nextServerResolver, nextFireAt, (opts.now ?? new Date()).toISOString(), id);
226
+ return { changedFields, nextFireAt };
227
+ }
228
+ // ── Pause / resume / delete ──────────────────────────────────────────────────
229
+ function assertNotTerminal(row) {
230
+ if (row.status === "completed" || row.status === "error") {
231
+ throw new TerminalCronotonError(row.status);
232
+ }
233
+ }
234
+ export function pauseCodexCronoton(id, dep) {
235
+ const db = dep.db;
236
+ const row = getCodexCronoton(id, { db });
237
+ if (!row)
238
+ throw new CodexCronotonValidationError("not found");
239
+ assertNotTerminal(row);
240
+ db.prepare(`UPDATE codex_cronotons SET status = 'paused', modified_at = ? WHERE id = ?`).run(new Date().toISOString(), id);
241
+ return { status: "paused", nextFireAt: row.next_fire_at };
242
+ }
243
+ /** Resume recomputes next_fire_at from NOW so a stale paused row never fire-storms. */
244
+ export function resumeCodexCronoton(id, opts) {
245
+ const db = opts.db;
246
+ const row = getCodexCronoton(id, { db });
247
+ if (!row)
248
+ throw new CodexCronotonValidationError("not found");
249
+ assertNotTerminal(row);
250
+ const now = opts.now ?? new Date();
251
+ // A trigger-only row (externally fireable OR runtime-arg) has no schedule — resume
252
+ // it to 'active' but keep next_fire_at NULL so the scheduler still never picks it up.
253
+ const rowTriggerOnly = rowExternalFireable(row) || rowRuntimeArgKeys(row).length > 0;
254
+ const nextFireAt = rowTriggerOnly
255
+ ? null
256
+ : computeNextOrReject(row.schedule_mode, JSON.parse(row.schedule_config_json), now).toISOString();
257
+ db.prepare(`UPDATE codex_cronotons SET status = 'active', next_fire_at = ?, modified_at = ? WHERE id = ?`).run(nextFireAt, now.toISOString(), id);
258
+ return { status: "active", nextFireAt };
259
+ }
260
+ export function deleteCodexCronoton(id, dep) {
261
+ const db = dep.db;
262
+ const countRow = db
263
+ .prepare("SELECT COUNT(*) AS c FROM codex_cronoton_fires WHERE codex_cronoton_id = ?")
264
+ .get(id);
265
+ const fireCountAtDelete = countRow?.c ?? 0;
266
+ db.prepare("DELETE FROM codex_cronotons WHERE id = ?").run(id);
267
+ return { fireCountAtDelete };
268
+ }
@@ -0,0 +1,26 @@
1
+ /** Generic validation/schedule reject — the route maps it to 400 + the reason. */
2
+ export declare class CodexCronotonValidationError extends Error {
3
+ constructor(message: string);
4
+ }
5
+ /** AUTO-gas commit-gate breach — an AUTO row needs a concrete calibrated limit. */
6
+ export declare class AutoGasGateError extends CodexCronotonValidationError {
7
+ constructor(message?: string);
8
+ }
9
+ /** Refusal to pause/resume/fire a spent one-time (completed/error) row. */
10
+ export declare class TerminalCronotonError extends Error {
11
+ constructor(status: string);
12
+ }
13
+ /** A batch is already running for this cronoton — the route maps this to 409. */
14
+ export declare class ManualBatchActiveError extends Error {
15
+ constructor();
16
+ }
17
+ /**
18
+ * Batch count bounds + fixed cadence. These back the injectable Config seam as
19
+ * its DEFAULTS: consumer sites read `config?.manualBatch?.<field> ?? <CONSTANT>`
20
+ * (min/max/intervalSeconds) so the constants stay the fallback contract.
21
+ */
22
+ export declare const MANUAL_BATCH_MIN = 2;
23
+ export declare const MANUAL_BATCH_MAX = 60;
24
+ export declare const MANUAL_BATCH_INTERVAL_SECONDS = 60;
25
+ /** Default per-tick due-selection ceiling — backs `config.tickBatchLimit`. */
26
+ export declare const TICK_BATCH_LIMIT = 100;
@@ -0,0 +1,40 @@
1
+ // ── Typed errors ─────────────────────────────────────────────────────────────
2
+ /** Generic validation/schedule reject — the route maps it to 400 + the reason. */
3
+ export class CodexCronotonValidationError extends Error {
4
+ constructor(message) {
5
+ super(message);
6
+ this.name = 'CodexCronotonValidationError';
7
+ }
8
+ }
9
+ /** AUTO-gas commit-gate breach — an AUTO row needs a concrete calibrated limit. */
10
+ export class AutoGasGateError extends CodexCronotonValidationError {
11
+ constructor(message = 'AUTO-gas row requires a concrete calibrated gasLimit > 0') {
12
+ super(message);
13
+ this.name = 'AutoGasGateError';
14
+ }
15
+ }
16
+ /** Refusal to pause/resume/fire a spent one-time (completed/error) row. */
17
+ export class TerminalCronotonError extends Error {
18
+ constructor(status) {
19
+ super(`codex cronoton is terminal (status='${status}'): a spent one-time entry cannot be reactivated or re-fired`);
20
+ this.name = 'TerminalCronotonError';
21
+ }
22
+ }
23
+ /** A batch is already running for this cronoton — the route maps this to 409. */
24
+ export class ManualBatchActiveError extends Error {
25
+ constructor() {
26
+ super('a manual execution batch is already running for this codex cronoton');
27
+ this.name = 'ManualBatchActiveError';
28
+ }
29
+ }
30
+ // ── Constants ────────────────────────────────────────────────────────────────
31
+ /**
32
+ * Batch count bounds + fixed cadence. These back the injectable Config seam as
33
+ * its DEFAULTS: consumer sites read `config?.manualBatch?.<field> ?? <CONSTANT>`
34
+ * (min/max/intervalSeconds) so the constants stay the fallback contract.
35
+ */
36
+ export const MANUAL_BATCH_MIN = 2;
37
+ export const MANUAL_BATCH_MAX = 60;
38
+ export const MANUAL_BATCH_INTERVAL_SECONDS = 60;
39
+ /** Default per-tick due-selection ceiling — backs `config.tickBatchLimit`. */
40
+ export const TICK_BATCH_LIMIT = 100;
@@ -0,0 +1,77 @@
1
+ import type { CodexCronotonFireRow, FireTxKey } from "../types.js";
2
+ import { type DbDep, type ResolveFireMode } from "../seams.js";
3
+ /**
4
+ * Carries the injected DB handle plus the optional {@link ResolveFireMode} seam
5
+ * into the fire writes. The tick (Phase 4) threads its context through this
6
+ * shape; an omitted `resolveFireMode` defaults to `() => 'live'` (the REQ-05
7
+ * default — NOT the Hub's implicit `'test'`).
8
+ */
9
+ export interface FireDep extends DbDep {
10
+ resolveFireMode?: ResolveFireMode;
11
+ }
12
+ /** Input to {@link recordFire}. Declared here (the Hub's fires block owns it), not in `../types.js`. */
13
+ export interface RecordFireInput {
14
+ codexCronotonId: string;
15
+ jobId: string | null;
16
+ firedAt: string;
17
+ status: "success" | "failure" | "running" | "nothing";
18
+ requestKey?: string;
19
+ chainId?: string;
20
+ errorMessage?: string;
21
+ chainResponse?: unknown;
22
+ definitionFingerprint: string;
23
+ /** Per-tx request keys for a multi-tx fire. */
24
+ txKeys?: FireTxKey[];
25
+ }
26
+ /** Insert exactly ONE fire row + bump the parent's last_fire_at. */
27
+ export declare function recordFire(input: RecordFireInput, dep: FireDep): string;
28
+ /**
29
+ * Open a fire row in the non-terminal `running` state the MOMENT a multi-tx
30
+ * (background-job) fire is dispatched, so the operator sees the entry at once.
31
+ * The worker later appends per-tx keys via {@link appendFireTxKeys} and flips it
32
+ * terminal via {@link finalizeFire}. Mirrors `recordFire`'s last_fire_at bump.
33
+ */
34
+ export declare function createRunningFire(input: {
35
+ codexCronotonId: string;
36
+ jobId: string | null;
37
+ firedAt: string;
38
+ definitionFingerprint: string;
39
+ }, dep: FireDep): string;
40
+ /** Link a fire row to the background job that executes it (best-effort). */
41
+ export declare function setFireJobId(fireId: string, jobId: string, dep: DbDep): void;
42
+ /**
43
+ * Append one or more per-tx keys to a fire's `tx_keys_json` (read-modify-write,
44
+ * de-duplicated by requestKey so a resumed/retried leg never double-lists). Safe
45
+ * to call repeatedly during a multi-minute run; the fire history reads the
46
+ * growing array on each refresh. A missing fire is a no-op (never throws).
47
+ */
48
+ export declare function appendFireTxKeys(fireId: string, txKeys: FireTxKey[], dep: DbDep): void;
49
+ /**
50
+ * Flip a `running` fire to its terminal outcome. Sets status + the headline
51
+ * request key + error + structured chain response, and merges any final tx keys.
52
+ */
53
+ export declare function finalizeFire(fireId: string, result: {
54
+ status: "success" | "failure" | "nothing";
55
+ requestKey?: string | null;
56
+ chainId?: string | null;
57
+ errorMessage?: string | null;
58
+ chainResponse?: unknown;
59
+ txKeys?: FireTxKey[];
60
+ }, dep: DbDep): void;
61
+ /** Paginated fire history for a cronoton, newest-first (limit clamped 1..100, default 20). */
62
+ export declare function listFires(id: string, params: {
63
+ limit?: number;
64
+ offset?: number;
65
+ } | undefined, dep: DbDep): {
66
+ fires: CodexCronotonFireRow[];
67
+ total: number;
68
+ };
69
+ /**
70
+ * Manual recovery: reconcile a FAILED fire to its true on-chain outcome by
71
+ * attaching the confirmed request key. Flips status failure→success, stamps
72
+ * `recovered_at`, and clears the stale transport error (e.g. an nginx 504 that
73
+ * hid a successful submit). Returns true if a failed row was updated, false if
74
+ * the fire wasn't found OR wasn't in `failure` (idempotent — a second call is a
75
+ * no-op).
76
+ */
77
+ export declare function recoverFire(fireId: string, requestKey: string, dep: DbDep): boolean;