@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,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";
@@ -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;