@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,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;
@@ -0,0 +1,170 @@
1
+ /**
2
+ * Fire history writes/reads for a codex cronoton.
3
+ *
4
+ * Each fire row records ONE dispatch of a cronoton's transaction(s): a
5
+ * single-tx `recordFire`, or a `running` row (`createRunningFire`) that a
6
+ * background worker later grows with per-tx keys (`appendFireTxKeys`) and flips
7
+ * terminal (`finalizeFire`). `listFires` paginates the history newest-first and
8
+ * `recoverFire` reconciles a stale `failure` to its true on-chain `success`.
9
+ *
10
+ * Fire-mode seam (map §8 divergence #1): each fire is badged `test`/`live` at
11
+ * write time. The parent's `fire_mode_override = 'live'` column is the FIRST
12
+ * gate (an operator declaring its transactions real); anything else defers to
13
+ * the injected {@link ResolveFireMode}. The Hub's global
14
+ * `system_state.scoring_live_locked` read is GONE — that signal now lives behind
15
+ * the seam. `ResolveFireMode` is synchronous BY TYPE (better-sqlite3 is a sync
16
+ * driver, so its result binds directly into the INSERT); a consumer needing
17
+ * async fire-mode resolution pre-resolves before invoking the tick.
18
+ */
19
+ import { randomUUID } from "node:crypto";
20
+ import { defaultResolveFireMode, } from "../seams.js";
21
+ /**
22
+ * Resolve a fire's mode badge. The parent's `fire_mode_override = 'live'` wins
23
+ * FIRST (the single write site enforcing the `test | live` domain); any other
24
+ * override value defers to the injected, synchronous {@link ResolveFireMode}.
25
+ */
26
+ function readFireMode(db, codexCronotonId, resolveFireMode) {
27
+ const parent = db
28
+ .prepare(`SELECT fire_mode_override FROM codex_cronotons WHERE id = ?`)
29
+ .get(codexCronotonId);
30
+ if (parent?.fire_mode_override === "live")
31
+ return "live";
32
+ return resolveFireMode(codexCronotonId);
33
+ }
34
+ /** Insert exactly ONE fire row + bump the parent's last_fire_at. */
35
+ export function recordFire(input, dep) {
36
+ const db = dep.db;
37
+ const fireId = randomUUID();
38
+ const mode = readFireMode(db, input.codexCronotonId, dep.resolveFireMode ?? defaultResolveFireMode);
39
+ db.prepare(`INSERT INTO codex_cronoton_fires
40
+ (id, codex_cronoton_id, job_id, fired_at, status, request_key, chain_id,
41
+ error_message, chain_response_json, definition_fingerprint, mode, tx_keys_json)
42
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(fireId, input.codexCronotonId, input.jobId, input.firedAt, input.status, input.requestKey ?? null, input.chainId ?? null, input.errorMessage ?? null, input.chainResponse !== undefined ? JSON.stringify(input.chainResponse) : null, input.definitionFingerprint, mode, input.txKeys && input.txKeys.length ? JSON.stringify(input.txKeys) : null);
43
+ db.prepare(`UPDATE codex_cronotons SET last_fire_at = ? WHERE id = ?`).run(input.firedAt, input.codexCronotonId);
44
+ return fireId;
45
+ }
46
+ /**
47
+ * Open a fire row in the non-terminal `running` state the MOMENT a multi-tx
48
+ * (background-job) fire is dispatched, so the operator sees the entry at once.
49
+ * The worker later appends per-tx keys via {@link appendFireTxKeys} and flips it
50
+ * terminal via {@link finalizeFire}. Mirrors `recordFire`'s last_fire_at bump.
51
+ */
52
+ export function createRunningFire(input, dep) {
53
+ const db = dep.db;
54
+ const fireId = randomUUID();
55
+ const mode = readFireMode(db, input.codexCronotonId, dep.resolveFireMode ?? defaultResolveFireMode);
56
+ db.prepare(`INSERT INTO codex_cronoton_fires
57
+ (id, codex_cronoton_id, job_id, fired_at, status, definition_fingerprint, mode, tx_keys_json)
58
+ VALUES (?, ?, ?, ?, 'running', ?, ?, '[]')`).run(fireId, input.codexCronotonId, input.jobId, input.firedAt, input.definitionFingerprint, mode);
59
+ db.prepare(`UPDATE codex_cronotons SET last_fire_at = ? WHERE id = ?`).run(input.firedAt, input.codexCronotonId);
60
+ return fireId;
61
+ }
62
+ /** Link a fire row to the background job that executes it (best-effort). */
63
+ export function setFireJobId(fireId, jobId, dep) {
64
+ dep.db
65
+ .prepare(`UPDATE codex_cronoton_fires SET job_id = ? WHERE id = ?`)
66
+ .run(jobId, fireId);
67
+ }
68
+ /**
69
+ * Append one or more per-tx keys to a fire's `tx_keys_json` (read-modify-write,
70
+ * de-duplicated by requestKey so a resumed/retried leg never double-lists). Safe
71
+ * to call repeatedly during a multi-minute run; the fire history reads the
72
+ * growing array on each refresh. A missing fire is a no-op (never throws).
73
+ */
74
+ export function appendFireTxKeys(fireId, txKeys, dep) {
75
+ if (!txKeys.length)
76
+ return;
77
+ const db = dep.db;
78
+ const row = db
79
+ .prepare(`SELECT tx_keys_json FROM codex_cronoton_fires WHERE id = ?`)
80
+ .get(fireId);
81
+ if (!row)
82
+ return;
83
+ let existing = [];
84
+ try {
85
+ existing = row.tx_keys_json ? JSON.parse(row.tx_keys_json) : [];
86
+ }
87
+ catch {
88
+ existing = [];
89
+ }
90
+ const byKey = new Map(existing.map((t) => [t.requestKey, t]));
91
+ for (const t of txKeys)
92
+ byKey.set(t.requestKey, t); // upsert: latest ok/state wins
93
+ db.prepare(`UPDATE codex_cronoton_fires SET tx_keys_json = ? WHERE id = ?`).run(JSON.stringify([...byKey.values()]), fireId);
94
+ }
95
+ /**
96
+ * Flip a `running` fire to its terminal outcome. Sets status + the headline
97
+ * request key + error + structured chain response, and merges any final tx keys.
98
+ */
99
+ export function finalizeFire(fireId, result, dep) {
100
+ const db = dep.db;
101
+ if (result.txKeys && result.txKeys.length)
102
+ appendFireTxKeys(fireId, result.txKeys, dep);
103
+ db.prepare(`UPDATE codex_cronoton_fires
104
+ SET status = ?, request_key = ?, chain_id = ?, error_message = ?,
105
+ chain_response_json = ?
106
+ WHERE id = ?`).run(result.status, result.requestKey ?? null, result.chainId ?? null, result.errorMessage ?? null, result.chainResponse !== undefined ? JSON.stringify(result.chainResponse) : null, fireId);
107
+ }
108
+ /** Parse the stored tx_keys_json into a typed array; tolerate null/garbage. */
109
+ function parseTxKeys(json) {
110
+ if (!json)
111
+ return [];
112
+ try {
113
+ const parsed = JSON.parse(json);
114
+ return Array.isArray(parsed) ? parsed : [];
115
+ }
116
+ catch {
117
+ return [];
118
+ }
119
+ }
120
+ /** Paginated fire history for a cronoton, newest-first (limit clamped 1..100, default 20). */
121
+ export function listFires(id, params = {}, dep) {
122
+ const db = dep.db;
123
+ const limit = Math.min(Math.max(params.limit ?? 20, 1), 100);
124
+ const offset = Math.max(params.offset ?? 0, 0);
125
+ const rows = db
126
+ .prepare(`SELECT id, fired_at, status, request_key, chain_id, error_message,
127
+ chain_response_json, definition_fingerprint, mode, recovered_at, tx_keys_json
128
+ FROM codex_cronoton_fires
129
+ WHERE codex_cronoton_id = ?
130
+ ORDER BY fired_at DESC LIMIT ? OFFSET ?`)
131
+ .all(id, limit, offset);
132
+ const totalRow = db
133
+ .prepare("SELECT COUNT(*) AS c FROM codex_cronoton_fires WHERE codex_cronoton_id = ?")
134
+ .get(id);
135
+ return {
136
+ fires: rows.map((r) => ({
137
+ id: r.id,
138
+ firedAt: r.fired_at,
139
+ status: r.status,
140
+ requestKey: r.request_key,
141
+ chainId: r.chain_id,
142
+ errorMessage: r.error_message,
143
+ chainResponse: r.chain_response_json ? JSON.parse(r.chain_response_json) : null,
144
+ definitionFingerprint: r.definition_fingerprint,
145
+ mode: r.mode === "live" ? "live" : "test",
146
+ recoveredAt: r.recovered_at,
147
+ txKeys: parseTxKeys(r.tx_keys_json),
148
+ })),
149
+ total: totalRow?.c ?? 0,
150
+ };
151
+ }
152
+ /**
153
+ * Manual recovery: reconcile a FAILED fire to its true on-chain outcome by
154
+ * attaching the confirmed request key. Flips status failure→success, stamps
155
+ * `recovered_at`, and clears the stale transport error (e.g. an nginx 504 that
156
+ * hid a successful submit). Returns true if a failed row was updated, false if
157
+ * the fire wasn't found OR wasn't in `failure` (idempotent — a second call is a
158
+ * no-op).
159
+ */
160
+ export function recoverFire(fireId, requestKey, dep) {
161
+ const res = dep.db
162
+ .prepare(`UPDATE codex_cronoton_fires
163
+ SET status = 'success',
164
+ request_key = ?,
165
+ recovered_at = ?,
166
+ error_message = NULL
167
+ WHERE id = ? AND status = 'failure'`)
168
+ .run(requestKey, new Date().toISOString(), fireId);
169
+ return res.changes > 0;
170
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The store public surface for `@ancientpantheon/khronoton-core/server`.
3
+ *
4
+ * Re-exports every store function/error/type the consumer drives, via relative
5
+ * `.js`-suffixed paths (values with `export {…}`, types/interfaces with
6
+ * `export type {…}`), so the emitted `.d.ts` stays fully erasable.
7
+ *
8
+ * Deliberately NOT re-exported from `./errors.js`: the tuning constants
9
+ * `TICK_BATCH_LIMIT`, `MANUAL_BATCH_MIN`, `MANUAL_BATCH_MAX`,
10
+ * `MANUAL_BATCH_INTERVAL_SECONDS`. Those names are already the public export at
11
+ * `../seams.js` (the injectable `Config` defaults) and are surfaced by the
12
+ * Phase-1 server barrel. The `./errors.js` copies exist only as the module-local
13
+ * fallback backing `config?.<field> ?? <CONSTANT>`; re-exporting them here would
14
+ * collide with the seams.ts source at the server barrel. seams.ts is the single
15
+ * public source for those constants.
16
+ */
17
+ export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, } from "./errors.js";
18
+ export { rowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, manualBatchView, } from "./mappers.js";
19
+ export { fetchDueCodexCronotons, claimDueCodexCronoton, applyTerminalIntent, advanceRecurring, } from "./claim.js";
20
+ export { recordFire, createRunningFire, setFireJobId, appendFireTxKeys, finalizeFire, listFires, recoverFire, } from "./fires.js";
21
+ export type { RecordFireInput, FireDep } from "./fires.js";
22
+ export { commitCodexCronoton, getCodexCronoton, findCodexCronotonIdByServerResolver, listCodexCronotons, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
23
+ export type { CommitCodexCronotonInput, EditCodexCronotonPatch } from "./cronoton.js";
24
+ export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from "./manual-batch.js";
25
+ export type { CreateManualBatchInput } from "./manual-batch.js";
26
+ export { computeDefinitionFingerprint } from "../pure/fingerprint.js";
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The store public surface for `@ancientpantheon/khronoton-core/server`.
3
+ *
4
+ * Re-exports every store function/error/type the consumer drives, via relative
5
+ * `.js`-suffixed paths (values with `export {…}`, types/interfaces with
6
+ * `export type {…}`), so the emitted `.d.ts` stays fully erasable.
7
+ *
8
+ * Deliberately NOT re-exported from `./errors.js`: the tuning constants
9
+ * `TICK_BATCH_LIMIT`, `MANUAL_BATCH_MIN`, `MANUAL_BATCH_MAX`,
10
+ * `MANUAL_BATCH_INTERVAL_SECONDS`. Those names are already the public export at
11
+ * `../seams.js` (the injectable `Config` defaults) and are surfaced by the
12
+ * Phase-1 server barrel. The `./errors.js` copies exist only as the module-local
13
+ * fallback backing `config?.<field> ?? <CONSTANT>`; re-exporting them here would
14
+ * collide with the seams.ts source at the server barrel. seams.ts is the single
15
+ * public source for those constants.
16
+ */
17
+ // ── Typed errors (classes — values, not types) ───────────────────────────────
18
+ export { CodexCronotonValidationError, AutoGasGateError, TerminalCronotonError, ManualBatchActiveError, } from "./errors.js";
19
+ // ── Pure mappers / gates ─────────────────────────────────────────────────────
20
+ export { rowToDefinition, rowExternalFireable, rowRuntimeArgKeys, assertAutoGasGate, manualBatchView, } from "./mappers.js";
21
+ // ── Atomic claim + due selection + terminal/advance writes ───────────────────
22
+ export { fetchDueCodexCronotons, claimDueCodexCronoton, applyTerminalIntent, advanceRecurring, } from "./claim.js";
23
+ // ── Fires: record / running / append / finalize / list / recover ─────────────
24
+ export { recordFire, createRunningFire, setFireJobId, appendFireTxKeys, finalizeFire, listFires, recoverFire, } from "./fires.js";
25
+ // ── Cronoton lifecycle: commit / read / find / list / edit / pause / resume / delete ─
26
+ export { commitCodexCronoton, getCodexCronoton, findCodexCronotonIdByServerResolver, listCodexCronotons, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
27
+ // ── Manual-batch lifecycle: create / due-fetch / claim / cancel ──────────────
28
+ export { getManualBatch, getActiveManualBatchForCronoton, createManualBatch, fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from "./manual-batch.js";
29
+ // ── Fingerprint (Phase-1 pure helper, re-surfaced for Hub `store.ts` parity) ──
30
+ // The Hub exported `computeDefinitionFingerprint` FROM its store module; the
31
+ // store barrel is the single export site here (the Phase-1 server barrel drops
32
+ // its own direct fingerprint export in favor of this one to avoid a duplicate).
33
+ export { computeDefinitionFingerprint } from "../pure/fingerprint.js";