@ancientpantheon/khronoton-core 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +75 -3
  3. package/dist/server/executor-signers.d.ts +29 -0
  4. package/dist/server/executor-signers.js +60 -0
  5. package/dist/server/executor.d.ts +53 -0
  6. package/dist/server/executor.js +280 -0
  7. package/dist/server/index.d.ts +27 -0
  8. package/dist/server/index.js +51 -0
  9. package/dist/server/loop.d.ts +36 -0
  10. package/dist/server/loop.js +51 -0
  11. package/dist/server/pure/capability.d.ts +31 -0
  12. package/dist/server/pure/capability.js +63 -0
  13. package/dist/server/pure/fingerprint.d.ts +8 -0
  14. package/dist/server/pure/fingerprint.js +44 -0
  15. package/dist/server/pure/runtime-args.d.ts +34 -0
  16. package/dist/server/pure/runtime-args.js +99 -0
  17. package/dist/server/resolvers.d.ts +140 -0
  18. package/dist/server/resolvers.js +200 -0
  19. package/dist/server/schema.d.ts +31 -0
  20. package/dist/server/schema.js +93 -0
  21. package/dist/server/seams.d.ts +231 -0
  22. package/dist/server/seams.js +34 -0
  23. package/dist/server/store/claim.d.ts +59 -0
  24. package/dist/server/store/claim.js +97 -0
  25. package/dist/server/store/cronoton.d.ts +79 -0
  26. package/dist/server/store/cronoton.js +268 -0
  27. package/dist/server/store/errors.d.ts +26 -0
  28. package/dist/server/store/errors.js +40 -0
  29. package/dist/server/store/fires.d.ts +77 -0
  30. package/dist/server/store/fires.js +170 -0
  31. package/dist/server/store/index.d.ts +26 -0
  32. package/dist/server/store/index.js +33 -0
  33. package/dist/server/store/manual-batch.d.ts +38 -0
  34. package/dist/server/store/manual-batch.js +110 -0
  35. package/dist/server/store/mappers.d.ts +21 -0
  36. package/dist/server/store/mappers.js +62 -0
  37. package/dist/server/tick.d.ts +83 -0
  38. package/dist/server/tick.js +235 -0
  39. package/dist/server/types.d.ts +220 -0
  40. package/dist/server/types.js +14 -0
  41. package/package.json +14 -2
@@ -0,0 +1,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";
@@ -0,0 +1,38 @@
1
+ import type { Config, DbDep } from "../seams.js";
2
+ import type { CodexManualBatchRow } from "../types.js";
3
+ export declare function getManualBatch(id: string, dep: DbDep): CodexManualBatchRow | null;
4
+ /** The one active batch for a cronoton (at most one is allowed at a time). */
5
+ export declare function getActiveManualBatchForCronoton(cronotonId: string, dep: DbDep): CodexManualBatchRow | null;
6
+ export interface CreateManualBatchInput {
7
+ cronotonId: string;
8
+ total: number;
9
+ createdBy: string;
10
+ }
11
+ interface CreateManualBatchOpts extends DbDep {
12
+ now?: Date;
13
+ /** Overrides the default count bounds and inter-fire cadence. */
14
+ config?: Partial<Config>;
15
+ }
16
+ /**
17
+ * Create a manual execution batch. Validates the count bounds, that the parent
18
+ * cronoton exists + is active + is NOT one-time (a single fire spends a one-time
19
+ * entry, so batching it is meaningless), and that no batch is already running
20
+ * for it. `next_at = now` so the first fire is picked up on the next worker tick.
21
+ */
22
+ export declare function createManualBatch(input: CreateManualBatchInput, opts: CreateManualBatchOpts): CodexManualBatchRow;
23
+ /** Active batches with a due slot (`next_at <= now`), oldest-first. */
24
+ export declare function fetchDueManualBatches(now: Date, limit: number, dep: DbDep): CodexManualBatchRow[];
25
+ /**
26
+ * Atomically claim one fire slot of a batch BEFORE the inline fire (mirrors
27
+ * claimDueCodexCronoton): a single conditional UPDATE increments `completed`,
28
+ * advances `next_at` (+interval, or NULL on the final slot) and flips status to
29
+ * 'completed' on the last slot. The WHERE clause re-asserts the due predicate so
30
+ * two racing claimers see exactly one win. Returns true when this caller won the
31
+ * slot (changes === 1) and should fire.
32
+ */
33
+ export declare function claimManualBatchFire(batch: CodexManualBatchRow, now: Date, dep: DbDep): boolean;
34
+ /** Operator (or auto) cancel of an active batch. Idempotent: ok=false if not active. */
35
+ export declare function cancelManualBatch(id: string, dep: DbDep): {
36
+ ok: boolean;
37
+ };
38
+ export {};
@@ -0,0 +1,110 @@
1
+ /**
2
+ * manual-batch — the create / due-fetch / claim / cancel lifecycle for
3
+ * `codex_cronoton_manual_batches` ("Execute Now ×N").
4
+ *
5
+ * The centerpiece is {@link claimManualBatchFire}: a single conditional UPDATE
6
+ * that increments `completed`, advances `next_at` (+interval, or NULL on the
7
+ * final slot) and flips `status` to 'completed' on the last slot IN THE SAME
8
+ * statement. The WHERE clause re-asserts the due predicate so two racing
9
+ * claimers see exactly one win — the once-only guarantee mirrored from
10
+ * {@link claimDueCodexCronoton}.
11
+ *
12
+ * Count bounds and inter-fire cadence read from an OPTIONAL injected config
13
+ * ({@link Config.manualBatch}); the exported constants back them as DEFAULTS.
14
+ */
15
+ import crypto from "node:crypto";
16
+ import { getCodexCronoton } from "./cronoton.js";
17
+ import { CodexCronotonValidationError, ManualBatchActiveError, MANUAL_BATCH_INTERVAL_SECONDS, MANUAL_BATCH_MAX, MANUAL_BATCH_MIN, } from "./errors.js";
18
+ export function getManualBatch(id, dep) {
19
+ const row = dep.db
20
+ .prepare("SELECT * FROM codex_cronoton_manual_batches WHERE id = ?")
21
+ .get(id);
22
+ return row ?? null;
23
+ }
24
+ /** The one active batch for a cronoton (at most one is allowed at a time). */
25
+ export function getActiveManualBatchForCronoton(cronotonId, dep) {
26
+ const row = dep.db
27
+ .prepare(`SELECT * FROM codex_cronoton_manual_batches
28
+ WHERE codex_cronoton_id = ? AND status = 'active'
29
+ ORDER BY created_at DESC LIMIT 1`)
30
+ .get(cronotonId);
31
+ return row ?? null;
32
+ }
33
+ /**
34
+ * Create a manual execution batch. Validates the count bounds, that the parent
35
+ * cronoton exists + is active + is NOT one-time (a single fire spends a one-time
36
+ * entry, so batching it is meaningless), and that no batch is already running
37
+ * for it. `next_at = now` so the first fire is picked up on the next worker tick.
38
+ */
39
+ export function createManualBatch(input, opts) {
40
+ const db = opts.db;
41
+ const { min, max, intervalSeconds } = opts.config?.manualBatch ?? {
42
+ min: MANUAL_BATCH_MIN,
43
+ max: MANUAL_BATCH_MAX,
44
+ intervalSeconds: MANUAL_BATCH_INTERVAL_SECONDS,
45
+ };
46
+ const total = Math.trunc(input.total);
47
+ if (!Number.isFinite(input.total) || total < min || total > max) {
48
+ throw new CodexCronotonValidationError(`count must be an integer between ${min} and ${max}`);
49
+ }
50
+ const cronoton = getCodexCronoton(input.cronotonId, { db });
51
+ if (!cronoton)
52
+ throw new CodexCronotonValidationError("not found");
53
+ if (cronoton.status !== "active") {
54
+ throw new CodexCronotonValidationError(`cannot batch-execute a codex cronoton with status '${cronoton.status}'`);
55
+ }
56
+ if (cronoton.schedule_mode === "one-time") {
57
+ throw new CodexCronotonValidationError("one-time codex cronotons cannot be batch-executed (a single fire spends them)");
58
+ }
59
+ if (getActiveManualBatchForCronoton(input.cronotonId, { db })) {
60
+ throw new ManualBatchActiveError();
61
+ }
62
+ const now = opts.now ?? new Date();
63
+ const nowIso = now.toISOString();
64
+ const id = crypto.randomUUID();
65
+ db.prepare(`INSERT INTO codex_cronoton_manual_batches
66
+ (id, codex_cronoton_id, total, completed, interval_seconds, status,
67
+ next_at, created_at, modified_at, created_by)
68
+ VALUES (?, ?, ?, 0, ?, 'active', ?, ?, ?, ?)`).run(id, input.cronotonId, total, intervalSeconds, nowIso, nowIso, nowIso, input.createdBy);
69
+ return getManualBatch(id, { db });
70
+ }
71
+ /** Active batches with a due slot (`next_at <= now`), oldest-first. */
72
+ export function fetchDueManualBatches(now, limit, dep) {
73
+ return dep.db
74
+ .prepare(`SELECT * FROM codex_cronoton_manual_batches
75
+ WHERE status = 'active' AND next_at IS NOT NULL AND next_at <= ?
76
+ ORDER BY next_at ASC LIMIT ?`)
77
+ .all(now.toISOString(), limit);
78
+ }
79
+ /**
80
+ * Atomically claim one fire slot of a batch BEFORE the inline fire (mirrors
81
+ * claimDueCodexCronoton): a single conditional UPDATE increments `completed`,
82
+ * advances `next_at` (+interval, or NULL on the final slot) and flips status to
83
+ * 'completed' on the last slot. The WHERE clause re-asserts the due predicate so
84
+ * two racing claimers see exactly one win. Returns true when this caller won the
85
+ * slot (changes === 1) and should fire.
86
+ */
87
+ export function claimManualBatchFire(batch, now, dep) {
88
+ const db = dep.db;
89
+ const nowIso = now.toISOString();
90
+ const nextAtIso = new Date(now.getTime() + batch.interval_seconds * 1000).toISOString();
91
+ const result = db
92
+ .prepare(`UPDATE codex_cronoton_manual_batches
93
+ SET completed = completed + 1,
94
+ next_at = CASE WHEN completed + 1 < total THEN ? ELSE NULL END,
95
+ status = CASE WHEN completed + 1 < total THEN 'active' ELSE 'completed' END,
96
+ modified_at = ?
97
+ WHERE id = ? AND status = 'active' AND next_at IS NOT NULL
98
+ AND next_at <= ? AND completed < total`)
99
+ .run(nextAtIso, nowIso, batch.id, nowIso);
100
+ return result.changes === 1;
101
+ }
102
+ /** Operator (or auto) cancel of an active batch. Idempotent: ok=false if not active. */
103
+ export function cancelManualBatch(id, dep) {
104
+ const result = dep.db
105
+ .prepare(`UPDATE codex_cronoton_manual_batches
106
+ SET status = 'cancelled', next_at = NULL, modified_at = ?
107
+ WHERE id = ? AND status = 'active'`)
108
+ .run(new Date().toISOString(), id);
109
+ return { ok: result.changes === 1 };
110
+ }
@@ -0,0 +1,21 @@
1
+ import type { CodexCronotonRow, CodexManualBatchRow, CodexTxConfig, CodexTxDefinition, ManualBatchView } from '../types.js';
2
+ /**
3
+ * The single mapper from a `codex_cronotons` row to the `CodexTxDefinition`
4
+ * consumed by the executor. `scheduleKind` is `'one-time'` ONLY for the
5
+ * one-time mode; all other six modes map to `'recurring'`.
6
+ */
7
+ export declare function rowToDefinition(row: CodexCronotonRow): CodexTxDefinition;
8
+ /** True when the row is opted into external (HMAC-endpoint) firing. */
9
+ export declare function rowExternalFireable(row: CodexCronotonRow): boolean;
10
+ /** The declared runtime-arg keys for the row; empty for ordinary rows. */
11
+ export declare function rowRuntimeArgKeys(row: CodexCronotonRow): string[];
12
+ /**
13
+ * AUTO-gas commit-gate: an `autoGasLimit === true` row cannot be committed
14
+ * without a concrete positive numeric `gasLimit` (the prior simulate's
15
+ * calibrated output, supplied by the client). The API does NOT re-run a
16
+ * simulate at commit time — it enforces the presence of a concrete limit so the
17
+ * autonomous fire always has one (the tick never has a human to calibrate).
18
+ */
19
+ export declare function assertAutoGasGate(config: CodexTxConfig): void;
20
+ /** Project a raw batch row onto the client-facing view (clamping remaining). */
21
+ export declare function manualBatchView(row: CodexManualBatchRow): ManualBatchView;
@@ -0,0 +1,62 @@
1
+ import { parseRuntimeArgKeys } from '../pure/runtime-args.js';
2
+ import { AutoGasGateError } from './errors.js';
3
+ function parseJson(json, fallback) {
4
+ if (json == null)
5
+ return fallback;
6
+ return JSON.parse(json);
7
+ }
8
+ /**
9
+ * The single mapper from a `codex_cronotons` row to the `CodexTxDefinition`
10
+ * consumed by the executor. `scheduleKind` is `'one-time'` ONLY for the
11
+ * one-time mode; all other six modes map to `'recurring'`.
12
+ */
13
+ export function rowToDefinition(row) {
14
+ return {
15
+ pactCode: row.pact_code,
16
+ config: parseJson(row.config_json, {}),
17
+ payload: parseJson(row.payload_json, {}),
18
+ gasPayer: parseJson(row.gas_payer_json, {
19
+ type: 'gas-station',
20
+ }),
21
+ signers: parseJson(row.signers_json, []),
22
+ scheduleKind: row.schedule_mode === 'one-time' ? 'one-time' : 'recurring',
23
+ serverResolver: row.server_resolver ?? undefined,
24
+ };
25
+ }
26
+ /** True when the row is opted into external (HMAC-endpoint) firing. */
27
+ export function rowExternalFireable(row) {
28
+ return row.external_fireable === 1;
29
+ }
30
+ /** The declared runtime-arg keys for the row; empty for ordinary rows. */
31
+ export function rowRuntimeArgKeys(row) {
32
+ return parseRuntimeArgKeys(row.runtime_arg_keys);
33
+ }
34
+ /**
35
+ * AUTO-gas commit-gate: an `autoGasLimit === true` row cannot be committed
36
+ * without a concrete positive numeric `gasLimit` (the prior simulate's
37
+ * calibrated output, supplied by the client). The API does NOT re-run a
38
+ * simulate at commit time — it enforces the presence of a concrete limit so the
39
+ * autonomous fire always has one (the tick never has a human to calibrate).
40
+ */
41
+ export function assertAutoGasGate(config) {
42
+ if (config.autoGasLimit !== true)
43
+ return;
44
+ if (!Number.isFinite(config.gasLimit) || config.gasLimit <= 0) {
45
+ throw new AutoGasGateError();
46
+ }
47
+ }
48
+ /** Project a raw batch row onto the client-facing view (clamping remaining). */
49
+ export function manualBatchView(row) {
50
+ return {
51
+ id: row.id,
52
+ codexCronotonId: row.codex_cronoton_id,
53
+ total: row.total,
54
+ completed: row.completed,
55
+ remaining: Math.max(0, row.total - row.completed),
56
+ intervalSeconds: row.interval_seconds,
57
+ status: row.status,
58
+ nextAt: row.next_at,
59
+ createdBy: row.created_by,
60
+ createdAt: row.created_at,
61
+ };
62
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The server tick — the async select → claim → fire → record → finalize → audit
3
+ * sequence, lifted from the Hub `lib/codex-cronoton/tick.ts` into a pure
4
+ * ctx-taking form.
5
+ *
6
+ * The Hub reached its DB, audit log, and fire dispatcher through ambient globals
7
+ * (`getDb()`, `logAuditFromWorker`, a `stoicism-mint` re-export). Here every one
8
+ * of those is injected on {@link TickCtx} and threaded explicitly: `{ db }` into
9
+ * each store call, `{ db, resolveFireMode }` into the fire record, the full
10
+ * `{ runtime, resolver, config, db, deps }` into {@link fireByServerResolver},
11
+ * and `onAudit(...)` for the two audit action strings.
12
+ *
13
+ * ── CLAIM-BEFORE-FIRE / once-only contract (LOAD-BEARING) ─────────────────────
14
+ * Because the fire runs inline and can block for minutes, each due row's
15
+ * `next_fire_at` MUST be advanced (recurring) or cleared (one-time) atomically
16
+ * BEFORE the await via {@link claimDueCodexCronoton}:
17
+ * - claim wins (true) → the row is no longer due/re-selectable; fire it.
18
+ * - claim lost (false) → an overlapping tick or a manual Execute-Now already
19
+ * claimed it → SKIP (no fire).
20
+ * The per-row atomic claim is the PRIMARY double-fire guard.
21
+ *
22
+ * ── Failure policy ────────────────────────────────────────────────────────────
23
+ * Single attempt, no retry, no backoff, NO auto-pause. Exactly ONE fire row per
24
+ * fire. A recurring FAILURE stays `active` (its next_fire_at was already advanced
25
+ * by the claim — the failure lives only in fire history). A one-time fire applies
26
+ * the executor's terminal intent (success → completed, failure → error). The fire
27
+ * dispatcher NEVER throws — the tick reads `result.ok`; the surrounding try/catch
28
+ * isolates only orchestration errors (rowToDefinition parse, recordFire write).
29
+ *
30
+ * The ONLY status write this tick issues is the one-time terminal transition via
31
+ * {@link applyTerminalIntent}. It NEVER writes `status='paused'` and issues NO
32
+ * post-fire recurring advance (the claim already advanced it).
33
+ */
34
+ import type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode } from "./seams.js";
35
+ /**
36
+ * The injected context the tick runs against — a structural SUPERSET of the
37
+ * executor's `{ runtime, resolver }`, so {@link fireByServerResolver} receives
38
+ * `runtime`+`resolver`+`db` straight off it. Every host capability the Hub tick
39
+ * reached for ambiently arrives here.
40
+ */
41
+ export interface TickCtx {
42
+ db: Database;
43
+ resolver: KeyResolver;
44
+ runtime: ChainRuntime;
45
+ onAudit: OnAudit;
46
+ resolveFireMode: ResolveFireMode;
47
+ config: Config;
48
+ }
49
+ export interface CodexTickResult {
50
+ /** Rows that fired successfully (result ok:true). */
51
+ firedIds: string[];
52
+ /** Rows that fired but the dispatcher returned ok:false (fired-and-failed). */
53
+ failedIds: string[];
54
+ /** Rows skipped without firing (lost claim, or an orchestration error). */
55
+ skippedIds: string[];
56
+ }
57
+ /**
58
+ * Select → claim → fire → record → finalize → audit for every due codex
59
+ * cronoton. Fires INLINE via {@link fireByServerResolver} (map §8 divergence #3:
60
+ * always through the dispatcher, never the executor directly).
61
+ */
62
+ export declare function codexCronotonTickOnce(now: Date, ctx: TickCtx): Promise<CodexTickResult>;
63
+ export interface CodexManualBatchTickResult {
64
+ /** Batch ids that fired a slot successfully this tick. */
65
+ firedIds: string[];
66
+ /** Batch ids that fired a slot but the dispatcher returned ok:false. */
67
+ failedIds: string[];
68
+ /** Batch ids skipped (lost claim / orchestration error). */
69
+ skippedIds: string[];
70
+ /** Batch ids auto-cancelled because the parent cronoton is no longer active. */
71
+ cancelledIds: string[];
72
+ }
73
+ /**
74
+ * Process due manual-execution batches — the "Execute Now ×N" rail. For each
75
+ * batch with a due slot it fires the PARENT cronoton ONCE (the same shared fire +
76
+ * fire-row recording as the scheduled tick), spaced by the batch's interval. Each
77
+ * slot is CLAIMED before the inline fire so an overlapping tick cannot double-fire
78
+ * it. A batch fire records a fire row + a `manual_fire` audit (actor 'ancient',
79
+ * via 'manual_batch', attributed to the batch's creator) and NEVER advances the
80
+ * cronoton's own schedule. If the parent has left 'active', the batch is
81
+ * auto-cancelled instead of fired.
82
+ */
83
+ export declare function processDueManualBatchesOnce(now: Date, ctx: TickCtx): Promise<CodexManualBatchTickResult>;