@ancientpantheon/khronoton-core 0.1.0 → 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 +19 -0
  2. package/README.md +77 -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 +16 -3
@@ -0,0 +1,200 @@
1
+ /**
2
+ * Generic server-resolver registry + the kind-routed fire dispatcher.
3
+ *
4
+ * A "server resolver" is a named hook consulted at fire time. Two kinds are
5
+ * distinguished by a `kind` discriminator so the tick can route each to the
6
+ * right execution path:
7
+ *
8
+ * - 'single-tx' — fills designated payload keys from live server data, merges
9
+ * them into ONE {@link CodexTxDefinition}, runs a safety-guard simulate,
10
+ * fires ONE transaction, then settles the server ledger. Dispatched through
11
+ * {@link fireWithServerResolver} (resolve → simulate-guard → fire → settle).
12
+ *
13
+ * - 'multi-tx' — an orchestrator that owns its own fire cardinality and guard
14
+ * (N independent fires). It does NOT ride the single-merge fire path; it is
15
+ * dispatched to its own `run` orchestrator via {@link dispatchMultiTxResolver}.
16
+ * The `run` implementation is supplied by the registering module.
17
+ *
18
+ * This module carries NO consumer-domain coupling: the concrete resolvers and
19
+ * their settlement-event sinks belong to the host, which registers them and may
20
+ * observe settlement outcomes through the optional `onEvent` hook on the fire
21
+ * opts. The only runtime dependency is the Phase-3 executor, bound at the
22
+ * dispatch boundary via an injectable `exec` seam (default: a ctx-bound closure).
23
+ */
24
+ import { executeCodexTransaction } from "./executor.js";
25
+ import { SINGLE_TX_GAS_GUARD } from "./seams.js";
26
+ /** Registry of server resolvers keyed by `serverResolver` name. */
27
+ const SERVER_RESOLVERS = {};
28
+ /**
29
+ * Register (or replace) a named server resolver. A module that owns a resolver
30
+ * calls this at module-eval time so the registry is populated by the time the
31
+ * tick consults it.
32
+ */
33
+ export function registerServerResolver(name, resolver) {
34
+ SERVER_RESOLVERS[name] = resolver;
35
+ }
36
+ /** Read a registered resolver entry (with its `kind`) by name, or `undefined`. */
37
+ export function getServerResolver(name) {
38
+ return SERVER_RESOLVERS[name];
39
+ }
40
+ /**
41
+ * Resolve a named SINGLE-TX resolver's plan + payload WITHOUT firing — used by a
42
+ * simulate/preview endpoint to show what a fire would produce. Returns `null`
43
+ * for an unknown name OR for a multi-tx resolver (which has no single-tx payload
44
+ * to preview).
45
+ */
46
+ export function resolveServerVars(name, dep) {
47
+ const r = SERVER_RESOLVERS[name];
48
+ return r && r.kind === "single-tx" ? r.resolve(dep) : null;
49
+ }
50
+ /**
51
+ * Dispatch a registered MULTI-TX resolver's orchestrator. The tick routes a
52
+ * multi-tx `serverResolver` here instead of through {@link fireWithServerResolver}.
53
+ * Throws for an unknown name, or for a name registered as single-tx (routing it
54
+ * here would force its merge through the wrong path).
55
+ */
56
+ export async function dispatchMultiTxResolver(name, opts) {
57
+ const r = SERVER_RESOLVERS[name];
58
+ if (!r)
59
+ throw new Error(`unknown server resolver: ${name}`);
60
+ if (r.kind !== "multi-tx") {
61
+ throw new Error(`server resolver "${name}" is not a multi-tx resolver (kind=${r.kind})`);
62
+ }
63
+ return r.run(opts);
64
+ }
65
+ function postponed(error) {
66
+ return { ok: false, mode: "fire", error, terminalIntent: null };
67
+ }
68
+ /**
69
+ * Adapt a multi-tx orchestrator's run summary to a {@link FireResult} so the tick
70
+ * records one observable fire row for the run. A returned summary always means
71
+ * the run COMPLETED (`ok:true`); the summary is stashed in `rawResult` and the
72
+ * first batch's request key (when present) is surfaced so the fire row links to
73
+ * the on-chain batch.
74
+ */
75
+ function adaptMultiTxSummary(summary) {
76
+ const s = (summary ?? {});
77
+ const firstBatchKey = Array.isArray(s.batches) && s.batches.length > 0 ? s.batches[0]?.requestKey : undefined;
78
+ return {
79
+ ok: true,
80
+ mode: "fire",
81
+ requestKey: firstBatchKey,
82
+ rawResult: summary,
83
+ terminalIntent: null,
84
+ };
85
+ }
86
+ /**
87
+ * Build the executor seam: the injected `exec` override if present, else a
88
+ * ctx-bound closure that threads `runtime`+`resolver`+`config` into the Phase-3
89
+ * executor so its Config reads (`listenTimeoutMs`/`autoGasCeiling`) see the
90
+ * injected tuning.
91
+ */
92
+ function resolveExec(opts) {
93
+ if (opts.exec)
94
+ return opts.exec;
95
+ const ctx = {
96
+ runtime: opts.runtime,
97
+ resolver: opts.resolver,
98
+ config: opts.config,
99
+ };
100
+ const bound = (definition, mode) => mode === "simulate"
101
+ ? executeCodexTransaction(definition, "simulate", ctx)
102
+ : executeCodexTransaction(definition, "fire", ctx);
103
+ return bound;
104
+ }
105
+ /**
106
+ * The single fire-time dispatcher the tick calls for EVERY row. Routes by kind:
107
+ * - no `serverResolver` → executor `fire` (pass-through);
108
+ * - registered `multi-tx` → {@link dispatchMultiTxResolver} + summary adapt;
109
+ * - otherwise → {@link fireWithServerResolver} (the single-tx merge path).
110
+ *
111
+ * NEVER throws out: a multi-tx orchestrator throw becomes a `postponed`
112
+ * FireResult so the tick records a single failure fire row rather than aborting.
113
+ */
114
+ export async function fireByServerResolver(definition, row, opts = {}) {
115
+ if (!definition.serverResolver) {
116
+ const exec = resolveExec(opts);
117
+ return exec(definition, "fire");
118
+ }
119
+ const registered = SERVER_RESOLVERS[definition.serverResolver];
120
+ if (registered && registered.kind === "multi-tx") {
121
+ try {
122
+ const dispatchOpts = opts.deps ?? (opts.db ? { db: opts.db } : {});
123
+ const summary = await dispatchMultiTxResolver(definition.serverResolver, dispatchOpts);
124
+ return adaptMultiTxSummary(summary);
125
+ }
126
+ catch (err) {
127
+ const message = err instanceof Error ? err.message : String(err);
128
+ return postponed(`multi-tx dispatch error: ${message}`);
129
+ }
130
+ }
131
+ // No registered entry, or a single-tx entry → the single-tx fire path (which
132
+ // itself postpones an unknown name and handles the pass-through case).
133
+ return fireWithServerResolver(definition, row, opts);
134
+ }
135
+ /**
136
+ * Single-tx fire-time wrapper. For an ordinary row (no `serverResolver`) this is
137
+ * a pure pass-through to `exec(def,'fire')`. For a single-tx server-resolved row
138
+ * it resolves the payload → runs a SAFETY-GUARD simulate (postpone on failure or
139
+ * over-budget gas) → fires → settles on success. A settlement failure AFTER a
140
+ * successful fire NEVER marks the fire failed (the tx already landed; settlement
141
+ * is idempotent) — it is surfaced via the optional `onEvent` hook.
142
+ *
143
+ * A multi-tx resolver name is REFUSED here (postponed): it must be dispatched via
144
+ * {@link dispatchMultiTxResolver}, never merged+fired through this single path.
145
+ */
146
+ export async function fireWithServerResolver(definition, _row, opts = {}) {
147
+ const exec = resolveExec(opts);
148
+ if (!definition.serverResolver) {
149
+ return exec(definition, "fire");
150
+ }
151
+ const registered = SERVER_RESOLVERS[definition.serverResolver];
152
+ if (registered && registered.kind !== "single-tx") {
153
+ return postponed(`server resolver "${definition.serverResolver}" is multi-tx — dispatch via the orchestrator, not the single-tx fire path`);
154
+ }
155
+ const resolve = opts.resolve ?? registered?.resolve;
156
+ const settle = opts.settle ?? registered?.settle;
157
+ if (!resolve || !settle) {
158
+ return postponed(`unknown server resolver: ${definition.serverResolver}`);
159
+ }
160
+ const { plan, payload } = resolve(opts.db ? { db: opts.db } : undefined);
161
+ // An empty plan is NOT a postpone: a resolver may legitimately fire an empty
162
+ // definition (an on-chain "nothing to do" record) and settle to a no-op. Only
163
+ // genuine can't-fire cases below (simulate failure, gas over guard) postpone.
164
+ const fired = {
165
+ ...definition,
166
+ payload: { ...definition.payload, ...payload },
167
+ };
168
+ // SAFETY GUARD: a single simulate confirms the tx lands at today's volume. If
169
+ // it can't (sim failed, or gas over the single-tx ceiling), postpone rather
170
+ // than burn gas on a tx that cannot succeed.
171
+ const sim = await exec(fired, "simulate");
172
+ if (!sim.ok) {
173
+ opts.onEvent?.({ kind: "postponed", reason: "simulate failed", error: sim.error });
174
+ return postponed(`postponed: simulate failed: ${sim.error ?? "unknown"}`);
175
+ }
176
+ const guard = opts.config?.singleTxGasGuard ?? SINGLE_TX_GAS_GUARD;
177
+ const gasUsed = sim.gasUsed ?? 0;
178
+ if (gasUsed > guard) {
179
+ opts.onEvent?.({ kind: "postponed", reason: "gas over single-tx guard", gasUsed, guard });
180
+ return postponed(`postponed: gas ${gasUsed} exceeds single-tx guard ${guard} (multi-tx split deferred)`);
181
+ }
182
+ const result = await exec(fired, "fire");
183
+ if (result.ok) {
184
+ try {
185
+ settle(plan, { db: opts.db, requestKey: result.requestKey });
186
+ opts.onEvent?.({ kind: "settled", count: plan.length, requestKey: result.requestKey });
187
+ }
188
+ catch (err) {
189
+ // The tx LANDED on-chain — a settlement write failure must NOT mark the
190
+ // fire failed. Surface it for follow-up; settlement is idempotent.
191
+ const message = err instanceof Error ? err.message : String(err);
192
+ opts.onEvent?.({
193
+ kind: "settlement-needs-attention",
194
+ error: message,
195
+ requestKey: result.requestKey,
196
+ });
197
+ }
198
+ }
199
+ return result;
200
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The consolidated DDL installer for the three codex-cronoton tables.
3
+ *
4
+ * This folds the Hub's incremental migration chain (base tables + a dozen later
5
+ * ALTERs) into the FINAL column shapes, emitted in a single idempotent call.
6
+ * Every statement uses `IF NOT EXISTS`, so re-running the installer on an
7
+ * already-provisioned database is a no-op.
8
+ *
9
+ * Genericization deltas from the Hub schema (this package carries no host FKs
10
+ * and owns no status domain):
11
+ * - `codex_cronoton_fires.job_id` is a plain nullable `TEXT` column — the Hub's
12
+ * `REFERENCES jobs(id)` FK is dropped, since a generic host has no `jobs`
13
+ * table.
14
+ * - `codex_cronoton_fires.status` has NO CHECK constraint — the application is
15
+ * the single writer and owns the value domain (success/failure/running/
16
+ * nothing/…), so widening a CHECK per new outcome is avoided.
17
+ *
18
+ * The installer is driver-free: it only calls `db.exec(...)` on the injected
19
+ * {@link Database} handle, so it never imports `better-sqlite3` at runtime and
20
+ * works against any backend that structurally satisfies the seam.
21
+ */
22
+ import type { Database } from "./seams.js";
23
+ /**
24
+ * Installs the three codex-cronoton tables and their indexes on the injected DB
25
+ * handle in a single idempotent call. Safe to re-run: every statement is guarded
26
+ * with `IF NOT EXISTS`.
27
+ *
28
+ * @param db - Any handle satisfying the {@link Database} seam (a real
29
+ * `better-sqlite3` instance qualifies). Only `db.exec` is used.
30
+ */
31
+ export declare function installSchema(db: Database): void;
@@ -0,0 +1,93 @@
1
+ const SCHEMA_SQL = `
2
+ CREATE TABLE IF NOT EXISTS codex_cronotons (
3
+ id TEXT PRIMARY KEY,
4
+ name TEXT NOT NULL,
5
+ description TEXT,
6
+ pact_code TEXT NOT NULL,
7
+ config_json TEXT NOT NULL,
8
+ payload_json TEXT,
9
+ gas_payer_json TEXT NOT NULL,
10
+ signers_json TEXT NOT NULL,
11
+ schedule_mode TEXT NOT NULL CHECK (schedule_mode IN (
12
+ 'daily-at-utc',
13
+ 'every-n-minutes',
14
+ 'weekly',
15
+ 'monthly',
16
+ 'cron-expression',
17
+ 'one-time',
18
+ 'several-times-per-day'
19
+ )),
20
+ schedule_config_json TEXT NOT NULL,
21
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN (
22
+ 'active',
23
+ 'paused',
24
+ 'completed',
25
+ 'error'
26
+ )),
27
+ next_fire_at TEXT,
28
+ last_fire_at TEXT,
29
+ created_at TEXT NOT NULL,
30
+ modified_at TEXT NOT NULL,
31
+ created_by TEXT NOT NULL,
32
+ server_resolver TEXT,
33
+ fire_mode_override TEXT,
34
+ external_fireable INTEGER NOT NULL DEFAULT 0,
35
+ runtime_arg_keys TEXT
36
+ );
37
+
38
+ CREATE INDEX IF NOT EXISTS idx_codex_cronotons_next_fire
39
+ ON codex_cronotons(status, next_fire_at);
40
+
41
+ CREATE TABLE IF NOT EXISTS codex_cronoton_fires (
42
+ id TEXT PRIMARY KEY,
43
+ codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
44
+ job_id TEXT,
45
+ fired_at TEXT NOT NULL,
46
+ status TEXT NOT NULL,
47
+ request_key TEXT,
48
+ chain_id TEXT,
49
+ error_message TEXT,
50
+ chain_response_json TEXT,
51
+ definition_fingerprint TEXT,
52
+ mode TEXT NOT NULL DEFAULT 'test',
53
+ recovered_at TEXT,
54
+ tx_keys_json TEXT
55
+ );
56
+
57
+ CREATE INDEX IF NOT EXISTS idx_codex_fires_cronoton
58
+ ON codex_cronoton_fires(codex_cronoton_id, fired_at DESC);
59
+
60
+ CREATE TABLE IF NOT EXISTS codex_cronoton_manual_batches (
61
+ id TEXT PRIMARY KEY,
62
+ codex_cronoton_id TEXT NOT NULL REFERENCES codex_cronotons(id) ON DELETE CASCADE,
63
+ total INTEGER NOT NULL,
64
+ completed INTEGER NOT NULL DEFAULT 0,
65
+ interval_seconds INTEGER NOT NULL DEFAULT 60,
66
+ status TEXT NOT NULL DEFAULT 'active' CHECK (status IN (
67
+ 'active',
68
+ 'completed',
69
+ 'cancelled'
70
+ )),
71
+ next_at TEXT,
72
+ created_at TEXT NOT NULL,
73
+ modified_at TEXT NOT NULL,
74
+ created_by TEXT NOT NULL
75
+ );
76
+
77
+ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_due
78
+ ON codex_cronoton_manual_batches(status, next_at);
79
+
80
+ CREATE INDEX IF NOT EXISTS idx_codex_manual_batches_cronoton
81
+ ON codex_cronoton_manual_batches(codex_cronoton_id);
82
+ `;
83
+ /**
84
+ * Installs the three codex-cronoton tables and their indexes on the injected DB
85
+ * handle in a single idempotent call. Safe to re-run: every statement is guarded
86
+ * with `IF NOT EXISTS`.
87
+ *
88
+ * @param db - Any handle satisfying the {@link Database} seam (a real
89
+ * `better-sqlite3` instance qualifies). Only `db.exec` is used.
90
+ */
91
+ export function installSchema(db) {
92
+ db.exec(SCHEMA_SQL);
93
+ }
@@ -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;