@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,44 @@
1
+ /**
2
+ * Pure, side-effect-free definition-fingerprint helper ported verbatim from the
3
+ * AncientHoldings hub store (lib/codex-cronoton/store.ts:168-206). Kept
4
+ * dependency-free (only `node:crypto`) so a fire can be pinned to the exact
5
+ * definition that ran, deterministically and key-order-independently.
6
+ */
7
+ import crypto from "node:crypto";
8
+ /** Recursively sort object keys so JSON.stringify is order-independent. */
9
+ function canonicalize(value) {
10
+ if (Array.isArray(value))
11
+ return value.map(canonicalize);
12
+ if (value && typeof value === "object") {
13
+ const sorted = {};
14
+ for (const key of Object.keys(value).sort()) {
15
+ sorted[key] = canonicalize(value[key]);
16
+ }
17
+ return sorted;
18
+ }
19
+ return value;
20
+ }
21
+ function parseJson(json, fallback) {
22
+ if (json == null)
23
+ return fallback;
24
+ return JSON.parse(json);
25
+ }
26
+ /**
27
+ * Stable sha256 hex over the canonical-key-sorted JSON of the definition parts.
28
+ * Computed at FIRE time from the row-as-it-then-is so a historical fire is
29
+ * attributable to the exact definition that ran even after an edit. Pure +
30
+ * deterministic + key-order-independent.
31
+ */
32
+ export function computeDefinitionFingerprint(row) {
33
+ const parts = {
34
+ pactCode: row.pact_code,
35
+ config: parseJson(row.config_json, {}),
36
+ payload: parseJson(row.payload_json, {}),
37
+ gasPayer: parseJson(row.gas_payer_json, {}),
38
+ signers: parseJson(row.signers_json, []),
39
+ scheduleMode: row.schedule_mode,
40
+ scheduleConfig: parseJson(row.schedule_config_json, {}),
41
+ };
42
+ const canonical = JSON.stringify(canonicalize(parts));
43
+ return crypto.createHash("sha256").update(canonical).digest("hex");
44
+ }
@@ -0,0 +1,34 @@
1
+ import type { CodexTxDefinition } from '../types.js';
2
+ /** A validated bag of runtime args — every value is a string (Pact `read-string`). */
3
+ export type RuntimeArgs = Record<string, string>;
4
+ /** Parse the row's `runtime_arg_keys` JSON column to a string[] (empty on null/garbage). */
5
+ export declare function parseRuntimeArgKeys(raw: string | null | undefined): string[];
6
+ export type ValidateRuntimeArgsResult = {
7
+ ok: true;
8
+ args: RuntimeArgs;
9
+ } | {
10
+ ok: false;
11
+ error: string;
12
+ };
13
+ /**
14
+ * Validate supplied args against the declared keys. The supplied object must
15
+ * carry EXACTLY the declared keys (no missing, no extra) and every value must be
16
+ * a string. Rejects when the cronoton declares no runtime args (declaredKeys
17
+ * empty) — such a cronoton is not runtime-arg-fireable.
18
+ */
19
+ export declare function validateRuntimeArgs(declaredKeys: string[], supplied: unknown): ValidateRuntimeArgsResult;
20
+ /**
21
+ * Merge validated runtime args into a definition's payload (env-data). Throws if
22
+ * any arg key collides with a fixed payload key — a runtime arg must never be able
23
+ * to override a keyset or other fixed data (defense-in-depth; commit-time
24
+ * validation already forbids the overlap).
25
+ */
26
+ export declare function applyRuntimeArgs(definition: CodexTxDefinition, args: RuntimeArgs): CodexTxDefinition;
27
+ /** True when any declared runtime-arg key overlaps the fixed payload keys (a misconfiguration). */
28
+ export declare function runtimeArgKeysCollide(payload: Record<string, unknown>, declaredKeys: string[]): boolean;
29
+ /**
30
+ * A stable sha256 over the canonical (key-sorted) args — recorded per fire for
31
+ * provenance. The arg VALUES themselves go on-chain via the request key; the hash
32
+ * lets an auditor tie a fire row to the exact args without storing them verbatim.
33
+ */
34
+ export declare function hashRuntimeArgs(args: RuntimeArgs): string;
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Runtime-arg injection for codex-cronotons.
3
+ *
4
+ * Ordinarily a codex-cronoton's transaction is fully frozen at definition time.
5
+ * A RUNTIME-ARG cronoton instead DECLARES a set of env-data keys
6
+ * (`runtime_arg_keys`) whose values are supplied by the TRIGGER — the external
7
+ * Pythia endpoint or the ancient manual form — at fire time and merged into the
8
+ * payload, so the Pact code reads them via `(read-string "key")`.
9
+ *
10
+ * SAFETY: values are always strings and flow through env-data (`addData`), NEVER
11
+ * string-concatenated into `pactCode` — so there is no code-injection surface.
12
+ * And a runtime arg can NEVER clobber a fixed payload key (e.g. a keyset): the
13
+ * declared keys must be disjoint from the template payload (enforced at commit),
14
+ * and `applyRuntimeArgs` throws on any collision as a defense-in-depth net.
15
+ *
16
+ * These helpers are pure + `@stoachain`-free, so they are unit-testable and
17
+ * importable by both the API routes and the worker.
18
+ */
19
+ import crypto from 'node:crypto';
20
+ /** Parse the row's `runtime_arg_keys` JSON column to a string[] (empty on null/garbage). */
21
+ export function parseRuntimeArgKeys(raw) {
22
+ if (!raw)
23
+ return [];
24
+ let parsed;
25
+ try {
26
+ parsed = JSON.parse(raw);
27
+ }
28
+ catch {
29
+ return [];
30
+ }
31
+ if (!Array.isArray(parsed))
32
+ return [];
33
+ return parsed.filter((k) => typeof k === 'string' && k.length > 0);
34
+ }
35
+ /**
36
+ * Validate supplied args against the declared keys. The supplied object must
37
+ * carry EXACTLY the declared keys (no missing, no extra) and every value must be
38
+ * a string. Rejects when the cronoton declares no runtime args (declaredKeys
39
+ * empty) — such a cronoton is not runtime-arg-fireable.
40
+ */
41
+ export function validateRuntimeArgs(declaredKeys, supplied) {
42
+ if (declaredKeys.length === 0) {
43
+ return { ok: false, error: 'this cronoton declares no runtime args' };
44
+ }
45
+ if (supplied == null || typeof supplied !== 'object' || Array.isArray(supplied)) {
46
+ return { ok: false, error: 'args must be an object' };
47
+ }
48
+ const obj = supplied;
49
+ const declared = new Set(declaredKeys);
50
+ for (const k of Object.keys(obj)) {
51
+ if (!declared.has(k))
52
+ return { ok: false, error: `unexpected arg "${k}"` };
53
+ }
54
+ // Null-prototype + own-property checks so a (self-declared) key like `__proto__`
55
+ // is handled by identity — never swallowed by an inherited setter or a
56
+ // false-positive `in` on Object.prototype.
57
+ const args = Object.create(null);
58
+ for (const k of declaredKeys) {
59
+ if (!Object.prototype.hasOwnProperty.call(obj, k))
60
+ return { ok: false, error: `missing arg "${k}"` };
61
+ const v = obj[k];
62
+ if (typeof v !== 'string')
63
+ return { ok: false, error: `arg "${k}" must be a string` };
64
+ args[k] = v;
65
+ }
66
+ return { ok: true, args };
67
+ }
68
+ /**
69
+ * Merge validated runtime args into a definition's payload (env-data). Throws if
70
+ * any arg key collides with a fixed payload key — a runtime arg must never be able
71
+ * to override a keyset or other fixed data (defense-in-depth; commit-time
72
+ * validation already forbids the overlap).
73
+ */
74
+ export function applyRuntimeArgs(definition, args) {
75
+ for (const k of Object.keys(args)) {
76
+ if (Object.prototype.hasOwnProperty.call(definition.payload, k)) {
77
+ throw new Error(`runtime arg "${k}" collides with a fixed payload key`);
78
+ }
79
+ }
80
+ return { ...definition, payload: { ...definition.payload, ...args } };
81
+ }
82
+ /** True when any declared runtime-arg key overlaps the fixed payload keys (a misconfiguration). */
83
+ export function runtimeArgKeysCollide(payload, declaredKeys) {
84
+ return declaredKeys.some((k) => Object.prototype.hasOwnProperty.call(payload, k));
85
+ }
86
+ /**
87
+ * A stable sha256 over the canonical (key-sorted) args — recorded per fire for
88
+ * provenance. The arg VALUES themselves go on-chain via the request key; the hash
89
+ * lets an auditor tie a fire row to the exact args without storing them verbatim.
90
+ */
91
+ export function hashRuntimeArgs(args) {
92
+ const sorted = Object.keys(args)
93
+ .sort()
94
+ .reduce((o, k) => {
95
+ o[k] = args[k];
96
+ return o;
97
+ }, {});
98
+ return crypto.createHash('sha256').update(JSON.stringify(sorted)).digest('hex');
99
+ }
@@ -0,0 +1,140 @@
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 type { ChainRuntime, Config, Database, DbDep, KeyResolver } from "./seams.js";
25
+ import type { CodexTxDefinition, FireResult, SimulateResult } from "./types.js";
26
+ /** The plan + payload a single-tx resolver produces for one fire. */
27
+ export interface ServerResolverResolution {
28
+ /** Opaque per-entry settlement plan, forwarded verbatim to `settle`. */
29
+ plan: unknown[];
30
+ /** Payload keys merged into the fired definition before simulate/fire. */
31
+ payload: Record<string, unknown>;
32
+ }
33
+ /** Opts passed to a single-tx resolver's `settle` after a successful fire. */
34
+ export interface SettleOpts {
35
+ db?: Database;
36
+ /** The landed on-chain request key, so the ledger write links to the tx. */
37
+ requestKey?: string;
38
+ }
39
+ /**
40
+ * A single-tx server resolver: how to fill the payload + how to settle on
41
+ * success. The resolve/settle pair is consumed by {@link fireWithServerResolver}.
42
+ */
43
+ export interface SingleTxResolver {
44
+ kind: "single-tx";
45
+ resolve(dep?: DbDep): ServerResolverResolution;
46
+ settle(plan: unknown[], opts?: SettleOpts): void;
47
+ }
48
+ /**
49
+ * A multi-tx server resolver: a net-new orchestrator that owns its own fire
50
+ * cardinality and guard. `run` is the seam the tick dispatches to; its concrete
51
+ * signature/return is defined by the orchestrator that registers it. The
52
+ * registry only knows it is an async orchestrator taking an injected opts bag.
53
+ */
54
+ export interface MultiTxResolver {
55
+ kind: "multi-tx";
56
+ run(opts: unknown): Promise<unknown>;
57
+ }
58
+ /** Either resolver kind; the `kind` field discriminates the union. */
59
+ export type ServerResolver = SingleTxResolver | MultiTxResolver;
60
+ /**
61
+ * Register (or replace) a named server resolver. A module that owns a resolver
62
+ * calls this at module-eval time so the registry is populated by the time the
63
+ * tick consults it.
64
+ */
65
+ export declare function registerServerResolver(name: string, resolver: ServerResolver): void;
66
+ /** Read a registered resolver entry (with its `kind`) by name, or `undefined`. */
67
+ export declare function getServerResolver(name: string): ServerResolver | undefined;
68
+ /**
69
+ * Resolve a named SINGLE-TX resolver's plan + payload WITHOUT firing — used by a
70
+ * simulate/preview endpoint to show what a fire would produce. Returns `null`
71
+ * for an unknown name OR for a multi-tx resolver (which has no single-tx payload
72
+ * to preview).
73
+ */
74
+ export declare function resolveServerVars(name: string, dep?: DbDep): ServerResolverResolution | null;
75
+ /**
76
+ * Dispatch a registered MULTI-TX resolver's orchestrator. The tick routes a
77
+ * multi-tx `serverResolver` here instead of through {@link fireWithServerResolver}.
78
+ * Throws for an unknown name, or for a name registered as single-tx (routing it
79
+ * here would force its merge through the wrong path).
80
+ */
81
+ export declare function dispatchMultiTxResolver(name: string, opts: unknown): Promise<unknown>;
82
+ /**
83
+ * The two-arg executor seam. Defaults to a ctx-bound closure over the Phase-3
84
+ * {@link executeCodexTransaction}; a test may inject a `vi.fn()` in its place.
85
+ * The overloads preserve the mode→result discrimination so `exec(def,'fire')`
86
+ * yields a {@link FireResult} and `exec(def,'simulate')` a {@link SimulateResult}.
87
+ */
88
+ interface ExecFn {
89
+ (definition: CodexTxDefinition, mode: "simulate"): Promise<SimulateResult>;
90
+ (definition: CodexTxDefinition, mode: "fire"): Promise<FireResult>;
91
+ }
92
+ /**
93
+ * An optional settlement-observation hook. Replaces the Hub's stoicism-specific
94
+ * `recordStoicismEvent` coupling: a resolver that wants its own settlement
95
+ * telemetry passes `onEvent`; the default is a no-op and no host module is wired.
96
+ */
97
+ export type OnResolverEvent = (event: unknown) => void;
98
+ /** Injectable seams for the single-tx fire path (default to the registry/executor). */
99
+ export interface FireOpts {
100
+ /** Executor seam; default binds `runtime`+`resolver`+`config` into the Phase-3 executor. */
101
+ exec?: ExecFn;
102
+ runtime?: ChainRuntime;
103
+ resolver?: KeyResolver;
104
+ config?: Partial<Config>;
105
+ db?: Database;
106
+ /** Override the single-tx resolve (else the registered resolver's). */
107
+ resolve?: (dep?: DbDep) => ServerResolverResolution;
108
+ /** Override the single-tx settle (else the registered resolver's). */
109
+ settle?: (plan: unknown[], opts?: SettleOpts) => void;
110
+ /** Optional settlement-observation hook (no-op default). */
111
+ onEvent?: OnResolverEvent;
112
+ }
113
+ /** Opts for the top-level fire dispatcher: {@link FireOpts} plus multi-tx `deps`. */
114
+ export interface FireByServerResolverOpts extends FireOpts {
115
+ /** Orchestrator opts forwarded verbatim to a multi-tx resolver's `run`. */
116
+ deps?: unknown;
117
+ }
118
+ /**
119
+ * The single fire-time dispatcher the tick calls for EVERY row. Routes by kind:
120
+ * - no `serverResolver` → executor `fire` (pass-through);
121
+ * - registered `multi-tx` → {@link dispatchMultiTxResolver} + summary adapt;
122
+ * - otherwise → {@link fireWithServerResolver} (the single-tx merge path).
123
+ *
124
+ * NEVER throws out: a multi-tx orchestrator throw becomes a `postponed`
125
+ * FireResult so the tick records a single failure fire row rather than aborting.
126
+ */
127
+ export declare function fireByServerResolver(definition: CodexTxDefinition, row: unknown, opts?: FireByServerResolverOpts): Promise<FireResult>;
128
+ /**
129
+ * Single-tx fire-time wrapper. For an ordinary row (no `serverResolver`) this is
130
+ * a pure pass-through to `exec(def,'fire')`. For a single-tx server-resolved row
131
+ * it resolves the payload → runs a SAFETY-GUARD simulate (postpone on failure or
132
+ * over-budget gas) → fires → settles on success. A settlement failure AFTER a
133
+ * successful fire NEVER marks the fire failed (the tx already landed; settlement
134
+ * is idempotent) — it is surfaced via the optional `onEvent` hook.
135
+ *
136
+ * A multi-tx resolver name is REFUSED here (postponed): it must be dispatched via
137
+ * {@link dispatchMultiTxResolver}, never merged+fired through this single path.
138
+ */
139
+ export declare function fireWithServerResolver(definition: CodexTxDefinition, _row: unknown, opts?: FireOpts): Promise<FireResult>;
140
+ export {};
@@ -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
+ }