@ancientpantheon/khronoton-core 0.12.0 → 0.14.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 (68) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +8 -0
  3. package/dist/blockchain/stoachain.d.ts +1 -1
  4. package/dist/blockchain/stoachain.js +16 -1
  5. package/dist/{chunk-GIGLXIMC.js → chunk-A5YODPKQ.js} +820 -23
  6. package/dist/{chunk-KQZYMPZS.js → chunk-WKI52IPY.js} +1 -1
  7. package/dist/{context-CApk-LP4.d.ts → context-P-rCtBbJ.d.ts} +1 -1
  8. package/dist/handlers/execute.d.ts +12 -4
  9. package/dist/handlers/execute.js +42 -5
  10. package/dist/handlers/index.d.ts +2 -1
  11. package/dist/handlers/index.js +4 -1
  12. package/dist/handlers/read.d.ts +11 -0
  13. package/dist/handlers/read.js +65 -1
  14. package/dist/handlers/steps.d.ts +3 -0
  15. package/dist/handlers/steps.js +152 -0
  16. package/dist/hooks/index.d.ts +3 -3
  17. package/dist/hooks/index.js +2 -2
  18. package/dist/provider/index.d.ts +3 -3
  19. package/dist/provider/index.js +33 -2
  20. package/dist/{seams-DUtxDw_U.d.ts → seams-Co8Tq4ka.d.ts} +24 -0
  21. package/dist/server/executor.d.ts +14 -1
  22. package/dist/server/executor.js +144 -26
  23. package/dist/server/index.d.ts +12 -2
  24. package/dist/server/index.js +38 -1
  25. package/dist/server/loop.d.ts +17 -13
  26. package/dist/server/loop.js +19 -12
  27. package/dist/server/planners/evict.d.ts +20 -0
  28. package/dist/server/planners/evict.js +143 -0
  29. package/dist/server/planners/inject.d.ts +22 -0
  30. package/dist/server/planners/inject.js +120 -0
  31. package/dist/server/planners/registry.d.ts +118 -0
  32. package/dist/server/planners/registry.js +94 -0
  33. package/dist/server/planners/stoa-unwrap.d.ts +23 -0
  34. package/dist/server/planners/stoa-unwrap.js +204 -0
  35. package/dist/server/planners/stoa-wrap.d.ts +26 -0
  36. package/dist/server/planners/stoa-wrap.js +229 -0
  37. package/dist/server/planners/unstall.d.ts +25 -0
  38. package/dist/server/planners/unstall.js +135 -0
  39. package/dist/server/pure/run-advance.d.ts +76 -0
  40. package/dist/server/pure/run-advance.js +94 -0
  41. package/dist/server/pure/split-plan.d.ts +144 -0
  42. package/dist/server/pure/split-plan.js +362 -0
  43. package/dist/server/pure/yields.d.ts +57 -0
  44. package/dist/server/pure/yields.js +101 -0
  45. package/dist/server/resolvers.js +48 -6
  46. package/dist/server/runs-driver.d.ts +92 -0
  47. package/dist/server/runs-driver.js +582 -0
  48. package/dist/server/schema.d.ts +6 -2
  49. package/dist/server/schema.js +89 -1
  50. package/dist/server/seams.d.ts +28 -0
  51. package/dist/server/seams.js +4 -0
  52. package/dist/server/store/errors.d.ts +38 -0
  53. package/dist/server/store/errors.js +61 -0
  54. package/dist/server/store/index.d.ts +7 -2
  55. package/dist/server/store/index.js +8 -2
  56. package/dist/server/store/mappers.d.ts +11 -0
  57. package/dist/server/store/mappers.js +20 -0
  58. package/dist/server/store/runs.d.ts +233 -0
  59. package/dist/server/store/runs.js +341 -0
  60. package/dist/server/store/steps.d.ts +54 -0
  61. package/dist/server/store/steps.js +74 -0
  62. package/dist/server/store/yields.d.ts +46 -0
  63. package/dist/server/store/yields.js +73 -0
  64. package/dist/server/tick.d.ts +7 -0
  65. package/dist/server/tick.js +50 -1
  66. package/dist/server/types.d.ts +42 -3
  67. package/dist/ui/index.js +2 -2
  68. package/package.json +1 -1
@@ -51,18 +51,58 @@ export { LISTEN_TIMEOUT_MS } from "./seams.js";
51
51
  function isSaneCeiling(v) {
52
52
  return typeof v === "number" && Number.isFinite(v) && v > 0;
53
53
  }
54
+ /**
55
+ * Live block-gas-limit cache, keyed by chain id — closes a cross-phase-
56
+ * review-found performance gap: `resolveCeiling` used to re-fetch on EVERY
57
+ * simulate/fire/submit call with no caching at all, including every leg of
58
+ * a fanned-out step (`ouronet.aqp-evict`/`ouronet.aqp-unstall` can produce
59
+ * dozens) and every probe of `split-plan.ts`'s own multi-probe sizing pass
60
+ * (up to ~7 per planning pass) — all serially (`driveRunOnce`'s own
61
+ * `for...of`+`await` submit loop is deliberate, never `Promise.all`), within
62
+ * ONE tick pass that `loop.ts`'s single `running` boolean gates for EVERY
63
+ * other in-flight run and due cronoton that tick. The block gas limit
64
+ * changes rarely, so a SHORT TTL (not a permanent cache, which could serve
65
+ * a stale value indefinitely in a long-running process) eliminates the
66
+ * redundant network chatter within one pass without that risk.
67
+ */
68
+ const CEILING_CACHE_TTL_MS = 30000;
69
+ const ceilingCache = new Map();
70
+ /**
71
+ * TEST-ONLY: clears the live ceiling cache. A test suite that exercises
72
+ * multiple scenarios against the SAME chain id with DIFFERENT mocked
73
+ * `getBlockGasLimit` return values (e.g. `executor.test.ts`'s own
74
+ * "live block gas limit" cases) would otherwise leak a cached value from
75
+ * an earlier test into a later one, since the cache above is genuine
76
+ * module-level state that persists across test cases within one file run.
77
+ * Not part of the public `/server` surface (not re-exported from
78
+ * `server/index.ts`) — import it directly from `./executor.js` in a test's
79
+ * own `beforeEach`.
80
+ */
81
+ export function __clearCeilingCacheForTests() {
82
+ ceilingCache.clear();
83
+ }
54
84
  /** Resolves the effective simulate/fire ceiling: an explicit config override
55
- * wins outright (no network call); else a best-effort live fetch off the
56
- * ALREADY-CONSTRUCTED client for this fire's own chain; else the static
57
- * fallback. Never throws — `getBlockGasLimit` failures are absorbed by the
58
- * adapter itself (see `blockchain/stoachain.ts`), and an out-of-range value
59
- * from EITHER source falls back to `AUTO_GAS_CEILING` rather than being
60
- * trusted verbatim. */
61
- async function resolveCeiling(ctx, client) {
85
+ * wins outright (no network call, no cache lookup); else a cached recent
86
+ * value for this chain when still fresh; else a best-effort live fetch off
87
+ * the ALREADY-CONSTRUCTED client for this fire's own chain, cached for
88
+ * {@link CEILING_CACHE_TTL_MS}; else the static fallback. Never throws —
89
+ * `getBlockGasLimit` failures are absorbed by the adapter itself (see
90
+ * `blockchain/stoachain.ts`), and an out-of-range value from EITHER source
91
+ * falls back to `AUTO_GAS_CEILING` rather than being trusted verbatim (and
92
+ * is never cached as a sane value in that case — `AUTO_GAS_CEILING` itself
93
+ * IS cached, so a chain whose adapter keeps failing doesn't re-attempt the
94
+ * live fetch on every single call either). */
95
+ async function resolveCeiling(ctx, client, chainId) {
62
96
  if (isSaneCeiling(ctx.config?.autoGasCeiling))
63
97
  return ctx.config.autoGasCeiling;
98
+ const now = Date.now();
99
+ const cached = ceilingCache.get(chainId);
100
+ if (cached && cached.expiresAt > now)
101
+ return cached.value;
64
102
  const live = await client.getBlockGasLimit?.();
65
- return isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
103
+ const resolved = isSaneCeiling(live) ? live : AUTO_GAS_CEILING;
104
+ ceilingCache.set(chainId, { value: resolved, expiresAt: now + CEILING_CACHE_TTL_MS });
105
+ return resolved;
66
106
  }
67
107
  /**
68
108
  * Build a Pact transaction from the definition:
@@ -160,6 +200,17 @@ async function signTransaction(runtime, resolver, signers, tx) {
160
200
  function dirtyReadError(result) {
161
201
  return result.error?.message || "Transaction simulation failed on-chain.";
162
202
  }
203
+ /**
204
+ * Describe a caught throw for a structured `{ ok: false, error }` result —
205
+ * shared by the `submit` and `fire` catch branches of
206
+ * {@link executeCodexTransaction} so a future change to how a thrown error is
207
+ * rendered (e.g. handling `AggregateError`) is made once, not twice.
208
+ * `fallbackLabel` names the mode for the truly-no-message case only.
209
+ */
210
+ function describeThrown(e, fallbackLabel) {
211
+ return ((e instanceof Error ? e.message : String(e)) ||
212
+ (e instanceof Error ? `${e.name} (no message)` : `unknown ${fallbackLabel} error`));
213
+ }
163
214
  /** Listen with a timeout (`Promise.race`, `clearTimeout` cleanup). */
164
215
  async function listenWithTimeout(listen, descriptor, timeoutMs) {
165
216
  let timeoutId = null;
@@ -183,7 +234,7 @@ async function runSimulate(ctx, definition, signers) {
183
234
  const { runtime, resolver } = ctx;
184
235
  const { autoGasLimit } = definition.config;
185
236
  const client = runtime.createClient(runtime.getPactUrl(definition.config.chainId));
186
- const ceiling = await resolveCeiling(ctx, client);
237
+ const ceiling = await resolveCeiling(ctx, client, definition.config.chainId);
187
238
  const tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
188
239
  const signed = await signTransaction(runtime, resolver, signers, tx);
189
240
  if (autoGasLimit && !client.preflightRead) {
@@ -227,12 +278,9 @@ async function runSimulate(ctx, definition, signers) {
227
278
  terminalIntent: null,
228
279
  };
229
280
  }
230
- async function runFire(ctx, definition, signers) {
281
+ async function submitTransaction(ctx, definition, signers, client, ceiling) {
231
282
  const { runtime, resolver } = ctx;
232
- const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
233
283
  const { chainId, autoGasLimit } = definition.config;
234
- const client = runtime.createClient(runtime.getPactUrl(chainId));
235
- const ceiling = await resolveCeiling(ctx, client);
236
284
  // Build + sign for the pre-flight read.
237
285
  let tx = buildTransaction(runtime, definition, signers, autoGasLimit ? ceiling : undefined);
238
286
  let signed = await signTransaction(runtime, resolver, signers, tx);
@@ -253,11 +301,9 @@ async function runFire(ctx, definition, signers) {
253
301
  if (preflight.result.status === "failure") {
254
302
  return {
255
303
  ok: false,
256
- mode: "fire",
257
304
  chainId,
258
305
  error: dirtyReadError(preflight.result),
259
306
  rawResult: preflight.result,
260
- terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
261
307
  };
262
308
  }
263
309
  // Refuse the unmineable case BEFORE any rebuild/resubmit — a transaction
@@ -267,11 +313,10 @@ async function runFire(ctx, definition, signers) {
267
313
  if (gasUsed > ceiling) {
268
314
  return {
269
315
  ok: false,
270
- mode: "fire",
271
316
  chainId,
272
317
  error: `Transaction needs ${gasUsed} gas, over the block limit of ${ceiling} — no gas setting can mine it. Reduce the transaction's size or complexity.`,
273
318
  rawResult: preflight.result,
274
- terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
319
+ gasUsed,
275
320
  };
276
321
  }
277
322
  // Auto-gas: rebuild + re-sign with the calibrated limit from the pre-flight read.
@@ -315,19 +360,43 @@ async function runFire(ctx, definition, signers) {
315
360
  descriptor.networkId = derivedNetworkId;
316
361
  submitResult = descriptor;
317
362
  }
363
+ return {
364
+ ok: true,
365
+ chainId,
366
+ requestKey: submitResult.requestKey,
367
+ networkId: derivedNetworkId,
368
+ };
369
+ }
370
+ async function runFire(ctx, definition, signers) {
371
+ const { runtime } = ctx;
372
+ const listenMs = ctx.config?.listenTimeoutMs ?? LISTEN_TIMEOUT_MS;
373
+ const { chainId } = definition.config;
374
+ const client = runtime.createClient(runtime.getPactUrl(chainId));
375
+ const ceiling = await resolveCeiling(ctx, client, chainId);
376
+ const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
377
+ if (!outcome.ok) {
378
+ return {
379
+ ok: false,
380
+ mode: "fire",
381
+ chainId: outcome.chainId,
382
+ error: outcome.error,
383
+ rawResult: outcome.rawResult,
384
+ terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
385
+ };
386
+ }
318
387
  // Listen, but NEVER let a timeout/error throw the request key away — a tx
319
388
  // whose confirmation we couldn't observe may still be on-chain, so return a
320
389
  // failure that PRESERVES the key for recovery instead of recording it NULL.
321
390
  let result;
322
391
  try {
323
- result = await listenWithTimeout(client.listen, submitResult, listenMs);
392
+ result = await listenWithTimeout(client.listen, { requestKey: outcome.requestKey, chainId: outcome.chainId, networkId: outcome.networkId }, listenMs);
324
393
  }
325
394
  catch (listenErr) {
326
395
  return {
327
396
  ok: false,
328
397
  mode: "fire",
329
- chainId,
330
- requestKey: submitResult.requestKey,
398
+ chainId: outcome.chainId,
399
+ requestKey: outcome.requestKey,
331
400
  error: listenErr instanceof Error
332
401
  ? listenErr.message
333
402
  : "Transaction confirmation could not be observed.",
@@ -338,8 +407,8 @@ async function runFire(ctx, definition, signers) {
338
407
  return {
339
408
  ok: false,
340
409
  mode: "fire",
341
- chainId,
342
- requestKey: result.reqKey || submitResult.requestKey,
410
+ chainId: outcome.chainId,
411
+ requestKey: result.reqKey || outcome.requestKey,
343
412
  error: result.result.error?.message || "Transaction failed on-chain.",
344
413
  rawResult: result.result,
345
414
  terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", false),
@@ -348,12 +417,40 @@ async function runFire(ctx, definition, signers) {
348
417
  return {
349
418
  ok: true,
350
419
  mode: "fire",
351
- chainId,
352
- requestKey: result.reqKey || submitResult.requestKey,
420
+ chainId: outcome.chainId,
421
+ requestKey: result.reqKey || outcome.requestKey,
353
422
  rawResult: result.result,
354
423
  terminalIntent: computeTerminalIntent(definition.scheduleKind, "fire", true),
355
424
  };
356
425
  }
426
+ /**
427
+ * `submit` builds, signs, pre-flights, and submits — exactly what `fire` does
428
+ * up through the submit-with-504-recovery step — but NEVER calls `listen`.
429
+ * Confirmation is a separate poll (Phase 3's driver), not this call's job.
430
+ */
431
+ async function runSubmit(ctx, definition, signers) {
432
+ const { runtime } = ctx;
433
+ const { chainId } = definition.config;
434
+ const client = runtime.createClient(runtime.getPactUrl(chainId));
435
+ const ceiling = await resolveCeiling(ctx, client, chainId);
436
+ const outcome = await submitTransaction(ctx, definition, signers, client, ceiling);
437
+ if (!outcome.ok) {
438
+ return {
439
+ ok: false,
440
+ mode: "submit",
441
+ chainId: outcome.chainId,
442
+ error: outcome.error,
443
+ rawResult: outcome.rawResult,
444
+ };
445
+ }
446
+ return {
447
+ ok: true,
448
+ mode: "submit",
449
+ requestKey: outcome.requestKey,
450
+ chainId: outcome.chainId,
451
+ networkId: outcome.networkId,
452
+ };
453
+ }
357
454
  export async function executeCodexTransaction(definition, mode, ctx) {
358
455
  const { runtime } = ctx;
359
456
  if (mode === "simulate") {
@@ -366,6 +463,28 @@ export async function executeCodexTransaction(definition, mode, ctx) {
366
463
  }
367
464
  return runSimulate(ctx, definition, signers);
368
465
  }
466
+ if (mode === "submit") {
467
+ // Submit NEVER throws, same F-002 guarantee `fire` has: it's a step
468
+ // toward on-chain submission, not a dry-run like `simulate`, so it
469
+ // inherits `fire`'s never-throws contract rather than `simulate`'s
470
+ // surface-build-errors contract.
471
+ try {
472
+ const signers = effectiveSigners(definition, runtime.namespace);
473
+ if (signers.length === 0) {
474
+ throw new Error("At least one signer is required to build a codex transaction.");
475
+ }
476
+ return await runSubmit(ctx, definition, signers);
477
+ }
478
+ catch (e) {
479
+ const error = describeThrown(e, "submit");
480
+ return {
481
+ ok: false,
482
+ mode: "submit",
483
+ chainId: definition.config.chainId,
484
+ error,
485
+ };
486
+ }
487
+ }
369
488
  // Fire NEVER throws (F-002): every failure — including a gas-station signer
370
489
  // contract violation — returns a structured result so a one-time entry's spent
371
490
  // attempt is recorded instead of silently re-firing on the next tick.
@@ -377,8 +496,7 @@ export async function executeCodexTransaction(definition, mode, ctx) {
377
496
  return await runFire(ctx, definition, signers);
378
497
  }
379
498
  catch (e) {
380
- const error = (e instanceof Error ? e.message : String(e)) ||
381
- (e instanceof Error ? `${e.name} (no message)` : "unknown fire error");
499
+ const error = describeThrown(e, "fire");
382
500
  return {
383
501
  ok: false,
384
502
  mode: "fire",
@@ -10,12 +10,15 @@
10
10
  * the emitted `.d.ts` stays fully erasable and carries no external module
11
11
  * reference.
12
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";
13
+ export type { ChainId, ExecutorMode, ScheduleKind, CapabilityMode, CodexSigner, CodexGasPayer, CodexTxConfig, CodexTxDefinition, TerminalIntent, SimulateResult, FireResult, SubmitResult, ExecutorResult, CodexCronotonRow, CodexCronotonListItem, CodexFireMode, FireTxKey, CodexCronotonFireRow, CodexManualBatchRow, ManualBatchView, } from "./types.js";
14
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";
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, RUN_STEP_DEADLINE_MS, DEFAULT_MAX_REPLAN_ATTEMPTS, } from "./seams.js";
16
16
  export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
17
17
  export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
18
18
  export type { RuntimeArgs, ValidateRuntimeArgsResult } from "./pure/runtime-args.js";
19
+ export { advanceRun } from "./pure/run-advance.js";
20
+ export type { StepMode, RunState, LegState, RunPolicy, RunAction } from "./pure/run-advance.js";
21
+ export { YieldNotFoundError } from "./pure/yields.js";
19
22
  export { installSchema } from "./schema.js";
20
23
  export type { ScheduleMode, ScheduleConfig } from "../schedule.js";
21
24
  export { executeCodexTransaction } from "./executor.js";
@@ -23,5 +26,12 @@ export type { ExecutorCtx } from "./executor.js";
23
26
  export { effectiveSigners } from "./executor-signers.js";
24
27
  export * from "./store/index.js";
25
28
  export * from "./resolvers.js";
29
+ export * from "./planners/registry.js";
30
+ export * from "./planners/evict.js";
31
+ export * from "./planners/inject.js";
32
+ export * from "./planners/unstall.js";
33
+ export * from "./planners/stoa-wrap.js";
34
+ export * from "./planners/stoa-unwrap.js";
26
35
  export * from "./tick.js";
27
36
  export * from "./loop.js";
37
+ export * from "./runs-driver.js";
@@ -11,7 +11,7 @@
11
11
  * reference.
12
12
  */
13
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";
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, RUN_STEP_DEADLINE_MS, DEFAULT_MAX_REPLAN_ATTEMPTS, } from "./seams.js";
15
15
  // ── Pure helpers (T1.3 / T1.5) ───────────────────────────────────────────────
16
16
  // `computeDefinitionFingerprint` is intentionally NOT exported here: the store
17
17
  // barrel (`./store/index.js`, re-exported below) is its single export site, so
@@ -19,6 +19,16 @@ export { defaultOnAudit, defaultResolveFireMode, TICK_INTERVAL_MS, LISTEN_TIMEOU
19
19
  // the store module. Re-exporting it here too would duplicate that one binding.
20
20
  export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
21
21
  export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
22
+ export { advanceRun } from "./pure/run-advance.js";
23
+ // ── Step-to-step yield carry (docs/work/khronoton-step-yield-carry) ──────────
24
+ // Only the typed error is public — `resolveYieldRefs`/`resolveSingleStepPayload`
25
+ // are internal resolution mechanics (consulted transparently by
26
+ // `resolvePlannerFor`/`runs-driver.ts`/`handlers/steps.ts`, never something an
27
+ // external caller builds a step against directly), matching every OTHER
28
+ // typed error this package throws (`RunAlreadyInFlightError`,
29
+ // `PlannerNotRegisteredError`, etc.) being public so a host can `instanceof`-
30
+ // check it from its own error handling.
31
+ export { YieldNotFoundError } from "./pure/yields.js";
22
32
  // ── Consolidated schema installer (T1.6) ─────────────────────────────────────
23
33
  export { installSchema } from "./schema.js";
24
34
  // ── Headless executor (Phase 3: build/sign/simulate/fire behind the seams) ────
@@ -38,6 +48,28 @@ export * from "./store/index.js";
38
48
  // (`SINGLE_TX_GAS_GUARD`) is imported from `./seams.js`, not re-declared, so the
39
49
  // seam-defaults group above stays its single barrel source.
40
50
  export * from "./resolvers.js";
51
+ // ── StepPlanner registry + the real `ouronet.aqp-evict`/`ouronet.aqp-inject`/
52
+ // `ouronet.aqp-unstall`/`ouronet.stoa-wrap`/`ouronet.stoa-unwrap` planners
53
+ // (Phase 4 / Phase 4.1 / Phase 4b: registerStepPlanner/getStepPlanner/
54
+ // StepPlanner/PlannedLeg/PlannerCtx, plus `evictPlanner`/`injectPlanner`/
55
+ // `unstallPlanner`/`stoaWrapPlanner`/`stoaUnwrapPlanner` themselves).
56
+ // Collision-free: none re-exports anything already barrelled above.
57
+ // Importing `./planners/evict.js`/`./planners/inject.js`/
58
+ // `./planners/unstall.js`/`./planners/stoa-wrap.js`/`./planners/stoa-unwrap.js`
59
+ // here is load-bearing, not cosmetic — their module-eval side effects
60
+ // (`registerStepPlanner("ouronet.aqp-evict", evictPlanner)`,
61
+ // `registerStepPlanner("ouronet.aqp-inject", injectPlanner)`,
62
+ // `registerStepPlanner("ouronet.aqp-unstall", unstallPlanner)`,
63
+ // `registerStepPlanner("ouronet.stoa-wrap", stoaWrapPlanner)`, and
64
+ // `registerStepPlanner("ouronet.stoa-unwrap", stoaUnwrapPlanner)`) are what
65
+ // make those planner names resolvable at all for a consumer who imports
66
+ // anything from this package's `/server` entry point.
67
+ export * from "./planners/registry.js";
68
+ export * from "./planners/evict.js";
69
+ export * from "./planners/inject.js";
70
+ export * from "./planners/unstall.js";
71
+ export * from "./planners/stoa-wrap.js";
72
+ export * from "./planners/stoa-unwrap.js";
41
73
  // ── Server tick (Phase 4: select → claim → fire → record → finalize → audit).
42
74
  // `codexCronotonTickOnce` / `processDueManualBatchesOnce` + `TickCtx` + the two
43
75
  // tick result types. Collision-free: `TickCtx` and the result interfaces are
@@ -49,3 +81,8 @@ export * from "./tick.js";
49
81
  // Collision-free: it re-exports nothing already barrelled — it only imports the
50
82
  // two tick fns (via `./tick.js`) as its injectable defaults.
51
83
  export * from "./loop.js";
84
+ // ── Chained-run driver (Phase 3: executes Phase 2's pure `advanceRun`
85
+ // decision function against the real store/chain). `driveRunOnce` +
86
+ // `advanceInFlightRunsOnce` + `RunsDriverCtx` + `PlannerNotRegisteredError`.
87
+ // Collision-free: it re-exports nothing already barrelled.
88
+ export * from "./runs-driver.js";
@@ -2,28 +2,32 @@
2
2
  * The single-instance loop driver — `startKhronotonLoop`.
3
3
  *
4
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.
5
+ * ({@link codexCronotonTickOnce} then {@link processDueManualBatchesOnce} then
6
+ * {@link advanceInFlightRunsOnce}), guarded by a single closure boolean so a
7
+ * slow, multi-minute inline fire can NEVER have a second overlapping pass
8
+ * launched on top of it. This is the in-process re-entrancy guard (REQ-32);
9
+ * it is NOT leader election and NOT a multi-worker lease — the per-row atomic
10
+ * claim inside the tick remains the primary double-fire guard, and
11
+ * coordinating multiple hosts is the consumer's concern.
12
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.
13
+ * The three pass fns are injectable via `opts` purely for unit-testing the
14
+ * driver without a real DB; production callers pass only `ctx` and get the
15
+ * real Phase-4 tick fns. A pass that throws is surfaced (not rethrown) so one
16
+ * bad tick cannot kill the interval, and the `finally` always releases the
17
+ * guard.
17
18
  */
18
19
  import { codexCronotonTickOnce, processDueManualBatchesOnce } from "./tick.js";
19
20
  import type { TickCtx } from "./tick.js";
21
+ import { advanceInFlightRunsOnce } from "./runs-driver.js";
20
22
  /**
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
+ * Test/override seam: inject stand-ins for the three pass fns. All three
24
+ * default to the real Phase-4/Phase-3 exports, so a production caller
25
+ * supplies none.
23
26
  */
24
27
  export interface KhronotonLoopOpts {
25
28
  runTick?: typeof codexCronotonTickOnce;
26
29
  runManualBatch?: typeof processDueManualBatchesOnce;
30
+ runAdvance?: typeof advanceInFlightRunsOnce;
27
31
  }
28
32
  /** The started-loop handle: `stop()` clears the interval and is idempotent. */
29
33
  export interface KhronotonLoopHandle {
@@ -2,20 +2,22 @@
2
2
  * The single-instance loop driver — `startKhronotonLoop`.
3
3
  *
4
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.
5
+ * ({@link codexCronotonTickOnce} then {@link processDueManualBatchesOnce} then
6
+ * {@link advanceInFlightRunsOnce}), guarded by a single closure boolean so a
7
+ * slow, multi-minute inline fire can NEVER have a second overlapping pass
8
+ * launched on top of it. This is the in-process re-entrancy guard (REQ-32);
9
+ * it is NOT leader election and NOT a multi-worker lease — the per-row atomic
10
+ * claim inside the tick remains the primary double-fire guard, and
11
+ * coordinating multiple hosts is the consumer's concern.
12
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.
13
+ * The three pass fns are injectable via `opts` purely for unit-testing the
14
+ * driver without a real DB; production callers pass only `ctx` and get the
15
+ * real Phase-4 tick fns. A pass that throws is surfaced (not rethrown) so one
16
+ * bad tick cannot kill the interval, and the `finally` always releases the
17
+ * guard.
17
18
  */
18
19
  import { codexCronotonTickOnce, processDueManualBatchesOnce, } from "./tick.js";
20
+ import { advanceInFlightRunsOnce } from "./runs-driver.js";
19
21
  /** Fallback cadence when `ctx.config.tickIntervalMs` is absent (30s). */
20
22
  const DEFAULT_TICK_INTERVAL_MS = 30000;
21
23
  /**
@@ -25,6 +27,7 @@ const DEFAULT_TICK_INTERVAL_MS = 30000;
25
27
  export function startKhronotonLoop(ctx, opts) {
26
28
  const runTick = opts?.runTick ?? codexCronotonTickOnce;
27
29
  const runManualBatch = opts?.runManualBatch ?? processDueManualBatchesOnce;
30
+ const runAdvance = opts?.runAdvance ?? advanceInFlightRunsOnce;
28
31
  let running = false;
29
32
  const handle = setInterval(async () => {
30
33
  // A prior pass is still in flight — do NOT stack an overlapping pass.
@@ -32,8 +35,12 @@ export function startKhronotonLoop(ctx, opts) {
32
35
  return;
33
36
  running = true;
34
37
  try {
35
- await runTick(new Date(), ctx);
38
+ const tickResult = await runTick(new Date(), ctx);
36
39
  await runManualBatch(new Date(), ctx);
40
+ // Exclude any run codexCronotonTickOnce already drove inline this same
41
+ // pass (design.md §B) — without this, a freshly created run would be
42
+ // driven (and its submitted leg polled) TWICE in one loop callback.
43
+ await runAdvance(new Date(), ctx, new Set(tickResult.drivenRunIds));
37
44
  }
38
45
  catch (err) {
39
46
  // A bad pass must not kill the interval — surface and keep ticking.
@@ -0,0 +1,20 @@
1
+ import { type StepPlanner } from "./registry.js";
2
+ /**
3
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-evict`:
4
+ *
5
+ * 1. Parse `fvtId`/`patronAccount` from `step.planner_params_json`.
6
+ * 2. Derive `executor = k:<the step's own first signer's publicKey>`.
7
+ * 3-4. Read the plan (`URHC_BuildEvictPlans`) via a simulate; a failed READ
8
+ * is never "needs splitting" — there is no plan to split.
9
+ * 5-6. Zero plan entries → `[]` (handleReplanStep treats this as a cleared
10
+ * barrier — see design.md §C).
11
+ * 7-8. Probe `CC_FullEvictRewards` as one candidate leg; a successful
12
+ * simulate → exactly that one leg.
13
+ * 9. A failed probe is "needs splitting" ONLY when `runSimulate`'s own
14
+ * `gasUsed > ceiling` refuse-unmineable branch produced it (signaled by a
15
+ * numeric `gasUsed` on the `ok:false` result) — any OTHER failure
16
+ * rethrows as a genuine error, never silently treated as "needs
17
+ * splitting".
18
+ * 10. Fan out: one `CC_EvictSingleReward` leg per plan entry.
19
+ */
20
+ export declare const evictPlanner: StepPlanner;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * `ouronet.aqp-evict` — the "Evict Rewards" step planner, ported from
3
+ * OuronetUI's `EvictSection.tsx`/`evictSpecs.tsx`/`fvtChain.ts` (a different
4
+ * workspace entirely: `OuroborosNetwork/daimons/OuronetUI`). See design.md's
5
+ * §D for the full port rationale.
6
+ *
7
+ * Shape: one Pact *read* (`URHC_BuildEvictPlans`) computes the plan ON-CHAIN,
8
+ * so this planner never decides leg count itself — it tries one transaction
9
+ * (`CC_FullEvictRewards`) first and only fans out to one leg per plan entry
10
+ * (`CC_EvictSingleReward`) when that one transaction genuinely cannot fit the
11
+ * block's gas ceiling (never on any OTHER simulate failure, which propagates
12
+ * as a real error instead — see step 9 below).
13
+ */
14
+ import { executeCodexTransaction } from "../executor.js";
15
+ import { registerStepPlanner, } from "./registry.js";
16
+ /** Mirrors `store/mappers.ts`'s own one-line helper — duplicated locally per the plan rather than importing a private function from another module. */
17
+ function parseJson(json, fallback) {
18
+ if (json == null)
19
+ return fallback;
20
+ return JSON.parse(json);
21
+ }
22
+ /**
23
+ * Validate one chain-read plan entry's shape before it is trusted enough to
24
+ * become part of a signed transaction's `payload` (env-data). This is a
25
+ * live chain-read response, not operator-configured `planner_params_json` —
26
+ * nothing in this codebase (or, per the ported source's own caveat, the
27
+ * `AQP-EVCT` contract) guarantees these fields are well-formed, so a bare
28
+ * type assertion over `unknown` is not enough here.
29
+ */
30
+ function isWellFormedEvictLeg(value) {
31
+ if (typeof value !== "object" || value === null)
32
+ return false;
33
+ const leg = value;
34
+ return (typeof leg.beneficiary === "string" &&
35
+ typeof leg.scoreEntityType === "number" &&
36
+ Number.isInteger(leg.scoreEntityType) &&
37
+ typeof leg.scoreEntityId === "string" &&
38
+ typeof leg.rewardDptfId === "string");
39
+ }
40
+ /**
41
+ * Drives one `mode:'planner'` step registered under `ouronet.aqp-evict`:
42
+ *
43
+ * 1. Parse `fvtId`/`patronAccount` from `step.planner_params_json`.
44
+ * 2. Derive `executor = k:<the step's own first signer's publicKey>`.
45
+ * 3-4. Read the plan (`URHC_BuildEvictPlans`) via a simulate; a failed READ
46
+ * is never "needs splitting" — there is no plan to split.
47
+ * 5-6. Zero plan entries → `[]` (handleReplanStep treats this as a cleared
48
+ * barrier — see design.md §C).
49
+ * 7-8. Probe `CC_FullEvictRewards` as one candidate leg; a successful
50
+ * simulate → exactly that one leg.
51
+ * 9. A failed probe is "needs splitting" ONLY when `runSimulate`'s own
52
+ * `gasUsed > ceiling` refuse-unmineable branch produced it (signaled by a
53
+ * numeric `gasUsed` on the `ok:false` result) — any OTHER failure
54
+ * rethrows as a genuine error, never silently treated as "needs
55
+ * splitting".
56
+ * 10. Fan out: one `CC_EvictSingleReward` leg per plan entry.
57
+ */
58
+ export const evictPlanner = async (step, ctx) => {
59
+ const params = parseJson(step.planner_params_json, {});
60
+ if (typeof params.fvtId !== "string" || typeof params.patronAccount !== "string") {
61
+ throw new Error("ouronet.aqp-evict: step.planner_params_json must have fvtId and patronAccount strings");
62
+ }
63
+ const { fvtId, patronAccount } = params;
64
+ const signers = parseJson(step.signers_json, []);
65
+ if (signers.length === 0) {
66
+ throw new Error("ouronet.aqp-evict: step.signers_json must have at least one signer (used as the executor)");
67
+ }
68
+ const executor = `k:${signers[0].publicKey}`;
69
+ const config = parseJson(step.config_json, {});
70
+ const gasPayer = parseJson(step.gas_payer_json, { type: "gas-station" });
71
+ const executorCtx = { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config };
72
+ // `ouronet-ns.AQP-EVCT` — the module's REAL, deployed, namespaced path
73
+ // (confirmed against the ported source's own `fvtChain.ts` NS/EVCT
74
+ // constants and its `(namespace "ouronet-ns")` on-chain declaration; a
75
+ // bare `AQP-EVCT.*` reference is unresolvable by Pact's namespace
76
+ // mechanism). Built from `ctx.runtime.namespace`, never hardcoded, so a
77
+ // consumer on a different namespace isn't silently wrong.
78
+ const evct = `${ctx.runtime.namespace}.AQP-EVCT`;
79
+ // Every value below flows through `payload` (env-data, `addData` per
80
+ // `executor.ts`'s `buildTransaction`) and is read back with
81
+ // `read-string`/`read-integer` in `pactCode` — NEVER string-concatenated
82
+ // into the Pact source itself, mirroring `pure/runtime-args.ts`'s own
83
+ // "no code-injection surface" guarantee. This matters most for
84
+ // `beneficiary`/`scoreEntityId`/`rewardDptfId`/`scoreEntityType` below,
85
+ // which come from a LIVE CHAIN READ (`URHC_BuildEvictPlans`'s response),
86
+ // not from operator-configured `planner_params_json` — nothing in this
87
+ // codebase or (per the ported source's own caveat) the `AQP-EVCT`
88
+ // contract guarantees those fields can't contain `"`/`(`/`)`.
89
+ const probeDefinition = {
90
+ pactCode: `(${evct}.URHC_BuildEvictPlans (read-string "fvt-id"))`,
91
+ config,
92
+ payload: { "fvt-id": fvtId },
93
+ gasPayer,
94
+ signers,
95
+ };
96
+ const result = await executeCodexTransaction(probeDefinition, "simulate", executorCtx);
97
+ if (!result.ok) {
98
+ throw new Error(result.error ?? "evict plan read failed");
99
+ }
100
+ const data = result.rawResult?.data;
101
+ if (!Array.isArray(data)) {
102
+ throw new Error("ouronet.aqp-evict: URHC_BuildEvictPlans returned a non-array result");
103
+ }
104
+ if (!data.every(isWellFormedEvictLeg)) {
105
+ throw new Error("ouronet.aqp-evict: URHC_BuildEvictPlans returned a malformed plan entry (expected string beneficiary/scoreEntityId/rewardDptfId and an integer scoreEntityType)");
106
+ }
107
+ const legs = data;
108
+ if (legs.length === 0) {
109
+ return [];
110
+ }
111
+ const fullLeg = {
112
+ pactCode: `(${evct}.CC_FullEvictRewards (read-string "patron") (read-string "executor") (read-string "fvt-id"))`,
113
+ config,
114
+ payload: { patron: patronAccount, executor, "fvt-id": fvtId },
115
+ gasPayer,
116
+ signers,
117
+ };
118
+ const fullResult = await executeCodexTransaction(fullLeg, "simulate", executorCtx);
119
+ if (fullResult.ok) {
120
+ return [fullLeg];
121
+ }
122
+ if (typeof fullResult.gasUsed !== "number") {
123
+ // A genuine chain-level/Pact-execution failure — never interpreted as
124
+ // "needs splitting" (see the module doc's step 9 above).
125
+ throw new Error(fullResult.error ?? "CC_FullEvictRewards simulation failed");
126
+ }
127
+ return legs.map((leg) => ({
128
+ pactCode: `(${evct}.CC_EvictSingleReward (read-string "patron") (read-string "executor") (read-string "fvt-id") (read-string "beneficiary") (read-integer "score-entity-type") (read-string "score-entity-id") (read-string "reward-dptf-id"))`,
129
+ config,
130
+ payload: {
131
+ patron: patronAccount,
132
+ executor,
133
+ "fvt-id": fvtId,
134
+ beneficiary: leg.beneficiary,
135
+ "score-entity-type": leg.scoreEntityType,
136
+ "score-entity-id": leg.scoreEntityId,
137
+ "reward-dptf-id": leg.rewardDptfId,
138
+ },
139
+ gasPayer,
140
+ signers,
141
+ }));
142
+ };
143
+ registerStepPlanner("ouronet.aqp-evict", evictPlanner);