@ancientpantheon/khronoton-core 0.1.1 → 0.3.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 (67) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +83 -3
  3. package/dist/PactCodeMirror-HQTGE2K3.js +64 -0
  4. package/dist/chunk-DK4CDPXH.js +379 -0
  5. package/dist/chunk-U3F5HEHO.js +1639 -0
  6. package/dist/context-BKtdrA2B.d.ts +363 -0
  7. package/dist/handlers/batch.d.ts +21 -0
  8. package/dist/handlers/batch.js +57 -0
  9. package/dist/handlers/context.d.ts +94 -0
  10. package/dist/handlers/context.js +75 -0
  11. package/dist/handlers/cronoton.d.ts +70 -0
  12. package/dist/handlers/cronoton.js +165 -0
  13. package/dist/handlers/execute.d.ts +30 -0
  14. package/dist/handlers/execute.js +227 -0
  15. package/dist/handlers/http.d.ts +85 -0
  16. package/dist/handlers/http.js +84 -0
  17. package/dist/handlers/index.d.ts +27 -0
  18. package/dist/handlers/index.js +34 -0
  19. package/dist/handlers/read.d.ts +29 -0
  20. package/dist/handlers/read.js +94 -0
  21. package/dist/hooks/index.d.ts +143 -0
  22. package/dist/hooks/index.js +2 -0
  23. package/dist/provider/index.d.ts +421 -0
  24. package/dist/provider/index.js +675 -0
  25. package/dist/server/executor-signers.d.ts +29 -0
  26. package/dist/server/executor-signers.js +60 -0
  27. package/dist/server/executor.d.ts +53 -0
  28. package/dist/server/executor.js +280 -0
  29. package/dist/server/index.d.ts +27 -0
  30. package/dist/server/index.js +51 -0
  31. package/dist/server/loop.d.ts +36 -0
  32. package/dist/server/loop.js +51 -0
  33. package/dist/server/pure/capability.d.ts +31 -0
  34. package/dist/server/pure/capability.js +63 -0
  35. package/dist/server/pure/fingerprint.d.ts +8 -0
  36. package/dist/server/pure/fingerprint.js +44 -0
  37. package/dist/server/pure/runtime-args.d.ts +34 -0
  38. package/dist/server/pure/runtime-args.js +99 -0
  39. package/dist/server/resolvers.d.ts +140 -0
  40. package/dist/server/resolvers.js +200 -0
  41. package/dist/server/schema.d.ts +31 -0
  42. package/dist/server/schema.js +93 -0
  43. package/dist/server/seams.d.ts +231 -0
  44. package/dist/server/seams.js +34 -0
  45. package/dist/server/store/claim.d.ts +59 -0
  46. package/dist/server/store/claim.js +97 -0
  47. package/dist/server/store/cronoton.d.ts +79 -0
  48. package/dist/server/store/cronoton.js +268 -0
  49. package/dist/server/store/errors.d.ts +26 -0
  50. package/dist/server/store/errors.js +40 -0
  51. package/dist/server/store/fires.d.ts +77 -0
  52. package/dist/server/store/fires.js +170 -0
  53. package/dist/server/store/index.d.ts +26 -0
  54. package/dist/server/store/index.js +33 -0
  55. package/dist/server/store/manual-batch.d.ts +38 -0
  56. package/dist/server/store/manual-batch.js +110 -0
  57. package/dist/server/store/mappers.d.ts +21 -0
  58. package/dist/server/store/mappers.js +62 -0
  59. package/dist/server/tick.d.ts +83 -0
  60. package/dist/server/tick.js +235 -0
  61. package/dist/server/types.d.ts +220 -0
  62. package/dist/server/types.js +14 -0
  63. package/dist/types-u_nUX1Bg.d.ts +222 -0
  64. package/dist/ui/index.d.ts +235 -0
  65. package/dist/ui/index.js +3646 -0
  66. package/dist/ui.css +35 -0
  67. package/package.json +64 -5
@@ -0,0 +1,231 @@
1
+ /**
2
+ * The six injection seams the server automaton is built against.
3
+ *
4
+ * Every host-specific capability the Hub executor/store reached for directly
5
+ * (`@stoachain/*` runtime, the codex key resolver, the ambient SQLite handle,
6
+ * the audit log, the fire-mode signal, the tuning constants) is inverted here
7
+ * into a narrow, dependency-free contract the consumer injects. This module
8
+ * declares ONLY interfaces, type aliases, and the module-level default
9
+ * constants — no orchestration logic. It imports nothing from `@stoachain/*`
10
+ * and nothing from `better-sqlite3`; the carrier types
11
+ * (`IKadenaKeypair`, `UniversalKeypair`, `IUnsignedCommand`) are genericized
12
+ * and declared here so the emitted `.d.ts` carries zero external module
13
+ * references.
14
+ */
15
+ /**
16
+ * A resolved signing keypair returned by {@link KeyResolver}.
17
+ *
18
+ * `privateKey` here is the raw signing secret (hex). Note the field-name
19
+ * divergence from {@link UniversalKeypair}, whose equivalent field is
20
+ * `secretKey`; a consumer mapping a resolver result into a signer payload must
21
+ * copy `privateKey -> secretKey`. `seedType` is genericized to `string`
22
+ * (the Hub narrowed it to a `@stoachain` seed-type union). The derived-seed
23
+ * WASM-signing path carries `encryptedSecretKey` + `password` through.
24
+ */
25
+ export interface IKadenaKeypair {
26
+ publicKey: string;
27
+ privateKey: string;
28
+ seedType: string;
29
+ encryptedSecretKey?: string;
30
+ password?: string;
31
+ }
32
+ /**
33
+ * Resolves signer public keys to their keypairs and enumerates the pubkeys the
34
+ * backing key store owns. Mirrors the Hub `CodexKeyResolver`: async lookups
35
+ * and a `Set<string>` membership view.
36
+ */
37
+ export interface KeyResolver {
38
+ /** Resolve a signer public key to its keypair; rejects if not owned. */
39
+ getKeyPairByPublicKey(publicKey: string): Promise<IKadenaKeypair>;
40
+ /** Enumerate every public key the backing store can sign for. */
41
+ listCodexPubs(): Promise<Set<string>>;
42
+ /**
43
+ * Optional last-resort resolution for a foreign key not in the store. A
44
+ * headless consumer with no interactive prompt may omit this or reject
45
+ * fast — a signer whose pubkey is unknown then fails at build time.
46
+ */
47
+ requestForeignKey?(publicKey: string): Promise<string>;
48
+ }
49
+ /**
50
+ * A signer keypair as consumed by {@link ChainRuntime.universalSignTransaction}.
51
+ *
52
+ * Note `secretKey` here versus `privateKey` on {@link IKadenaKeypair}: the two
53
+ * carriers describe the same secret under different field names, so a consumer
54
+ * bridging resolver output into a signer must remap the field. `seedType` is
55
+ * genericized to `string`.
56
+ */
57
+ export interface UniversalKeypair {
58
+ publicKey: string;
59
+ secretKey: string;
60
+ seedType: string;
61
+ encryptedSecretKey?: string;
62
+ password?: string;
63
+ }
64
+ /**
65
+ * A genericized unsigned Kadena command (the Hub imported this from
66
+ * `@stoachain/kadena-stoic-legacy/types`). Structural shape only, so a real
67
+ * Kadena unsigned command satisfies it without pulling the chain dependency.
68
+ */
69
+ export interface IUnsignedCommand {
70
+ cmd: string;
71
+ hash: string;
72
+ sigs: Array<{
73
+ sig?: string;
74
+ } | undefined>;
75
+ }
76
+ /** The dirty-read (local simulation) result from {@link ChainRuntime}. */
77
+ export interface DirtyReadResult {
78
+ result: {
79
+ status: string;
80
+ error?: {
81
+ message?: string;
82
+ };
83
+ data?: unknown;
84
+ };
85
+ gas?: number;
86
+ }
87
+ /** The listen (confirmation) result from {@link ChainRuntime}. */
88
+ export interface ListenResult {
89
+ result: {
90
+ status: string;
91
+ error?: {
92
+ message?: string;
93
+ };
94
+ };
95
+ reqKey?: string;
96
+ }
97
+ /** A network client bound to a single Pact endpoint URL. */
98
+ export interface ChainClient {
99
+ dirtyRead(tx: unknown): Promise<DirtyReadResult>;
100
+ submit(tx: unknown): Promise<{
101
+ requestKey: string;
102
+ }>;
103
+ listen(desc: unknown): Promise<ListenResult>;
104
+ }
105
+ /**
106
+ * The chain runtime seam — every `@stoachain/*` runtime value the executor
107
+ * reaches for, inverted into one injectable object. Ported from the Hub's
108
+ * private `StoachainRuntime` interface, with the ambient constants renamed to
109
+ * seam-neutral names: `KADENA_NETWORK -> networkId`,
110
+ * `STOA_AUTONOMIC_OURONETGASSTATION -> gasStationAccount`,
111
+ * `KADENA_NAMESPACE -> namespace`. Deliberately excludes `pollRequestKeys`
112
+ * (the executor confirms via `listen`, never polls).
113
+ */
114
+ export interface ChainRuntime {
115
+ Pact: {
116
+ builder: {
117
+ execution(code: string): unknown;
118
+ };
119
+ };
120
+ createClient(url: string): ChainClient;
121
+ isSignedTransaction(tx: unknown): boolean;
122
+ universalSignTransaction(tx: IUnsignedCommand, keypairs: UniversalKeypair[]): Promise<unknown>;
123
+ calculateAutoGasLimit(gas: number): number;
124
+ anuToStoa(anu: number): number;
125
+ getPactUrl(chainId: string): string;
126
+ networkId: string;
127
+ namespace: string;
128
+ gasStationAccount: string;
129
+ }
130
+ /**
131
+ * A prepared statement — the subset of the better-sqlite3 `Statement` surface
132
+ * the store actually calls. Declared structurally (owned here, NOT re-exported
133
+ * from `better-sqlite3`) so the emitted `.d.ts` references no external DB
134
+ * module; a real better-sqlite3 `Statement` satisfies it.
135
+ */
136
+ export interface Statement {
137
+ run(...params: unknown[]): {
138
+ changes: number;
139
+ lastInsertRowid: number | bigint;
140
+ };
141
+ get(...params: unknown[]): unknown;
142
+ all(...params: unknown[]): unknown[];
143
+ }
144
+ /**
145
+ * The minimal synchronous SQL handle the store and `installSchema` require —
146
+ * `exec` for DDL, `prepare(...)` for parameterized reads/writes. A real
147
+ * better-sqlite3 `Database` instance structurally satisfies this, so no
148
+ * `better-sqlite3` import (or `@types/better-sqlite3` dependency) leaks into
149
+ * the public `/server` surface. `pragma`/`transaction` are intentionally
150
+ * omitted — no store function needs them.
151
+ */
152
+ export interface Database {
153
+ exec(sql: string): unknown;
154
+ prepare(sql: string): Statement;
155
+ }
156
+ /**
157
+ * Carries the injected DB handle into store calls.
158
+ *
159
+ * Divergence from the Hub's `resolveDb(dep) = dep?.db ?? getDb()`: this package
160
+ * has no ambient `getDb()` fallback, so the handle is REQUIRED — the consumer
161
+ * always injects a handle at the call boundary.
162
+ */
163
+ export interface DbDep {
164
+ db: Database;
165
+ }
166
+ /** The structured event passed to an {@link OnAudit} sink. */
167
+ export interface AuditEvent {
168
+ action: string;
169
+ result: string;
170
+ targetKind: string;
171
+ targetId: string;
172
+ detail: unknown;
173
+ }
174
+ /**
175
+ * Audit sink invoked on each mutating action. May be sync or async. The
176
+ * default is a no-op: `() => {}` — a consumer wanting an audit trail injects
177
+ * its own writer.
178
+ */
179
+ export type OnAudit = (event: AuditEvent) => void | Promise<void>;
180
+ /** The documented no-op default for {@link OnAudit}. */
181
+ export declare const defaultOnAudit: OnAudit;
182
+ /**
183
+ * Resolves a cronoton id to its effective fire mode. Strictly SYNCHRONOUS (no
184
+ * `Promise` in the union): better-sqlite3 is a synchronous driver and the store
185
+ * binds the result directly into the fire-record INSERT. A consumer needing
186
+ * async fire-mode resolution pre-resolves before invoking the tick.
187
+ *
188
+ * The default resolves to `'live'`. A consumer may honor a per-row
189
+ * `fire_mode_override = 'live'` first, then fall back to a global signal.
190
+ */
191
+ export type ResolveFireMode = (cronotonId: string) => 'test' | 'live';
192
+ /** The documented default for {@link ResolveFireMode}: always `'live'`. */
193
+ export declare const defaultResolveFireMode: ResolveFireMode;
194
+ /**
195
+ * Tuning knobs for the automaton. Every field maps to a module-level default
196
+ * constant below; a consumer passes a `Partial<Config>` and each consumer site
197
+ * reads `config?.<field> ?? <MODULE_DEFAULT>`, so an injected value takes
198
+ * effect and an omitted one falls back.
199
+ *
200
+ * `gasPriceFloor` and `ttl` are intentionally absent: the Hub never clamped
201
+ * gasPrice/ttl (the executor uses the per-cronoton `definition.config` values
202
+ * directly), so exposing them as injectable would misrepresent the behavior.
203
+ */
204
+ export interface Config {
205
+ tickIntervalMs: number;
206
+ listenTimeoutMs: number;
207
+ autoGasCeiling: number;
208
+ singleTxGasGuard: number;
209
+ tickBatchLimit: number;
210
+ manualBatch: {
211
+ min: number;
212
+ max: number;
213
+ intervalSeconds: number;
214
+ };
215
+ }
216
+ /** Default tick cadence (30s) — {@link Config.tickIntervalMs}. */
217
+ export declare const TICK_INTERVAL_MS = 30000;
218
+ /** Default listen (confirmation) timeout: 5 minutes — {@link Config.listenTimeoutMs}. */
219
+ export declare const LISTEN_TIMEOUT_MS = 300000;
220
+ /** Default auto-gas simulation ceiling — {@link Config.autoGasCeiling}. */
221
+ export declare const AUTO_GAS_CEILING = 2000000;
222
+ /** Default single-transaction gas guard — {@link Config.singleTxGasGuard}. */
223
+ export declare const SINGLE_TX_GAS_GUARD = 1600000;
224
+ /** Default max cronotons processed per tick — {@link Config.tickBatchLimit}. */
225
+ export declare const TICK_BATCH_LIMIT = 100;
226
+ /** Default manual-batch minimum size — {@link Config.manualBatch}.min. */
227
+ export declare const MANUAL_BATCH_MIN = 2;
228
+ /** Default manual-batch maximum size — {@link Config.manualBatch}.max. */
229
+ export declare const MANUAL_BATCH_MAX = 60;
230
+ /** Default manual-batch inter-fire interval (seconds) — {@link Config.manualBatch}.intervalSeconds. */
231
+ export declare const MANUAL_BATCH_INTERVAL_SECONDS = 60;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The six injection seams the server automaton is built against.
3
+ *
4
+ * Every host-specific capability the Hub executor/store reached for directly
5
+ * (`@stoachain/*` runtime, the codex key resolver, the ambient SQLite handle,
6
+ * the audit log, the fire-mode signal, the tuning constants) is inverted here
7
+ * into a narrow, dependency-free contract the consumer injects. This module
8
+ * declares ONLY interfaces, type aliases, and the module-level default
9
+ * constants — no orchestration logic. It imports nothing from `@stoachain/*`
10
+ * and nothing from `better-sqlite3`; the carrier types
11
+ * (`IKadenaKeypair`, `UniversalKeypair`, `IUnsignedCommand`) are genericized
12
+ * and declared here so the emitted `.d.ts` carries zero external module
13
+ * references.
14
+ */
15
+ /** The documented no-op default for {@link OnAudit}. */
16
+ export const defaultOnAudit = () => { };
17
+ /** The documented default for {@link ResolveFireMode}: always `'live'`. */
18
+ export const defaultResolveFireMode = () => 'live';
19
+ /** Default tick cadence (30s) — {@link Config.tickIntervalMs}. */
20
+ export const TICK_INTERVAL_MS = 30000;
21
+ /** Default listen (confirmation) timeout: 5 minutes — {@link Config.listenTimeoutMs}. */
22
+ export const LISTEN_TIMEOUT_MS = 300000;
23
+ /** Default auto-gas simulation ceiling — {@link Config.autoGasCeiling}. */
24
+ export const AUTO_GAS_CEILING = 2000000;
25
+ /** Default single-transaction gas guard — {@link Config.singleTxGasGuard}. */
26
+ export const SINGLE_TX_GAS_GUARD = 1600000;
27
+ /** Default max cronotons processed per tick — {@link Config.tickBatchLimit}. */
28
+ export const TICK_BATCH_LIMIT = 100;
29
+ /** Default manual-batch minimum size — {@link Config.manualBatch}.min. */
30
+ export const MANUAL_BATCH_MIN = 2;
31
+ /** Default manual-batch maximum size — {@link Config.manualBatch}.max. */
32
+ export const MANUAL_BATCH_MAX = 60;
33
+ /** Default manual-batch inter-fire interval (seconds) — {@link Config.manualBatch}.intervalSeconds. */
34
+ export const MANUAL_BATCH_INTERVAL_SECONDS = 60;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * claim — due selection, the atomic claim-before-fire, and the terminal/advance
3
+ * writes for `codex_cronotons`.
4
+ *
5
+ * The CENTERPIECE is {@link claimDueCodexCronoton}: a single conditional UPDATE
6
+ * that advances (recurring) or clears (one-time) `next_fire_at` BEFORE the
7
+ * caller fires, so the row is no longer due/re-selectable the instant the claim
8
+ * commits. The WHERE clause re-asserts the due predicate so two racing claimers
9
+ * see exactly one win — this is where the exactly-once guarantee lives.
10
+ *
11
+ * Schedule math is imported, never reimplemented: {@link computeNextFire} is
12
+ * called at a FRESH `now` inside the recurring branch, wrapped so a corrupt
13
+ * `schedule_config_json` clears `next_fire_at` (stopping re-selection) rather
14
+ * than throwing uncaught.
15
+ */
16
+ import type { CodexCronotonRow, TerminalIntent } from "../types.js";
17
+ import type { DbDep } from "../seams.js";
18
+ /**
19
+ * Write the computed terminal intent: non-null → status + clear next_fire_at;
20
+ * null → no-op (recurring). The executor owns the COMPUTE; the store owns the
21
+ * WRITE.
22
+ */
23
+ export declare function applyTerminalIntent(id: string, terminalIntent: TerminalIntent | null, dep: DbDep): void;
24
+ /** Recurring counterpart of applyTerminalIntent — advance next_fire_at + last_fire_at. */
25
+ export declare function advanceRecurring(id: string, nextDate: Date, firedAt: Date, dep: DbDep): void;
26
+ /**
27
+ * Candidate due rows for the tick: active, with a non-null next_fire_at at or
28
+ * before `now`, oldest-first, capped at the batch limit. Each candidate must
29
+ * still be CLAIMED (claimDueCodexCronoton) before firing.
30
+ *
31
+ * EXCLUDES runtime-arg cronotons (`runtime_arg_keys IS NOT NULL`): their tx
32
+ * needs trigger-supplied string args, so the scheduler must never auto-fire
33
+ * them (a fire without the args would fail). They stay `active` so an external
34
+ * trigger endpoint can fire them WITH args; the scheduler simply skips them.
35
+ */
36
+ export declare function fetchDueCodexCronotons(now: Date, limit: number | undefined, dep: DbDep): CodexCronotonRow[];
37
+ /**
38
+ * The atomic claim that closes the double-fire window. A single conditional
39
+ * UPDATE advances (recurring) or clears (one-time) `next_fire_at` BEFORE the
40
+ * caller's inline fire, so the row is no longer due/re-selectable the instant
41
+ * the claim commits. The caller fires ONLY when this returns `true`
42
+ * (changes === 1); `false` means another overlapping tick or a manual
43
+ * Execute-Now already claimed the row — skip it (no fire).
44
+ *
45
+ * Branch selection:
46
+ * - RECURRING → SET next_fire_at = computeNextFire(mode, config, now) at the
47
+ * FRESH `now` (avoids stale-now drift). The recurring row stays active with
48
+ * its advanced next-fire.
49
+ * - ONE-TIME → SET next_fire_at = NULL (un-re-selectable); the caller applies
50
+ * the terminal intent after the fire.
51
+ * - RECURRING whose computeNextFire returns null or throws mid-life (corrupt
52
+ * schedule_config_json) → SET next_fire_at = NULL so it stops re-selecting.
53
+ * A corrupt-config row cannot both stay-active AND not-fire-storm.
54
+ *
55
+ * The WHERE clause re-asserts the due predicate (status='active' AND
56
+ * next_fire_at IS NOT NULL AND next_fire_at <= now) so two racing claimers see
57
+ * exactly one win.
58
+ */
59
+ export declare function claimDueCodexCronoton(row: CodexCronotonRow, now: Date, dep: DbDep): boolean;
@@ -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 {};