@ancientpantheon/khronoton-core 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +77 -3
- package/dist/server/executor-signers.d.ts +29 -0
- package/dist/server/executor-signers.js +60 -0
- package/dist/server/executor.d.ts +53 -0
- package/dist/server/executor.js +280 -0
- package/dist/server/index.d.ts +27 -0
- package/dist/server/index.js +51 -0
- package/dist/server/loop.d.ts +36 -0
- package/dist/server/loop.js +51 -0
- package/dist/server/pure/capability.d.ts +31 -0
- package/dist/server/pure/capability.js +63 -0
- package/dist/server/pure/fingerprint.d.ts +8 -0
- package/dist/server/pure/fingerprint.js +44 -0
- package/dist/server/pure/runtime-args.d.ts +34 -0
- package/dist/server/pure/runtime-args.js +99 -0
- package/dist/server/resolvers.d.ts +140 -0
- package/dist/server/resolvers.js +200 -0
- package/dist/server/schema.d.ts +31 -0
- package/dist/server/schema.js +93 -0
- package/dist/server/seams.d.ts +231 -0
- package/dist/server/seams.js +34 -0
- package/dist/server/store/claim.d.ts +59 -0
- package/dist/server/store/claim.js +97 -0
- package/dist/server/store/cronoton.d.ts +79 -0
- package/dist/server/store/cronoton.js +268 -0
- package/dist/server/store/errors.d.ts +26 -0
- package/dist/server/store/errors.js +40 -0
- package/dist/server/store/fires.d.ts +77 -0
- package/dist/server/store/fires.js +170 -0
- package/dist/server/store/index.d.ts +26 -0
- package/dist/server/store/index.js +33 -0
- package/dist/server/store/manual-batch.d.ts +38 -0
- package/dist/server/store/manual-batch.js +110 -0
- package/dist/server/store/mappers.d.ts +21 -0
- package/dist/server/store/mappers.js +62 -0
- package/dist/server/tick.d.ts +83 -0
- package/dist/server/tick.js +235 -0
- package/dist/server/types.d.ts +220 -0
- package/dist/server/types.js +14 -0
- package/package.json +16 -3
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single-instance loop driver — `startKhronotonLoop`.
|
|
3
|
+
*
|
|
4
|
+
* A `setInterval` at `config.tickIntervalMs` whose handler runs ONE tick pass
|
|
5
|
+
* ({@link codexCronotonTickOnce} then {@link processDueManualBatchesOnce}),
|
|
6
|
+
* guarded by a single closure boolean so a slow, multi-minute inline fire can
|
|
7
|
+
* NEVER have a second overlapping pass launched on top of it. This is the
|
|
8
|
+
* in-process re-entrancy guard (REQ-32); it is NOT leader election and NOT a
|
|
9
|
+
* multi-worker lease — the per-row atomic claim inside the tick remains the
|
|
10
|
+
* primary double-fire guard, and coordinating multiple hosts is the consumer's
|
|
11
|
+
* concern.
|
|
12
|
+
*
|
|
13
|
+
* The two tick fns are injectable via `opts` purely for unit-testing the driver
|
|
14
|
+
* without a real DB; production callers pass only `ctx` and get the real
|
|
15
|
+
* Phase-4 tick fns. A pass that throws is surfaced (not rethrown) so one bad
|
|
16
|
+
* tick cannot kill the interval, and the `finally` always releases the guard.
|
|
17
|
+
*/
|
|
18
|
+
import { codexCronotonTickOnce, processDueManualBatchesOnce } from "./tick.js";
|
|
19
|
+
import type { TickCtx } from "./tick.js";
|
|
20
|
+
/**
|
|
21
|
+
* Test/override seam: inject stand-ins for the two tick fns. Both default to the
|
|
22
|
+
* real Phase-4 exports, so a production caller supplies neither.
|
|
23
|
+
*/
|
|
24
|
+
export interface KhronotonLoopOpts {
|
|
25
|
+
runTick?: typeof codexCronotonTickOnce;
|
|
26
|
+
runManualBatch?: typeof processDueManualBatchesOnce;
|
|
27
|
+
}
|
|
28
|
+
/** The started-loop handle: `stop()` clears the interval and is idempotent. */
|
|
29
|
+
export interface KhronotonLoopHandle {
|
|
30
|
+
stop(): void;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Start the automaton loop against `ctx`. Returns a handle whose `stop()` clears
|
|
34
|
+
* the interval.
|
|
35
|
+
*/
|
|
36
|
+
export declare function startKhronotonLoop(ctx: TickCtx, opts?: KhronotonLoopOpts): KhronotonLoopHandle;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single-instance loop driver — `startKhronotonLoop`.
|
|
3
|
+
*
|
|
4
|
+
* A `setInterval` at `config.tickIntervalMs` whose handler runs ONE tick pass
|
|
5
|
+
* ({@link codexCronotonTickOnce} then {@link processDueManualBatchesOnce}),
|
|
6
|
+
* guarded by a single closure boolean so a slow, multi-minute inline fire can
|
|
7
|
+
* NEVER have a second overlapping pass launched on top of it. This is the
|
|
8
|
+
* in-process re-entrancy guard (REQ-32); it is NOT leader election and NOT a
|
|
9
|
+
* multi-worker lease — the per-row atomic claim inside the tick remains the
|
|
10
|
+
* primary double-fire guard, and coordinating multiple hosts is the consumer's
|
|
11
|
+
* concern.
|
|
12
|
+
*
|
|
13
|
+
* The two tick fns are injectable via `opts` purely for unit-testing the driver
|
|
14
|
+
* without a real DB; production callers pass only `ctx` and get the real
|
|
15
|
+
* Phase-4 tick fns. A pass that throws is surfaced (not rethrown) so one bad
|
|
16
|
+
* tick cannot kill the interval, and the `finally` always releases the guard.
|
|
17
|
+
*/
|
|
18
|
+
import { codexCronotonTickOnce, processDueManualBatchesOnce, } from "./tick.js";
|
|
19
|
+
/** Fallback cadence when `ctx.config.tickIntervalMs` is absent (30s). */
|
|
20
|
+
const DEFAULT_TICK_INTERVAL_MS = 30000;
|
|
21
|
+
/**
|
|
22
|
+
* Start the automaton loop against `ctx`. Returns a handle whose `stop()` clears
|
|
23
|
+
* the interval.
|
|
24
|
+
*/
|
|
25
|
+
export function startKhronotonLoop(ctx, opts) {
|
|
26
|
+
const runTick = opts?.runTick ?? codexCronotonTickOnce;
|
|
27
|
+
const runManualBatch = opts?.runManualBatch ?? processDueManualBatchesOnce;
|
|
28
|
+
let running = false;
|
|
29
|
+
const handle = setInterval(async () => {
|
|
30
|
+
// A prior pass is still in flight — do NOT stack an overlapping pass.
|
|
31
|
+
if (running)
|
|
32
|
+
return;
|
|
33
|
+
running = true;
|
|
34
|
+
try {
|
|
35
|
+
await runTick(new Date(), ctx);
|
|
36
|
+
await runManualBatch(new Date(), ctx);
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
// A bad pass must not kill the interval — surface and keep ticking.
|
|
40
|
+
console.error("[khronoton] loop pass failed:", err);
|
|
41
|
+
}
|
|
42
|
+
finally {
|
|
43
|
+
running = false;
|
|
44
|
+
}
|
|
45
|
+
}, ctx.config?.tickIntervalMs ?? DEFAULT_TICK_INTERVAL_MS);
|
|
46
|
+
return {
|
|
47
|
+
stop() {
|
|
48
|
+
clearInterval(handle);
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure, side-effect-free executor helpers ported verbatim from the
|
|
3
|
+
* AncientHoldings hub (lib/codex-cronoton/executor.ts:72-131). Kept dependency-
|
|
4
|
+
* free so the terminal-intent mapping and the capability parser can be reused
|
|
5
|
+
* and unit-pinned in isolation from the chain runtime seam.
|
|
6
|
+
*/
|
|
7
|
+
import type { ScheduleKind, ExecutorMode, TerminalIntent } from "../types.js";
|
|
8
|
+
/**
|
|
9
|
+
* Parse a single capability line into a structured `{ name, args }`.
|
|
10
|
+
*
|
|
11
|
+
* Supported formats:
|
|
12
|
+
* - `(module.CAP arg1 "arg2" 0.5)` — parenthesized with optional args
|
|
13
|
+
* - `module.CAP` — bare dotted name, no args
|
|
14
|
+
*
|
|
15
|
+
* Returns null if the line cannot be parsed. Known F-006 limitation: a negative
|
|
16
|
+
* numeric arg (`-1`) encodes as the STRING `'-1'` — the `/^\d+$/` int test
|
|
17
|
+
* rejects the leading minus, so it falls through to the raw-token branch. This
|
|
18
|
+
* behavior is preserved deliberately; do not "fix" it.
|
|
19
|
+
*/
|
|
20
|
+
export declare function parseCapabilityLine(line: string): {
|
|
21
|
+
name: string;
|
|
22
|
+
args: unknown[];
|
|
23
|
+
} | null;
|
|
24
|
+
/**
|
|
25
|
+
* Pure, side-effect-free terminal-intent mapping.
|
|
26
|
+
*
|
|
27
|
+
* - one-time + fire + success → completed (single attempt spent)
|
|
28
|
+
* - one-time + fire + ANY failure → error (single attempt spent — no retry)
|
|
29
|
+
* - recurring, or any simulate → null
|
|
30
|
+
*/
|
|
31
|
+
export declare function computeTerminalIntent(scheduleKind: ScheduleKind | undefined, mode: ExecutorMode, ok: boolean): TerminalIntent | null;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parse a single capability line into a structured `{ name, args }`.
|
|
3
|
+
*
|
|
4
|
+
* Supported formats:
|
|
5
|
+
* - `(module.CAP arg1 "arg2" 0.5)` — parenthesized with optional args
|
|
6
|
+
* - `module.CAP` — bare dotted name, no args
|
|
7
|
+
*
|
|
8
|
+
* Returns null if the line cannot be parsed. Known F-006 limitation: a negative
|
|
9
|
+
* numeric arg (`-1`) encodes as the STRING `'-1'` — the `/^\d+$/` int test
|
|
10
|
+
* rejects the leading minus, so it falls through to the raw-token branch. This
|
|
11
|
+
* behavior is preserved deliberately; do not "fix" it.
|
|
12
|
+
*/
|
|
13
|
+
export function parseCapabilityLine(line) {
|
|
14
|
+
const trimmed = line.trim();
|
|
15
|
+
if (!trimmed)
|
|
16
|
+
return null;
|
|
17
|
+
if (trimmed.startsWith("(") && trimmed.endsWith(")")) {
|
|
18
|
+
const inner = trimmed.slice(1, -1);
|
|
19
|
+
const spaceIndex = inner.indexOf(" ");
|
|
20
|
+
if (spaceIndex > -1) {
|
|
21
|
+
const capName = inner.substring(0, spaceIndex);
|
|
22
|
+
const argsString = inner.substring(spaceIndex + 1);
|
|
23
|
+
const args = [];
|
|
24
|
+
const argMatches = argsString.match(/("([^"\\]|\\.)*"|[^\s]+)/g) || [];
|
|
25
|
+
for (const arg of argMatches) {
|
|
26
|
+
if (arg.startsWith('"') && arg.endsWith('"')) {
|
|
27
|
+
args.push(arg.slice(1, -1));
|
|
28
|
+
}
|
|
29
|
+
else if (/^\d+$/.test(arg)) {
|
|
30
|
+
args.push({ int: parseInt(arg, 10) });
|
|
31
|
+
}
|
|
32
|
+
else if (/^\d*\.\d+$/.test(arg)) {
|
|
33
|
+
args.push({ decimal: arg });
|
|
34
|
+
}
|
|
35
|
+
else {
|
|
36
|
+
args.push(arg);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return { name: capName, args };
|
|
40
|
+
}
|
|
41
|
+
return { name: inner, args: [] };
|
|
42
|
+
}
|
|
43
|
+
if (trimmed.includes(".")) {
|
|
44
|
+
return { name: trimmed, args: [] };
|
|
45
|
+
}
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Pure, side-effect-free terminal-intent mapping.
|
|
50
|
+
*
|
|
51
|
+
* - one-time + fire + success → completed (single attempt spent)
|
|
52
|
+
* - one-time + fire + ANY failure → error (single attempt spent — no retry)
|
|
53
|
+
* - recurring, or any simulate → null
|
|
54
|
+
*/
|
|
55
|
+
export function computeTerminalIntent(scheduleKind, mode, ok) {
|
|
56
|
+
if (mode !== "fire")
|
|
57
|
+
return null;
|
|
58
|
+
if (scheduleKind !== "one-time")
|
|
59
|
+
return null;
|
|
60
|
+
return ok
|
|
61
|
+
? { status: "completed", clearNextFire: true }
|
|
62
|
+
: { status: "error", clearNextFire: true };
|
|
63
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { CodexCronotonRow } from "../types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Stable sha256 hex over the canonical-key-sorted JSON of the definition parts.
|
|
4
|
+
* Computed at FIRE time from the row-as-it-then-is so a historical fire is
|
|
5
|
+
* attributable to the exact definition that ran even after an edit. Pure +
|
|
6
|
+
* deterministic + key-order-independent.
|
|
7
|
+
*/
|
|
8
|
+
export declare function computeDefinitionFingerprint(row: CodexCronotonRow): string;
|
|
@@ -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 {};
|