@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
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@ All notable changes to `@ancientpantheon/khronoton-core`.
4
4
 
5
5
  The engine's pre-extraction history lives in the AncientHoldings hub, whose inline scheduler ("Cronoton") this package extracts and generalises.
6
6
 
7
+ ## 0.2.0 — 2026-07-12
8
+
9
+ Added the **server/automaton engine** on a new `@ancientpantheon/khronoton-core/server` subpath — the stand-alone layer a consuming Automaton (e.g. Mnemosyne) needs to run scheduled, signed, on-chain firing. The root `.` schedule engine (7-mode math + `tickOnce`) is byte-unchanged; this is purely additive.
10
+
11
+ Lifted faithfully from the AncientHoldings hub's inline `codex-cronoton` system (~4,250 lines) and generalised behind **six injection seams** — `KeyResolver` (codex signing), `ChainRuntime` (chain client + constants), `Database` (a minimal structural handle; `better-sqlite3` satisfies it), `onAudit`, `resolveFireMode`, and a 6-field `Config` — so the package pulls no `@stoachain/*` symbol, no database driver, and no framework. What ships:
12
+
13
+ - **Store + atomic claim-before-fire (exactly-once).** The load-bearing invariant: a due fire is claimed by a conditional `UPDATE` that re-asserts the due predicate and advances `next_fire_at` in the same statement, firing only on `changes === 1`. Two overlapping ticks fire a row once — the primary double-fire guard, no leader election. Proven at the store layer and again end-to-end.
14
+ - **Headless single-transaction executor.** `executeCodexTransaction(definition, mode, ctx)` behind the `ChainRuntime` + `KeyResolver` seams: fire never throws (structured failure), dirty-read pre-flight gate (no submit on a failing pre-flight), AUTO-gas calibrate (rebuild + re-sign at the calibrated limit), and 504/derived-request-key recovery. The Hub's cross-chain SPV block is intentionally dropped.
15
+ - **Server tick + loop.** `codexCronotonTickOnce` / `processDueManualBatchesOnce` take an injected `ctx`; `startKhronotonLoop(ctx) → stop()` drives them on `config.tickIntervalMs` with a single-instance re-entrancy guard (a multi-minute inline fire never launches an overlapping tick).
16
+ - **Server-resolver registry/dispatcher.** A generic `registerServerResolver` / `fireByServerResolver` mechanism (single-tx and multi-tx kinds) between the tick and the executor; no concrete host resolvers are shipped.
17
+ - **`installSchema(db)`** — one driver-free installer for the three tables (`codex_cronotons`, `codex_cronoton_fires`, `codex_cronoton_manual_batches`), consolidating the Hub's migration chain and genericised (no host FKs/CHECKs).
18
+ - **Two definition-of-done integration tests** — a double-fire once-only proof and a codex-signs-a-scheduled-tx proof, both end-to-end against a real in-memory SQLite with mock seams.
19
+
20
+ The subpath carries the same dual `{ types, import, require }` exports condition as the root (the 0.1.1 CJS lesson), so a `tsx`/CommonJS host can `require('@ancientpantheon/khronoton-core/server')`. `better-sqlite3` is an optional dependency (reference/test backend only); the package keeps zero required runtime dependencies. Proprietary / all-rights-reserved posture unchanged.
21
+
7
22
  ## 0.1.1 — 2026-07-04
8
23
 
9
24
  Packaging fix — no API or behaviour change. Added a `require` condition to the package `exports` map (`"." → { types, import, require }`, all resolving to the ESM `dist/index.js`) so the package is a drop-in for CommonJS consumers as well as ESM ones. This makes it loadable by hosts whose runtime resolves bare specifiers through CommonJS `require` — notably the AncientHoldings hub's worker, which runs via `tsx` in CJS mode; under 0.1.0's `import`-only exports it hit `ERR_PACKAGE_PATH_NOT_EXPORTED` on a static import. Node 22.12+ (`require(esm)`) loads the ESM build synchronously; no separate CJS build is shipped. The engine code, types, and `dist/` output are byte-identical to 0.1.0. 0.1.0 is superseded (deprecate recommended).
package/README.md CHANGED
@@ -6,7 +6,7 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
6
6
 
7
7
  ## Status
8
8
 
9
- **`0.1.1` on public npmjs** — headless scheduler engine, drop-in for both ESM and CommonJS consumers. Both engines are implemented and locked by contract suites in `tests/`: the schedule math (the 7-mode model, `computeNextFire`, `summariseSchedule`, and the in-tree cron parser) and the injectable `tickOnce(now, deps)` tick engine. Consumed by the AncientHoldings hub, which injects storage and firing through the three hooks.
9
+ **`0.2.0` on public npmjs** — the headless scheduler engine at the root `.` import (unchanged), plus a new **server/automaton engine** at the `@ancientpantheon/khronoton-core/server` subpath. The root schedule math (the 7-mode model, `computeNextFire`, `summariseSchedule`, the in-tree cron parser) and the injectable `tickOnce(now, deps)` engine are locked by contract suites; the `/server` surface adds the full stand-alone automaton behind six injection seams — the store + atomic claim-before-fire (exactly-once), the headless single-transaction executor, the server tick + `startKhronotonLoop`, the server-resolver registry, and `installSchema` — so a consuming Automaton (e.g. Mnemosyne) can run scheduled on-chain firing by injecting only its host adapters. Both import conditions (ESM `import` + CJS `require`) resolve on both the root and the subpath.
10
10
 
11
11
  ## Schedule engine
12
12
 
@@ -138,9 +138,79 @@ const result = tickOnce(new Date('2026-05-24T12:00:00.500Z'), {
138
138
 
139
139
  Persistence, queues, timers, HTTP, or any framework binding — those stay in the host (the AncientHoldings hub keeps its own glue and imports this package for the scheduling logic). The `tickOnce` tick engine walks due schedules and invokes host hooks, but it never touches storage, queues, or clocks itself — the host injects all coupling through `loadDue`/`enqueueFire`/`persistNextFire`.
140
140
 
141
- ## Install
141
+ ## Server engine (`/server`)
142
+
143
+ The `@ancientpantheon/khronoton-core/server` subpath is the stand-alone automaton layer: everything needed to run scheduled, signed, on-chain firing on top of the root schedule engine. It ships **no** chain client, **no** database driver, and **no** framework — the host injects those through six seams. The root `.` import (pure schedule math + `tickOnce`) is byte-unchanged and carries no server dependency.
144
+
145
+ ```ts
146
+ import {
147
+ installSchema,
148
+ codexCronotonTickOnce,
149
+ processDueManualBatchesOnce,
150
+ startKhronotonLoop,
151
+ executeCodexTransaction,
152
+ registerServerResolver,
153
+ fireByServerResolver,
154
+ } from '@ancientpantheon/khronoton-core/server';
155
+ ```
156
+
157
+ ### The six injection seams
158
+
159
+ The host provides these; the engine stays framework- and chain-agnostic:
160
+
161
+ - **`KeyResolver`** — resolves a public key to a signing keypair (`getKeyPairByPublicKey`, `listCodexPubs`). This is where the codex signs.
162
+ - **`ChainRuntime`** — the chain client + constants: a Pact builder, `createClient(url) → { dirtyRead, submit, listen }`, a universal signer, gas helpers (`calculateAutoGasLimit`, `anuToStoa`), and `networkId` / `namespace` / `getPactUrl` / `gasStationAccount`.
163
+ - **`Database`** — a minimal structural handle (`exec`, `prepare(...).run/get/all`); a `better-sqlite3` instance satisfies it structurally, but any driver of that shape works. Run `installSchema(db)` once to create the three tables.
164
+ - **`onAudit`** — a sink called once per fire with `{ action, result, targetKind, targetId, detail }`.
165
+ - **`resolveFireMode`** — synchronous `(cronotonId) => 'test' | 'live'`; a per-row `fire_mode_override='live'` wins first.
166
+ - **`Config`** — six optional knobs; each defaults when omitted:
167
+
168
+ | Field | Default | Meaning |
169
+ | --- | --- | --- |
170
+ | `tickIntervalMs` | `30_000` | Loop interval |
171
+ | `listenTimeoutMs` | `300_000` | Fire listen timeout |
172
+ | `autoGasCeiling` | `2_000_000` | AUTO-gas pre-flight build ceiling |
173
+ | `singleTxGasGuard` | `1_600_000` | Server-resolver single-tx gas guard |
174
+ | `tickBatchLimit` | `100` | Rows claimed per tick |
175
+ | `manualBatch` | `{ min: 2, max: 60, intervalSeconds: 60 }` | Manual-batch bounds + spacing |
176
+
177
+ (There is no `gasPriceFloor` or `ttl` knob — the executor uses each cronoton's own `definition.config` gas price and TTL directly.)
178
+
179
+ ### Exactly-once (claim-before-fire)
142
180
 
143
- Not yet installable — the package is unpublished. Once released:
181
+ A due fire happens **once and only once**. Before firing, the tick issues an atomic conditional `UPDATE` that re-asserts the row is still due and advances its `next_fire_at` in the same statement; it fires only if that write claimed the row (`changes === 1`). Two overlapping ticks on the same row → the second claim is a no-op → no double-submit. This is the primary double-fire guard and needs **no leader election**; a multi-worker lease, if ever wanted, is the host's concern.
182
+
183
+ ### Wire-in recipe (Automaton host, e.g. Mnemosyne)
184
+
185
+ ```ts
186
+ import Database from 'better-sqlite3';
187
+ import { installSchema, startKhronotonLoop } from '@ancientpantheon/khronoton-core/server';
188
+
189
+ const db = new Database('automaton.db');
190
+ db.pragma('foreign_keys = ON');
191
+ installSchema(db);
192
+
193
+ const ctx = {
194
+ db,
195
+ resolver, // your KeyResolver adapter
196
+ runtime, // your ChainRuntime adapter
197
+ onAudit, // your audit sink
198
+ resolveFireMode, // () => 'test' | 'live'
199
+ config, // full Config (or omit fields to take the defaults above)
200
+ };
201
+
202
+ const { stop } = startKhronotonLoop(ctx); // ticks every config.tickIntervalMs; call stop() to halt
203
+ ```
204
+
205
+ ### API route contract (deferred)
206
+
207
+ This bump ships the engine only. Framework-agnostic HTTP handlers (create/edit/list/trigger/simulate a cronoton) are **not** included — a host writes thin routes over the exported store + `executeCodexTransaction`/`fireByServerResolver` surface. The route contract is documented for that; concrete handlers arrive in a later bump.
208
+
209
+ ### Node floor
210
+
211
+ The `/server` subpath's CJS `require` condition relies on Node's `require(esm)` support (Node **≥ 20.19 / ≥ 22.12**), the same mechanism as the root's 0.1.1 `require` condition — so the effective Node floor for CommonJS consumers is ≥ 20.19. The package `engines` field stays `>=20` (unchanged), matching the root.
212
+
213
+ ## Install
144
214
 
145
215
  ```bash
146
216
  npm install @ancientpantheon/khronoton-core
@@ -148,6 +218,8 @@ npm install @ancientpantheon/khronoton-core
148
218
 
149
219
  ## Version history
150
220
 
221
+ **v0.2.0** — Added the server/automaton engine on the new `@ancientpantheon/khronoton-core/server` subpath (dual ESM `import` + CJS `require`), behind six injection seams (`KeyResolver`, `ChainRuntime`, `Database`, `onAudit`, `resolveFireMode`, `Config`): the store + atomic claim-before-fire (exactly-once, proven end-to-end), the headless single-transaction executor (never-throws-on-fire, dirty-read pre-flight, AUTO-gas calibrate, 504/derived-key recovery), the server tick + `startKhronotonLoop`, the server-resolver registry/dispatcher, and `installSchema` for the three tables — lifted faithfully from the AncientHoldings hub's inline `codex-cronoton` system and generalised. The root `.` schedule engine is unchanged.
222
+
151
223
  **v0.1.1** — Packaging fix: added a `require` condition to the exports map so the package is a drop-in for CommonJS consumers (e.g. the hub's tsx/CJS worker) as well as ESM. No API or behaviour change from v0.1.0.
152
224
 
153
225
  **v0.1.0** — First published version: 7-mode schedule engine + injectable tickOnce tick engine.
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Signer-planning helpers for the headless codex executor.
3
+ *
4
+ * These three helpers are pure (string / signer-list in, signer-list out) and
5
+ * carry NO chain dependency: the namespace and gas-station account are plain
6
+ * string params, so the executor's gas-payer self-heal is unit-testable without
7
+ * any chain runtime. `buildTransaction` (the executor) consumes
8
+ * `effectiveSigners` + `deriveSenderAccount` to plan the signer set and sender.
9
+ */
10
+ import type { CodexTxDefinition, CodexSigner } from "./types.js";
11
+ /** Strip a leading `k:` prefix from an address if present. */
12
+ export declare function stripPrefix(addr: string): string;
13
+ /** Derive the Pact `senderAccount` string from the gas-payer reference. */
14
+ export declare function deriveSenderAccount(gasPayer: CodexTxDefinition["gasPayer"], gasStation: string): string;
15
+ /**
16
+ * Resolve the effective signer set the executor builds + signs, reconciling the
17
+ * gas-payer's auto-managed signer with the definition's own signers:
18
+ *
19
+ * - codex gas-payer: it must sign `coin.GAS`. If the gas-payer pubkey is
20
+ * absent it is auto-included as a `pure` signer; if already present (e.g. a
21
+ * prepended `coin.GAS` scoped signer) it is left untouched — never
22
+ * duplicated.
23
+ * - gas-station gas-payer: the gas station pays, but a codex key must sign the
24
+ * namespaced `DALOS.GAS_PAYER` capability. A scoped signer for
25
+ * `gasStationSignerKey` is SYNTHESIZED here (server-side, so the client stays
26
+ * free of the namespace constant). A missing key is a contract violation
27
+ * surfaced as a throw (caught + structured on fire).
28
+ */
29
+ export declare function effectiveSigners(definition: CodexTxDefinition, kadenaNamespace: string): CodexSigner[];
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Signer-planning helpers for the headless codex executor.
3
+ *
4
+ * These three helpers are pure (string / signer-list in, signer-list out) and
5
+ * carry NO chain dependency: the namespace and gas-station account are plain
6
+ * string params, so the executor's gas-payer self-heal is unit-testable without
7
+ * any chain runtime. `buildTransaction` (the executor) consumes
8
+ * `effectiveSigners` + `deriveSenderAccount` to plan the signer set and sender.
9
+ */
10
+ /** Strip a leading `k:` prefix from an address if present. */
11
+ export function stripPrefix(addr) {
12
+ return addr.startsWith("k:") ? addr.slice(2) : addr;
13
+ }
14
+ /** Derive the Pact `senderAccount` string from the gas-payer reference. */
15
+ export function deriveSenderAccount(gasPayer, gasStation) {
16
+ if (gasPayer.type === "gas-station")
17
+ return gasStation;
18
+ return `k:${stripPrefix(gasPayer.address || "")}`;
19
+ }
20
+ /**
21
+ * Resolve the effective signer set the executor builds + signs, reconciling the
22
+ * gas-payer's auto-managed signer with the definition's own signers:
23
+ *
24
+ * - codex gas-payer: it must sign `coin.GAS`. If the gas-payer pubkey is
25
+ * absent it is auto-included as a `pure` signer; if already present (e.g. a
26
+ * prepended `coin.GAS` scoped signer) it is left untouched — never
27
+ * duplicated.
28
+ * - gas-station gas-payer: the gas station pays, but a codex key must sign the
29
+ * namespaced `DALOS.GAS_PAYER` capability. A scoped signer for
30
+ * `gasStationSignerKey` is SYNTHESIZED here (server-side, so the client stays
31
+ * free of the namespace constant). A missing key is a contract violation
32
+ * surfaced as a throw (caught + structured on fire).
33
+ */
34
+ export function effectiveSigners(definition, kadenaNamespace) {
35
+ const signers = [...definition.signers];
36
+ if (definition.gasPayer.type === "codex" && definition.gasPayer.address) {
37
+ const gasPub = stripPrefix(definition.gasPayer.address);
38
+ if (!signers.some((s) => s.publicKey === gasPub)) {
39
+ signers.push({
40
+ publicKey: gasPub,
41
+ capabilityMode: "pure",
42
+ capabilities: "",
43
+ });
44
+ }
45
+ }
46
+ if (definition.gasPayer.type === "gas-station") {
47
+ const gasKey = definition.gasPayer.gasStationSignerKey;
48
+ if (!gasKey) {
49
+ throw new Error("Gas-station gas payer requires a signing key for the DALOS.GAS_PAYER capability.");
50
+ }
51
+ if (!signers.some((s) => s.publicKey === gasKey)) {
52
+ signers.push({
53
+ publicKey: gasKey,
54
+ capabilityMode: "scoped",
55
+ capabilities: `(${kadenaNamespace}.DALOS.GAS_PAYER "" 0 0.0)`,
56
+ });
57
+ }
58
+ }
59
+ return signers;
60
+ }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * The headless single-transaction codex executor.
3
+ *
4
+ * Lifted from the AncientHoldings hub (`lib/codex-cronoton/executor.ts`,
5
+ * single-tx path) behind the Phase-1 seams: every `@stoachain/*` runtime value
6
+ * arrives through the injected {@link ChainRuntime} and every keypair through
7
+ * the injected {@link KeyResolver}. This module pulls NO `@stoachain/*` symbol,
8
+ * does NO dynamic `import()`, and never constructs a concrete key resolver — the
9
+ * two-line hub bootstrap (`loadRuntime()` + `new CodexKeyResolver()`) is
10
+ * replaced by a caller-supplied {@link ExecutorCtx}.
11
+ *
12
+ * Four load-bearing invariants are preserved verbatim:
13
+ * - fire NEVER throws (F-002) — every failure returns a structured result;
14
+ * - the dirty-read pre-flight gate (F-001) — a failing pre-flight never submits;
15
+ * - AUTO-gas calibrate — build at the ceiling, rebuild + re-sign at the
16
+ * dirty-read-derived limit;
17
+ * - the 504/derived-request-key recovery (REQ-23) — the request key is derived
18
+ * from the signed command hash UP FRONT so a lost submit response or a listen
19
+ * timeout never discards a tx that may already be on-chain.
20
+ */
21
+ import type { ChainRuntime, KeyResolver, Config } from "./seams.js";
22
+ import type { CodexTxDefinition, FireResult, SimulateResult } from "./types.js";
23
+ /** Listen (confirmation) timeout default: 5 minutes. Overridable via `ctx.config.listenTimeoutMs`. */
24
+ export { LISTEN_TIMEOUT_MS } from "./seams.js";
25
+ /**
26
+ * The injected dependencies the executor runs against. `config` is OPTIONAL —
27
+ * when omitted the module-constant defaults apply. This is a superset-compatible
28
+ * shape: Phase 4's fuller tick ctx (`{ db, resolver, runtime, onAudit,
29
+ * resolveFireMode, config }`) structurally satisfies it, so a tick passes its
30
+ * ctx straight through.
31
+ */
32
+ export interface ExecutorCtx {
33
+ runtime: ChainRuntime;
34
+ resolver: KeyResolver;
35
+ config?: Partial<Config>;
36
+ }
37
+ /**
38
+ * Execute a codex transaction in `simulate` (sign + dirty-read, NO submit) or
39
+ * `fire` (pre-flight dirty-read → submit → listen) mode against the injected
40
+ * {@link ExecutorCtx}.
41
+ *
42
+ * `fire` mode NEVER throws on chain/sign/decrypt failure (F-002): every failure
43
+ * mode — dirty-read failure, sign-incompletion, submit error, listen timeout,
44
+ * and resolver/decrypt rejection — returns a structured
45
+ * `{ ok: false, error, terminalIntent }`. A one-time entry whose fire threw
46
+ * would otherwise get no terminalIntent and re-fire on the next tick.
47
+ *
48
+ * `simulate` mode surfaces build errors (zero signers, gas-station with no
49
+ * signing key) as throws to the caller, but converts chain-side dirty-read
50
+ * failures into structured results.
51
+ */
52
+ export declare function executeCodexTransaction(definition: CodexTxDefinition, mode: "simulate", ctx: ExecutorCtx): Promise<SimulateResult>;
53
+ export declare function executeCodexTransaction(definition: CodexTxDefinition, mode: "fire", ctx: ExecutorCtx): Promise<FireResult>;
@@ -0,0 +1,280 @@
1
+ /**
2
+ * The headless single-transaction codex executor.
3
+ *
4
+ * Lifted from the AncientHoldings hub (`lib/codex-cronoton/executor.ts`,
5
+ * single-tx path) behind the Phase-1 seams: every `@stoachain/*` runtime value
6
+ * arrives through the injected {@link ChainRuntime} and every keypair through
7
+ * the injected {@link KeyResolver}. This module pulls NO `@stoachain/*` symbol,
8
+ * does NO dynamic `import()`, and never constructs a concrete key resolver — the
9
+ * two-line hub bootstrap (`loadRuntime()` + `new CodexKeyResolver()`) is
10
+ * replaced by a caller-supplied {@link ExecutorCtx}.
11
+ *
12
+ * Four load-bearing invariants are preserved verbatim:
13
+ * - fire NEVER throws (F-002) — every failure returns a structured result;
14
+ * - the dirty-read pre-flight gate (F-001) — a failing pre-flight never submits;
15
+ * - AUTO-gas calibrate — build at the ceiling, rebuild + re-sign at the
16
+ * dirty-read-derived limit;
17
+ * - the 504/derived-request-key recovery (REQ-23) — the request key is derived
18
+ * from the signed command hash UP FRONT so a lost submit response or a listen
19
+ * timeout never discards a tx that may already be on-chain.
20
+ */
21
+ import { LISTEN_TIMEOUT_MS, AUTO_GAS_CEILING } from "./seams.js";
22
+ import { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
23
+ import { effectiveSigners, deriveSenderAccount } from "./executor-signers.js";
24
+ /** Listen (confirmation) timeout default: 5 minutes. Overridable via `ctx.config.listenTimeoutMs`. */
25
+ export { LISTEN_TIMEOUT_MS } from "./seams.js";
26
+ /**
27
+ * Build a Pact transaction from the definition:
28
+ * `Pact.builder.execution().setMeta().setNetworkId()` + an `addData` loop over
29
+ * the payload + pure-vs-scoped `addSigner`. Throws if no signers.
30
+ */
31
+ function buildTransaction(runtime, definition, signers, gasLimitOverride) {
32
+ if (signers.length === 0) {
33
+ throw new Error("At least one signer is required to build a codex transaction.");
34
+ }
35
+ const senderAccount = deriveSenderAccount(definition.gasPayer, runtime.gasStationAccount);
36
+ const builder = runtime.Pact.builder.execution(definition.pactCode);
37
+ builder
38
+ .setMeta({
39
+ senderAccount,
40
+ chainId: definition.config.chainId,
41
+ gasLimit: gasLimitOverride ?? definition.config.gasLimit,
42
+ gasPrice: runtime.anuToStoa(definition.config.gasPrice),
43
+ ttl: definition.config.ttl,
44
+ })
45
+ .setNetworkId(runtime.networkId);
46
+ for (const [key, value] of Object.entries(definition.payload)) {
47
+ builder.addData(key, value);
48
+ }
49
+ for (const signer of signers) {
50
+ if (signer.capabilityMode === "pure") {
51
+ builder.addSigner(signer.publicKey);
52
+ }
53
+ else {
54
+ builder.addSigner(signer.publicKey, (withCapability) => {
55
+ const caps = [];
56
+ for (const line of (signer.capabilities || "").split("\n")) {
57
+ const parsed = parseCapabilityLine(line);
58
+ if (parsed)
59
+ caps.push(withCapability(parsed.name, ...parsed.args));
60
+ }
61
+ return caps;
62
+ });
63
+ }
64
+ }
65
+ return builder.createTransaction();
66
+ }
67
+ /**
68
+ * Resolve + build the `UniversalKeypair[]` for all signers via the injected
69
+ * resolver, then sign. `IKadenaKeypair.privateKey` maps to
70
+ * `UniversalKeypair.secretKey`; the derived-seed WASM-path fields
71
+ * (`encryptedSecretKey`, `password`) are carried through (F-004). Asserts the
72
+ * result is a fully signed transaction or throws.
73
+ */
74
+ async function signTransaction(runtime, resolver, signers, tx) {
75
+ const keypairs = [];
76
+ for (const signer of signers) {
77
+ const kp = await resolver.getKeyPairByPublicKey(signer.publicKey);
78
+ keypairs.push({
79
+ publicKey: kp.publicKey,
80
+ secretKey: kp.privateKey,
81
+ seedType: kp.seedType,
82
+ encryptedSecretKey: kp.encryptedSecretKey,
83
+ password: kp.password,
84
+ });
85
+ }
86
+ const signed = await runtime.universalSignTransaction(tx, keypairs);
87
+ if (!runtime.isSignedTransaction(signed)) {
88
+ throw new Error("Signing incomplete: one or more signatures are missing after universalSignTransaction.");
89
+ }
90
+ return signed;
91
+ }
92
+ /** Extract a human-readable error from a dirty-read/failure result. */
93
+ function dirtyReadError(result) {
94
+ return result.error?.message || "Transaction simulation failed on-chain.";
95
+ }
96
+ /** Listen with a timeout (`Promise.race`, `clearTimeout` cleanup). */
97
+ async function listenWithTimeout(listen, descriptor, timeoutMs) {
98
+ let timeoutId = null;
99
+ try {
100
+ return await Promise.race([
101
+ listen(descriptor).finally(() => {
102
+ if (timeoutId)
103
+ clearTimeout(timeoutId);
104
+ }),
105
+ new Promise((_, reject) => {
106
+ timeoutId = setTimeout(() => reject(new Error("Transaction confirmation timed out. Check explorer with the request key.")), timeoutMs);
107
+ }),
108
+ ]);
109
+ }
110
+ finally {
111
+ if (timeoutId)
112
+ clearTimeout(timeoutId);
113
+ }
114
+ }
115
+ async function runSimulate(ctx, definition, signers) {
116
+ const { runtime, resolver } = ctx;
117
+ const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
118
+ const { autoGasLimit } = definition.config;
119
+ const tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
120
+ const signed = await signTransaction(runtime, resolver, signers, tx);
121
+ const { dirtyRead } = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
122
+ const simulation = await dirtyRead(signed);
123
+ if (simulation.result.status === "failure") {
124
+ return {
125
+ ok: false,
126
+ mode: "simulate",
127
+ error: dirtyReadError(simulation.result),
128
+ rawResult: simulation.result,
129
+ terminalIntent: null,
130
+ };
131
+ }
132
+ const gasUsed = simulation.gas || 0;
133
+ const calibratedGasLimit = autoGasLimit && gasUsed > 0
134
+ ? runtime.calculateAutoGasLimit(gasUsed)
135
+ : undefined;
136
+ return {
137
+ ok: true,
138
+ mode: "simulate",
139
+ gasUsed,
140
+ calibratedGasLimit,
141
+ rawResult: simulation.result,
142
+ terminalIntent: null,
143
+ };
144
+ }
145
+ async function runFire(ctx, definition, signers) {
146
+ const { runtime, resolver } = ctx;
147
+ const ceiling = ctx.config?.autoGasCeiling ?? AUTO_GAS_CEILING;
148
+ const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
149
+ const { chainId, autoGasLimit } = definition.config;
150
+ const client = runtime.createClient(runtime.getPactUrl(chainId));
151
+ // Build + sign for the pre-flight dirty-read.
152
+ let tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
153
+ let signed = await signTransaction(runtime, resolver, signers, tx);
154
+ // (F-001) Pre-submit dirty-read pre-flight — never submit a tx a pre-flight
155
+ // would catch (saves a one-time terminal fire + gas).
156
+ const preflight = await client.dirtyRead(signed);
157
+ if (preflight.result.status === "failure") {
158
+ return {
159
+ ok: false,
160
+ mode: "fire",
161
+ chainId,
162
+ error: dirtyReadError(preflight.result),
163
+ rawResult: preflight.result,
164
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
165
+ };
166
+ }
167
+ // Auto-gas: rebuild + re-sign with the calibrated limit from the dirty-read.
168
+ if (autoGasLimit && (preflight.gas || 0) > 0) {
169
+ const calibrated = runtime.calculateAutoGasLimit(preflight.gas || 0);
170
+ tx = buildTransaction(runtime, definition, signers, calibrated);
171
+ signed = await signTransaction(runtime, resolver, signers, tx);
172
+ }
173
+ // The request key is the DETERMINISTIC hash of the signed command, so derive
174
+ // it (and the networkId) from `signed` UP FRONT. A lost or timed-out submit
175
+ // RESPONSE — e.g. an nginx 504 returned while the node had ALREADY accepted
176
+ // the tx into its mempool — must never discard a key we can compute ourselves.
177
+ const signedAny = signed;
178
+ const derivedRequestKey = typeof signedAny.hash === "string" ? signedAny.hash : null;
179
+ let derivedNetworkId;
180
+ try {
181
+ const parsed = JSON.parse(typeof signedAny.cmd === "string" ? signedAny.cmd : "{}");
182
+ if (typeof parsed.networkId === "string")
183
+ derivedNetworkId = parsed.networkId;
184
+ }
185
+ catch {
186
+ /* cmd not JSON-parseable — leave networkId undefined */
187
+ }
188
+ let submitResult;
189
+ try {
190
+ submitResult = await client.submit(signed);
191
+ }
192
+ catch (submitErr) {
193
+ // Ambiguous submit: the node may have accepted the tx even though the HTTP
194
+ // response was lost. If we have the derived key, rebuild the listen
195
+ // descriptor and poll the chain by it — a tx that actually landed recovers
196
+ // as success; one that never sent times out below as a genuine failure
197
+ // (with the key preserved).
198
+ if (!derivedRequestKey)
199
+ throw submitErr;
200
+ const descriptor = {
201
+ requestKey: derivedRequestKey,
202
+ chainId,
203
+ };
204
+ if (derivedNetworkId)
205
+ descriptor.networkId = derivedNetworkId;
206
+ submitResult = descriptor;
207
+ }
208
+ // Listen, but NEVER let a timeout/error throw the request key away — a tx
209
+ // whose confirmation we couldn't observe may still be on-chain, so return a
210
+ // failure that PRESERVES the key for recovery instead of recording it NULL.
211
+ let result;
212
+ try {
213
+ result = await listenWithTimeout(client.listen, submitResult, listenMs);
214
+ }
215
+ catch (listenErr) {
216
+ return {
217
+ ok: false,
218
+ mode: "fire",
219
+ chainId,
220
+ requestKey: submitResult.requestKey,
221
+ error: listenErr instanceof Error
222
+ ? listenErr.message
223
+ : "Transaction confirmation could not be observed.",
224
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
225
+ };
226
+ }
227
+ if (result.result.status === "failure") {
228
+ return {
229
+ ok: false,
230
+ mode: "fire",
231
+ chainId,
232
+ requestKey: result.reqKey || submitResult.requestKey,
233
+ error: result.result.error?.message || "Transaction failed on-chain.",
234
+ rawResult: result.result,
235
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
236
+ };
237
+ }
238
+ return {
239
+ ok: true,
240
+ mode: "fire",
241
+ chainId,
242
+ requestKey: result.reqKey || submitResult.requestKey,
243
+ rawResult: result.result,
244
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", true),
245
+ };
246
+ }
247
+ export async function executeCodexTransaction(definition, mode, ctx) {
248
+ const { runtime } = ctx;
249
+ if (mode === "simulate") {
250
+ // Build-shape + gas-payer contract validation runs eagerly so callers see
251
+ // contract violations (zero signers, gas-station with no signing key) as a
252
+ // throw in simulate.
253
+ const signers = effectiveSigners(definition, runtime.namespace);
254
+ if (signers.length === 0) {
255
+ throw new Error("At least one signer is required to build a codex transaction.");
256
+ }
257
+ return runSimulate(ctx, definition, signers);
258
+ }
259
+ // Fire NEVER throws (F-002): every failure — including a gas-station signer
260
+ // contract violation — returns a structured result so a one-time entry's spent
261
+ // attempt is recorded instead of silently re-firing on the next tick.
262
+ try {
263
+ const signers = effectiveSigners(definition, runtime.namespace);
264
+ if (signers.length === 0) {
265
+ throw new Error("At least one signer is required to build a codex transaction.");
266
+ }
267
+ return await runFire(ctx, definition, signers);
268
+ }
269
+ catch (e) {
270
+ const error = (e instanceof Error ? e.message : String(e)) ||
271
+ (e instanceof Error ? `${e.name} (no message)` : "unknown fire error");
272
+ return {
273
+ ok: false,
274
+ mode: "fire",
275
+ chainId: definition.config.chainId,
276
+ error,
277
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
278
+ };
279
+ }
280
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Public entry for `@ancientpantheon/khronoton-core/server`.
3
+ *
4
+ * Re-exports the Phase-1 server surface: the shared domain types, the six
5
+ * injection seams (plus their carrier types and default tuning constants), the
6
+ * dependency-free pure helpers, and the driver-free `installSchema`. The
7
+ * schedule symbols the server surface leans on are re-exported from the root
8
+ * core so a consumer gets the whole contract from one entry (REQ-16) without a
9
+ * private copy. Every re-export is `export type` where the symbol is a type, so
10
+ * the emitted `.d.ts` stays fully erasable and carries no external module
11
+ * reference.
12
+ */
13
+ export type { ChainId, ExecutorMode, ScheduleKind, CapabilityMode, CodexSigner, CodexGasPayer, CodexTxConfig, CodexTxDefinition, TerminalIntent, SimulateResult, FireResult, ExecutorResult, CodexCronotonRow, CodexCronotonListItem, CodexFireMode, FireTxKey, CodexCronotonFireRow, CodexManualBatchRow, ManualBatchView, } from "./types.js";
14
+ export type { KeyResolver, ChainRuntime, Database, DbDep, OnAudit, ResolveFireMode, Config, IKadenaKeypair, UniversalKeypair, IUnsignedCommand, DirtyReadResult, ListenResult, ChainClient, Statement, AuditEvent, } from "./seams.js";
15
+ export { defaultOnAudit, defaultResolveFireMode, TICK_INTERVAL_MS, LISTEN_TIMEOUT_MS, AUTO_GAS_CEILING, SINGLE_TX_GAS_GUARD, TICK_BATCH_LIMIT, MANUAL_BATCH_MIN, MANUAL_BATCH_MAX, MANUAL_BATCH_INTERVAL_SECONDS, } from "./seams.js";
16
+ export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
17
+ export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
18
+ export type { RuntimeArgs, ValidateRuntimeArgsResult } from "./pure/runtime-args.js";
19
+ export { installSchema } from "./schema.js";
20
+ export type { ScheduleMode, ScheduleConfig } from "../schedule.js";
21
+ export { executeCodexTransaction } from "./executor.js";
22
+ export type { ExecutorCtx } from "./executor.js";
23
+ export { effectiveSigners } from "./executor-signers.js";
24
+ export * from "./store/index.js";
25
+ export * from "./resolvers.js";
26
+ export * from "./tick.js";
27
+ export * from "./loop.js";
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Public entry for `@ancientpantheon/khronoton-core/server`.
3
+ *
4
+ * Re-exports the Phase-1 server surface: the shared domain types, the six
5
+ * injection seams (plus their carrier types and default tuning constants), the
6
+ * dependency-free pure helpers, and the driver-free `installSchema`. The
7
+ * schedule symbols the server surface leans on are re-exported from the root
8
+ * core so a consumer gets the whole contract from one entry (REQ-16) without a
9
+ * private copy. Every re-export is `export type` where the symbol is a type, so
10
+ * the emitted `.d.ts` stays fully erasable and carries no external module
11
+ * reference.
12
+ */
13
+ // ── Seam defaults + tuning constants (T1.2) ──────────────────────────────────
14
+ export { defaultOnAudit, defaultResolveFireMode, TICK_INTERVAL_MS, LISTEN_TIMEOUT_MS, AUTO_GAS_CEILING, SINGLE_TX_GAS_GUARD, TICK_BATCH_LIMIT, MANUAL_BATCH_MIN, MANUAL_BATCH_MAX, MANUAL_BATCH_INTERVAL_SECONDS, } from "./seams.js";
15
+ // ── Pure helpers (T1.3 / T1.5) ───────────────────────────────────────────────
16
+ // `computeDefinitionFingerprint` is intentionally NOT exported here: the store
17
+ // barrel (`./store/index.js`, re-exported below) is its single export site, so
18
+ // the `/server` surface carries it once — mirroring the Hub, where it lived on
19
+ // the store module. Re-exporting it here too would duplicate that one binding.
20
+ export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
21
+ export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
22
+ // ── Consolidated schema installer (T1.6) ─────────────────────────────────────
23
+ export { installSchema } from "./schema.js";
24
+ // ── Headless executor (Phase 3: build/sign/simulate/fire behind the seams) ────
25
+ // `LISTEN_TIMEOUT_MS` is NOT re-exported here — the seam-defaults group above is
26
+ // its single barrel source (identical 300_000 constant), so re-exporting the
27
+ // executor's own copy would be a duplicate named export.
28
+ export { executeCodexTransaction } from "./executor.js";
29
+ export { effectiveSigners } from "./executor-signers.js";
30
+ // ── Store surface (Phase 2: errors, mappers, claim, fires, cronoton, batch) ───
31
+ // `export *` here is collision-free: the store barrel deliberately omits the
32
+ // `TICK_BATCH_LIMIT` / `MANUAL_BATCH_*` constants (seams.js above is their single
33
+ // source) and `computeDefinitionFingerprint` is exported ONLY through the store
34
+ // barrel now (the direct pure-helper re-export above was dropped).
35
+ export * from "./store/index.js";
36
+ // ── Server-resolver registry + fire dispatcher (Phase 4: registry, kind-routed
37
+ // fire, single-tx merge path). Collision-free: the constant it leans on
38
+ // (`SINGLE_TX_GAS_GUARD`) is imported from `./seams.js`, not re-declared, so the
39
+ // seam-defaults group above stays its single barrel source.
40
+ export * from "./resolvers.js";
41
+ // ── Server tick (Phase 4: select → claim → fire → record → finalize → audit).
42
+ // `codexCronotonTickOnce` / `processDueManualBatchesOnce` + `TickCtx` + the two
43
+ // tick result types. Collision-free: `TickCtx` and the result interfaces are
44
+ // declared only here, and the tick imports the store fns from their submodules
45
+ // (no re-export of an already-barrelled symbol).
46
+ export * from "./tick.js";
47
+ // ── Server loop driver (Phase 4: the single-instance setInterval driver with the
48
+ // one-boolean re-entrancy guard). `startKhronotonLoop` + its opts/handle types.
49
+ // Collision-free: it re-exports nothing already barrelled — it only imports the
50
+ // two tick fns (via `./tick.js`) as its injectable defaults.
51
+ export * from "./loop.js";