@ancientpantheon/khronoton-core 0.13.0 → 0.15.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 +31 -0
  2. package/README.md +8 -0
  3. package/dist/{chunk-IAK4UEAA.js → chunk-24THBKR7.js} +188 -28
  4. package/dist/{chunk-7H5TM3CS.js → chunk-VPVEIDNN.js} +1 -1
  5. package/dist/{context-P-rCtBbJ.d.ts → context-ec4m0UBZ.d.ts} +1 -1
  6. package/dist/handlers/execute.js +28 -41
  7. package/dist/handlers/steps.js +51 -14
  8. package/dist/hooks/index.d.ts +3 -3
  9. package/dist/hooks/index.js +2 -2
  10. package/dist/provider/index.d.ts +3 -3
  11. package/dist/provider/index.js +93 -45
  12. package/dist/server/fire-and-record.d.ts +47 -0
  13. package/dist/server/fire-and-record.js +85 -0
  14. package/dist/server/index.d.ts +1 -0
  15. package/dist/server/index.js +9 -0
  16. package/dist/server/planners/registry.d.ts +41 -3
  17. package/dist/server/planners/registry.js +49 -5
  18. package/dist/server/planners/stoa-wrap.d.ts +11 -7
  19. package/dist/server/planners/stoa-wrap.js +61 -33
  20. package/dist/server/pure/yields.d.ts +57 -0
  21. package/dist/server/pure/yields.js +101 -0
  22. package/dist/server/resolvers.js +7 -1
  23. package/dist/server/runs-driver.js +89 -18
  24. package/dist/server/schema.d.ts +4 -3
  25. package/dist/server/schema.js +26 -1
  26. package/dist/server/single-tx.d.ts +44 -0
  27. package/dist/server/single-tx.js +143 -0
  28. package/dist/server/store/cronoton.d.ts +21 -0
  29. package/dist/server/store/cronoton.js +72 -5
  30. package/dist/server/store/index.d.ts +2 -1
  31. package/dist/server/store/index.js +3 -1
  32. package/dist/server/store/steps.d.ts +12 -0
  33. package/dist/server/store/steps.js +26 -3
  34. package/dist/server/store/yields.d.ts +46 -0
  35. package/dist/server/store/yields.js +73 -0
  36. package/dist/server/tick.js +38 -0
  37. package/dist/server/types.d.ts +31 -0
  38. package/dist/{types-uYSglFrJ.d.ts → types-DH7Ym8FQ.d.ts} +17 -0
  39. package/dist/ui/index.d.ts +1 -1
  40. package/dist/ui/index.js +2 -2
  41. package/package.json +1 -1
@@ -23,7 +23,9 @@
23
23
  */
24
24
  import { json, err } from "./http.js";
25
25
  import { withConfirm } from "./context.js";
26
- import { executeCodexTransaction, fireByServerResolver, getServerResolver, resolveServerVars, getCodexCronoton, recordFire, recoverFire as recoverFireInStore, applyTerminalIntent, rowToDefinition, rowRuntimeArgKeys, computeDefinitionFingerprint, validateRuntimeArgs, applyRuntimeArgs, listStepsForCronoton, createRun, getRun, driveRunOnce, defaultOnAudit, RunAlreadyInFlightError, } from "../server/index.js";
26
+ import { executeCodexTransaction, getServerResolver, resolveServerVars, getCodexCronoton, recoverFire as recoverFireInStore, rowToDefinition, rowRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, listStepsForCronoton, createRun, getRun, driveRunOnce, defaultOnAudit, RunAlreadyInFlightError, } from "../server/index.js";
27
+ import { attemptSingleTxFirst } from "../server/single-tx.js";
28
+ import { fireAndRecord as sharedFireAndRecord } from "../server/fire-and-record.js";
27
29
  /** A landed on-chain request key: 40–48 URL-safe base64 chars. */
28
30
  const REQUEST_KEY_RE = /^[A-Za-z0-9_-]{40,48}$/;
29
31
  /** Terminal statuses cannot be fired on demand (their single/spent attempt is done). */
@@ -53,48 +55,14 @@ function chainDataFrom(rawResult) {
53
55
  }
54
56
  /**
55
57
  * Fire a loaded row inline through the shared dispatcher, record exactly one
56
- * fire row (success or failure), and apply the one-time terminal transition —
57
- * the same fire → record → finalize path the tick runs, minus the pre-fire
58
- * claim (an on-demand fire has no scheduler race to guard against).
58
+ * fire row, and apply the one-time terminal transition. A thin wrapper over
59
+ * the shared `fireAndRecord` (`server/fire-and-record.ts`) that only pins
60
+ * this handler's own `actor: "ancient"` audit-detail field — a review
61
+ * finding caught this handler and `single-tx.ts` each independently
62
+ * re-deriving the identical fire→record→finalize sequence by hand.
59
63
  */
60
64
  async function fireAndRecord(ctx, row, definition) {
61
- const result = await fireByServerResolver(definition, row, {
62
- runtime: ctx.runtime,
63
- resolver: ctx.resolver,
64
- config: ctx.config,
65
- db: ctx.db,
66
- });
67
- const fingerprint = computeDefinitionFingerprint(row);
68
- const fireId = recordFire({
69
- codexCronotonId: row.id,
70
- jobId: null,
71
- firedAt: new Date().toISOString(),
72
- status: result.ok ? "success" : "failure",
73
- requestKey: result.requestKey,
74
- chainId: result.chainId,
75
- errorMessage: result.error,
76
- chainResponse: result.rawResult,
77
- definitionFingerprint: fingerprint,
78
- }, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
79
- if ((definition.scheduleKind ?? "recurring") === "one-time") {
80
- applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
81
- }
82
- await ctx.onAudit?.({
83
- action: result.ok ? "codex_cronoton.fire" : "codex_cronoton.fire_failed",
84
- result: result.ok ? "success" : "failure",
85
- targetKind: "codex_cronoton",
86
- targetId: row.id,
87
- detail: {
88
- codexCronotonId: row.id,
89
- fireId,
90
- requestKey: result.requestKey,
91
- chainId: result.chainId,
92
- actor: "ancient",
93
- definitionFingerprint: fingerprint,
94
- errorMessage: result.error,
95
- },
96
- });
97
- return { result, fireId };
65
+ return sharedFireAndRecord(ctx, row, definition, { auditDetailExtra: { actor: "ancient" } });
98
66
  }
99
67
  /**
100
68
  * Preview a transaction WITHOUT submitting. Returns the full simulate union
@@ -164,6 +132,25 @@ export const executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
164
132
  if (TERMINAL_STATUSES.has(row.status)) {
165
133
  return err(400, "cannot execute a terminal cronoton");
166
134
  }
135
+ // Ahead of the chained/plain decision below: an opt-in single-tx-first row
136
+ // (docs/work/khronoton-single-tx-custom) gets one more decision first — fire
137
+ // the row's own top-level definition inline when it fits under the gas
138
+ // ceiling, falling through to the existing chained/plain path unchanged
139
+ // when it's specifically gas-refused (or when the flag is off at all).
140
+ // `ctx` (a `HandlerContext`) already satisfies `SingleTxAttemptCtx`
141
+ // structurally with no adaptation needed — a review finding caught this
142
+ // call site hand-rebuilding an equivalent object instead of passing `ctx`
143
+ // straight through, the idiom every other `attemptSingleTxFirst`/
144
+ // `fireByServerResolver` call site in this feature already uses.
145
+ const attempt = await attemptSingleTxFirst(row, ctx, { auditDetailExtra: { actor: "ancient" } });
146
+ if (attempt.fired) {
147
+ return json(200, {
148
+ ok: attempt.result.ok,
149
+ fireId: attempt.fireId,
150
+ requestKey: attempt.result.requestKey,
151
+ error: attempt.result.error,
152
+ });
153
+ }
167
154
  const steps = listStepsForCronoton(row.id, { db: ctx.db });
168
155
  if (steps.length > 0) {
169
156
  try {
@@ -17,7 +17,9 @@
17
17
  */
18
18
  import { json, err } from "./http.js";
19
19
  import { withConfirm } from "./context.js";
20
- import { getCodexCronoton, listStepsForCronoton, resolvePlannerFor, stepRowToDefinition, executeCodexTransaction, } from "../server/index.js";
20
+ import { getCodexCronoton, getStepByIndex, resolvePlannerFor, stepRowToDefinition, executeCodexTransaction, } from "../server/index.js";
21
+ import { resolveSingleStepPayload, YieldNotFoundError } from "../server/pure/yields.js";
22
+ import { normalizePlannerResult } from "../server/planners/registry.js";
21
23
  /** Terminal statuses cannot be fired on demand — same set `execute.ts`'s
22
24
  * `executeNow`/`triggerCronoton` already enforce, duplicated locally per
23
25
  * this codebase's own per-module-small-constant convention (`parseJson`,
@@ -27,18 +29,53 @@ const TERMINAL_STATUSES = new Set(["completed", "error"]);
27
29
  /** Resolve the leg(s) a stored step currently produces, via the SAME shared
28
30
  * `resolvePlannerFor` helper `runs-driver.ts`'s `handleReplanStep` uses —
29
31
  * not a parallel reimplementation, so the two call sites can never drift.
30
- * Returns `{ok:false}` for a planner-mode step whose `planner_name` has no
31
- * registered `StepPlanner`, matching `findStep`'s own `{ok,...}` result
32
- * convention rather than a one-off sentinel. */
32
+ * Returns a DISCRIMINATED failure reason rather than a bare `{ok:false}` —
33
+ * a real review finding caught that collapsing "planner not registered"
34
+ * and "unresolved $yield reference" into the same untagged shape made
35
+ * every caller report a misleading `planner 'null' is not registered`
36
+ * message for a `mode:'single'` step (whose `planner_name` is always
37
+ * `null`) that actually failed on a yield reference, not a planner lookup.
38
+ *
39
+ * A standalone fire/simulate has no run, so no yield pool to resolve a
40
+ * `{"$yield": "<name>"}` reference against — every resolution here runs
41
+ * against an explicit empty pool (`docs/work/khronoton-step-yield-carry/
42
+ * design.md`'s "Consuming a yield"). A step that references a yield (e.g.
43
+ * authored for chained-run use, then fired standalone to preview it) always
44
+ * fails `YieldNotFoundError`; caught here and reported as its own reason,
45
+ * rather than letting it escape uncaught to the handler's generic 500
46
+ * catch-all or being folded into the unrelated planner-not-registered case. */
33
47
  async function resolveStepLegs(step, ctx) {
34
- if (step.mode === "single") {
35
- return { ok: true, legs: [stepRowToDefinition(step)] };
48
+ try {
49
+ if (step.mode === "single") {
50
+ // Same shared helper `runs-driver.ts`'s single-mode branch uses — not
51
+ // a parallel reimplementation (a review finding caught the two call
52
+ // sites independently re-deriving the identical sequence).
53
+ const resolvedStep = resolveSingleStepPayload(step, {});
54
+ return { ok: true, legs: [stepRowToDefinition(resolvedStep)] };
55
+ }
56
+ const resolved = resolvePlannerFor(step, ctx, {});
57
+ if (!resolved)
58
+ return { ok: false, reason: "planner-not-registered" };
59
+ const result = await resolved.planner(resolved.resolvedStep, resolved.plannerCtx);
60
+ // The standalone route has no run to persist a yield into, so
61
+ // `normalized.yield`, if present, is deliberately discarded here.
62
+ const normalized = normalizePlannerResult(result);
63
+ return { ok: true, legs: normalized.legs };
64
+ }
65
+ catch (error) {
66
+ if (error instanceof YieldNotFoundError) {
67
+ return { ok: false, reason: "yield-not-found", message: error.message };
68
+ }
69
+ throw error;
70
+ }
71
+ }
72
+ /** Shared 404 body for either `resolveStepLegs` failure reason, so
73
+ * `simulateStep`/`fireStep` never independently decide how to phrase it. */
74
+ function resolveStepLegsErrorResponse(step, resolved) {
75
+ if (resolved.reason === "yield-not-found") {
76
+ return err(404, `cannot resolve this step: ${resolved.message}`);
36
77
  }
37
- const resolved = resolvePlannerFor(step, ctx);
38
- if (!resolved)
39
- return { ok: false };
40
- const legs = await resolved.planner(step, resolved.plannerCtx);
41
- return { ok: true, legs };
78
+ return err(404, `planner '${step.planner_name}' is not registered`);
42
79
  }
43
80
  /** Shared step lookup: 404 on missing cronoton or missing step-at-index.
44
81
  * Returns the parent cronoton row too (not just the step) so `fireStep`
@@ -48,7 +85,7 @@ function findStep(ctx, cronotonId, index) {
48
85
  const row = getCodexCronoton(cronotonId, { db: ctx.db });
49
86
  if (!row)
50
87
  return { ok: false, response: err(404, "not found") };
51
- const step = listStepsForCronoton(cronotonId, { db: ctx.db }).find((s) => s.step_index === index);
88
+ const step = getStepByIndex(cronotonId, index, { db: ctx.db });
52
89
  if (!step)
53
90
  return { ok: false, response: err(404, "step not found at that index") };
54
91
  return { ok: true, row, step };
@@ -63,7 +100,7 @@ export const simulateStep = (ctx, req) => withConfirm(ctx, req, async () => {
63
100
  return found.response;
64
101
  const resolved = await resolveStepLegs(found.step, ctx);
65
102
  if (!resolved.ok) {
66
- return err(404, `planner '${found.step.planner_name}' is not registered`);
103
+ return resolveStepLegsErrorResponse(found.step, resolved);
67
104
  }
68
105
  const legs = resolved.legs;
69
106
  const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "simulate", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
@@ -98,7 +135,7 @@ export const fireStep = (ctx, req) => withConfirm(ctx, req, async () => {
98
135
  return err(400, "cannot execute a terminal cronoton");
99
136
  const resolved = await resolveStepLegs(found.step, ctx);
100
137
  if (!resolved.ok) {
101
- return err(404, `planner '${found.step.planner_name}' is not registered`);
138
+ return resolveStepLegsErrorResponse(found.step, resolved);
102
139
  }
103
140
  const legs = resolved.legs;
104
141
  const results = await Promise.all(legs.map((leg) => executeCodexTransaction(leg, "fire", { runtime: ctx.runtime, resolver: ctx.resolver, config: ctx.config })));
@@ -1,6 +1,6 @@
1
- import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-P-rCtBbJ.js';
2
- export { U as UseKhronotonResult, u as useKhronoton } from '../context-P-rCtBbJ.js';
3
- import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
1
+ import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-ec4m0UBZ.js';
2
+ export { U as UseKhronotonResult, u as useKhronoton } from '../context-ec4m0UBZ.js';
3
+ import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-DH7Ym8FQ.js';
4
4
  import 'react';
5
5
  import '../seams-Co8Tq4ka.js';
6
6
 
@@ -1,2 +1,2 @@
1
- export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-7H5TM3CS.js';
2
- export { useKhronoton } from '../chunk-IAK4UEAA.js';
1
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-VPVEIDNN.js';
2
+ export { useKhronoton } from '../chunk-24THBKR7.js';
@@ -1,8 +1,8 @@
1
1
  import { ReactNode } from 'react';
2
- import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-P-rCtBbJ.js';
3
- export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-P-rCtBbJ.js';
2
+ import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-ec4m0UBZ.js';
3
+ export { c as CancelBatchView, l as CodexSignerDescriptor, C as CommitBody, a as CommitView, m as ConfirmGate, n as ConfirmOpts, o as DEFAULT_EXPLORER_BASE, p as DEFAULT_PAGE_SIZE, q as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, r as FiresView, G as GetBatchView, s as GetCronotonView, t as KhronotonConfig, v as KhronotonSnapshot, L as ListCronotonsQuery, w as ListCronotonsView, e as RecoverView, x as RenderMultiTx, h as RuntimeArgs, y as ServerResolverOption, z as SignersView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, T as ToggleView, U as UseKhronotonResult, A as assertAdapter, B as emptySnapshot, u as useKhronoton } from '../context-ec4m0UBZ.js';
4
4
  import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-Co8Tq4ka.js';
5
- export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-uYSglFrJ.js';
5
+ export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-DH7Ym8FQ.js';
6
6
 
7
7
  /**
8
8
  * The per-request handler context + the injectable auth/confirm seam + the two
@@ -1,8 +1,86 @@
1
- import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, listStepsForCronoton, createRun, defaultOnAudit, driveRunOnce, getRun, RunAlreadyInFlightError, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-IAK4UEAA.js';
2
- export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-IAK4UEAA.js';
1
+ import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, listStepsForCronoton, createRun, defaultOnAudit, driveRunOnce, getRun, RunAlreadyInFlightError, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-24THBKR7.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-24THBKR7.js';
3
3
  import { useRef, useState, useEffect } from 'react';
4
4
  import { jsx } from 'react/jsx-runtime';
5
5
 
6
+ // src/server/fire-and-record.ts
7
+ async function recordAndFinalizeFire(result, ctx, row, definition, extras = {}) {
8
+ const fingerprint = computeDefinitionFingerprint(row);
9
+ const fireId = recordFire(
10
+ {
11
+ codexCronotonId: row.id,
12
+ jobId: null,
13
+ firedAt: (/* @__PURE__ */ new Date()).toISOString(),
14
+ status: result.ok ? "success" : "failure",
15
+ requestKey: result.requestKey,
16
+ chainId: result.chainId,
17
+ errorMessage: result.error,
18
+ chainResponse: result.rawResult,
19
+ definitionFingerprint: fingerprint
20
+ },
21
+ { db: ctx.db, resolveFireMode: ctx.resolveFireMode }
22
+ );
23
+ if ((definition.scheduleKind ?? "recurring") === "one-time") {
24
+ applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
25
+ }
26
+ const { success, failure } = extras.auditAction ?? {
27
+ success: "codex_cronoton.fire",
28
+ failure: "codex_cronoton.fire_failed"
29
+ };
30
+ await ctx.onAudit?.({
31
+ action: result.ok ? success : failure,
32
+ result: result.ok ? "success" : "failure",
33
+ targetKind: "codex_cronoton",
34
+ targetId: row.id,
35
+ detail: {
36
+ codexCronotonId: row.id,
37
+ fireId,
38
+ requestKey: result.requestKey,
39
+ chainId: result.chainId,
40
+ definitionFingerprint: fingerprint,
41
+ errorMessage: result.error,
42
+ ...extras.auditDetailExtra
43
+ }
44
+ });
45
+ return { result, fireId };
46
+ }
47
+ async function fireAndRecord(ctx, row, definition, extras = {}) {
48
+ const result = await fireByServerResolver(definition, row, ctx);
49
+ return recordAndFinalizeFire(result, ctx, row, definition, extras);
50
+ }
51
+
52
+ // src/server/single-tx.ts
53
+ var SINGLE_TX_AUDIT_ACTION = {
54
+ success: "codex_cronoton.single_tx.fire",
55
+ failure: "codex_cronoton.single_tx.fire_failed"
56
+ };
57
+ async function attemptSingleTxFirst(row, ctx, extras = {}) {
58
+ if (!row.try_single_tx_first) return { fired: false };
59
+ if (row.server_resolver && getServerResolver(row.server_resolver)?.kind === "multi-tx") {
60
+ return { fired: false };
61
+ }
62
+ const definition = rowToDefinition(row);
63
+ const sim = await executeCodexTransaction(definition, "simulate", {
64
+ runtime: ctx.runtime,
65
+ resolver: ctx.resolver,
66
+ config: ctx.config
67
+ });
68
+ if (!sim.ok) {
69
+ if (typeof sim.gasUsed === "number") {
70
+ return { fired: false };
71
+ }
72
+ throw new Error(sim.error ?? "single-tx simulate failed");
73
+ }
74
+ const result = await fireByServerResolver(definition, row, ctx);
75
+ if (result.postponed) {
76
+ return { fired: false };
77
+ }
78
+ const { fireId } = await recordAndFinalizeFire(result, ctx, row, definition, {
79
+ auditAction: SINGLE_TX_AUDIT_ACTION,
80
+ auditDetailExtra: extras.auditDetailExtra
81
+ });
82
+ return { fired: true, result, fireId };
83
+ }
6
84
  function KhronotonProvider(props) {
7
85
  const { children } = props;
8
86
  const staticRef = useRef(null);
@@ -381,47 +459,8 @@ function chainDataFrom(rawResult) {
381
459
  }
382
460
  return void 0;
383
461
  }
384
- async function fireAndRecord(ctx, row, definition) {
385
- const result = await fireByServerResolver(definition, row, {
386
- runtime: ctx.runtime,
387
- resolver: ctx.resolver,
388
- config: ctx.config,
389
- db: ctx.db
390
- });
391
- const fingerprint = computeDefinitionFingerprint(row);
392
- const fireId = recordFire(
393
- {
394
- codexCronotonId: row.id,
395
- jobId: null,
396
- firedAt: (/* @__PURE__ */ new Date()).toISOString(),
397
- status: result.ok ? "success" : "failure",
398
- requestKey: result.requestKey,
399
- chainId: result.chainId,
400
- errorMessage: result.error,
401
- chainResponse: result.rawResult,
402
- definitionFingerprint: fingerprint
403
- },
404
- { db: ctx.db, resolveFireMode: ctx.resolveFireMode }
405
- );
406
- if ((definition.scheduleKind ?? "recurring") === "one-time") {
407
- applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
408
- }
409
- await ctx.onAudit?.({
410
- action: result.ok ? "codex_cronoton.fire" : "codex_cronoton.fire_failed",
411
- result: result.ok ? "success" : "failure",
412
- targetKind: "codex_cronoton",
413
- targetId: row.id,
414
- detail: {
415
- codexCronotonId: row.id,
416
- fireId,
417
- requestKey: result.requestKey,
418
- chainId: result.chainId,
419
- actor: "ancient",
420
- definitionFingerprint: fingerprint,
421
- errorMessage: result.error
422
- }
423
- });
424
- return { result, fireId };
462
+ async function fireAndRecord2(ctx, row, definition) {
463
+ return fireAndRecord(ctx, row, definition, { auditDetailExtra: { actor: "ancient" } });
425
464
  }
426
465
  var simulateCodexTx = (ctx, req) => withConfirm(ctx, req, async () => {
427
466
  const body = req.body ?? {};
@@ -467,6 +506,15 @@ var executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
467
506
  if (TERMINAL_STATUSES.has(row.status)) {
468
507
  return err(400, "cannot execute a terminal cronoton");
469
508
  }
509
+ const attempt = await attemptSingleTxFirst(row, ctx, { auditDetailExtra: { actor: "ancient" } });
510
+ if (attempt.fired) {
511
+ return json(200, {
512
+ ok: attempt.result.ok,
513
+ fireId: attempt.fireId,
514
+ requestKey: attempt.result.requestKey,
515
+ error: attempt.result.error
516
+ });
517
+ }
470
518
  const steps = listStepsForCronoton(row.id, { db: ctx.db });
471
519
  if (steps.length > 0) {
472
520
  try {
@@ -502,7 +550,7 @@ var executeNow = (ctx, req) => withConfirm(ctx, req, async () => {
502
550
  if (resolverName && getServerResolver(resolverName)?.kind === "multi-tx") {
503
551
  return json(202, { ok: true, queued: true });
504
552
  }
505
- const { result, fireId } = await fireAndRecord(ctx, row, rowToDefinition(row));
553
+ const { result, fireId } = await fireAndRecord2(ctx, row, rowToDefinition(row));
506
554
  return json(200, {
507
555
  ok: result.ok,
508
556
  fireId,
@@ -523,7 +571,7 @@ var triggerCronoton = (ctx, req) => withConfirm(ctx, req, async () => {
523
571
  const validated = validateRuntimeArgs(rowRuntimeArgKeys(row), args);
524
572
  if (!validated.ok) return err(400, validated.error);
525
573
  const definition = applyRuntimeArgs(rowToDefinition(row), validated.args);
526
- const { result, fireId } = await fireAndRecord(ctx, row, definition);
574
+ const { result, fireId } = await fireAndRecord2(ctx, row, definition);
527
575
  return json(200, {
528
576
  ok: result.ok,
529
577
  fireId,
@@ -0,0 +1,47 @@
1
+ import type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode } from "./seams.js";
2
+ import type { CodexCronotonRow, CodexTxDefinition, FireResult } from "./types.js";
3
+ /**
4
+ * The injected context this function runs against — a structural subset
5
+ * `HandlerContext`/`RunsDriverCtx`/`SingleTxAttemptCtx` all already satisfy,
6
+ * so every existing caller passes its own `ctx` straight through with no
7
+ * adaptation.
8
+ */
9
+ export interface FireAndRecordCtx {
10
+ db: Database;
11
+ runtime: ChainRuntime;
12
+ resolver: KeyResolver;
13
+ config?: Partial<Config>;
14
+ resolveFireMode?: ResolveFireMode;
15
+ onAudit?: OnAudit;
16
+ }
17
+ export interface FireAndRecordExtras {
18
+ /** Audit action-name pair; defaults to the ordinary one-shot fire names
19
+ * (`codex_cronoton.fire`/`.fire_failed`) every pre-existing caller relies on. */
20
+ auditAction?: {
21
+ success: string;
22
+ failure: string;
23
+ };
24
+ /** Extra fields merged into the audit event's `detail` (e.g. `actor`). */
25
+ auditDetailExtra?: Record<string, unknown>;
26
+ }
27
+ /**
28
+ * Record exactly one fire row for an ALREADY-obtained `result`, apply the
29
+ * one-time terminal transition, and audit — the record+finalize+audit half
30
+ * of the sequence, shared by both {@link fireAndRecord} and any caller (like
31
+ * `single-tx.ts`) that needs to inspect `result` itself before reaching
32
+ * this point.
33
+ */
34
+ export declare function recordAndFinalizeFire(result: FireResult, ctx: FireAndRecordCtx, row: CodexCronotonRow, definition: CodexTxDefinition, extras?: FireAndRecordExtras): Promise<{
35
+ result: FireResult;
36
+ fireId: string;
37
+ }>;
38
+ /**
39
+ * Fire `definition` for `row` through the shared dispatcher, then record +
40
+ * finalize + audit via {@link recordAndFinalizeFire}. The convenience
41
+ * all-in-one entry point for every caller that doesn't need to inspect the
42
+ * `FireResult` before deciding whether to record it.
43
+ */
44
+ export declare function fireAndRecord(ctx: FireAndRecordCtx, row: CodexCronotonRow, definition: CodexTxDefinition, extras?: FireAndRecordExtras): Promise<{
45
+ result: FireResult;
46
+ fireId: string;
47
+ }>;
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The shared fire -> record -> finalize -> audit sequence for firing a
3
+ * loaded cronoton row's own definition inline through the dispatcher — "fire
4
+ * one transaction, write exactly one fire row, apply the one-time terminal
5
+ * transition." `handlers/execute.ts`'s on-demand fire (`executeNow`/
6
+ * `triggerCronoton`) and `single-tx.ts`'s single-tx-first attempt both need
7
+ * this identically.
8
+ *
9
+ * A review finding caught the two independently re-deriving this exact
10
+ * sequence by hand (`single-tx.ts`'s own module doc used to admit as much).
11
+ * A third, pre-existing, MORE divergent inline copy already lived in
12
+ * `tick.ts` before this feature (it also collects `txKeys` for the
13
+ * scheduler's multi-tx dispatch path and carries a few extra audit-detail
14
+ * fields) — deliberately left alone here: unifying that one too is a larger,
15
+ * separate refactor the finding that prompted this extraction never asked
16
+ * for.
17
+ *
18
+ * Split into two layers rather than one all-in-one function: `single-tx.ts`
19
+ * needs to inspect the fire `FireResult` itself (specifically
20
+ * `result.postponed` — see that field's own doc comment) BEFORE deciding
21
+ * whether to record/finalize/audit anything at all, so it cannot call an
22
+ * all-in-one "fire-then-record" helper. {@link recordAndFinalizeFire} is the
23
+ * shared record+finalize+audit half, taking an ALREADY-obtained result;
24
+ * {@link fireAndRecord} is the full convenience (fire, then delegate to
25
+ * {@link recordAndFinalizeFire}) for the common case that needs no
26
+ * interception between the two.
27
+ */
28
+ import { fireByServerResolver } from "./resolvers.js";
29
+ import { recordFire } from "./store/fires.js";
30
+ import { applyTerminalIntent } from "./store/claim.js";
31
+ import { computeDefinitionFingerprint } from "./pure/fingerprint.js";
32
+ /**
33
+ * Record exactly one fire row for an ALREADY-obtained `result`, apply the
34
+ * one-time terminal transition, and audit — the record+finalize+audit half
35
+ * of the sequence, shared by both {@link fireAndRecord} and any caller (like
36
+ * `single-tx.ts`) that needs to inspect `result` itself before reaching
37
+ * this point.
38
+ */
39
+ export async function recordAndFinalizeFire(result, ctx, row, definition, extras = {}) {
40
+ const fingerprint = computeDefinitionFingerprint(row);
41
+ const fireId = recordFire({
42
+ codexCronotonId: row.id,
43
+ jobId: null,
44
+ firedAt: new Date().toISOString(),
45
+ status: result.ok ? "success" : "failure",
46
+ requestKey: result.requestKey,
47
+ chainId: result.chainId,
48
+ errorMessage: result.error,
49
+ chainResponse: result.rawResult,
50
+ definitionFingerprint: fingerprint,
51
+ }, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
52
+ if ((definition.scheduleKind ?? "recurring") === "one-time") {
53
+ applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
54
+ }
55
+ const { success, failure } = extras.auditAction ?? {
56
+ success: "codex_cronoton.fire",
57
+ failure: "codex_cronoton.fire_failed",
58
+ };
59
+ await ctx.onAudit?.({
60
+ action: result.ok ? success : failure,
61
+ result: result.ok ? "success" : "failure",
62
+ targetKind: "codex_cronoton",
63
+ targetId: row.id,
64
+ detail: {
65
+ codexCronotonId: row.id,
66
+ fireId,
67
+ requestKey: result.requestKey,
68
+ chainId: result.chainId,
69
+ definitionFingerprint: fingerprint,
70
+ errorMessage: result.error,
71
+ ...extras.auditDetailExtra,
72
+ },
73
+ });
74
+ return { result, fireId };
75
+ }
76
+ /**
77
+ * Fire `definition` for `row` through the shared dispatcher, then record +
78
+ * finalize + audit via {@link recordAndFinalizeFire}. The convenience
79
+ * all-in-one entry point for every caller that doesn't need to inspect the
80
+ * `FireResult` before deciding whether to record it.
81
+ */
82
+ export async function fireAndRecord(ctx, row, definition, extras = {}) {
83
+ const result = await fireByServerResolver(definition, row, ctx);
84
+ return recordAndFinalizeFire(result, ctx, row, definition, extras);
85
+ }
@@ -18,6 +18,7 @@ export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgK
18
18
  export type { RuntimeArgs, ValidateRuntimeArgsResult } from "./pure/runtime-args.js";
19
19
  export { advanceRun } from "./pure/run-advance.js";
20
20
  export type { StepMode, RunState, LegState, RunPolicy, RunAction } from "./pure/run-advance.js";
21
+ export { YieldNotFoundError } from "./pure/yields.js";
21
22
  export { installSchema } from "./schema.js";
22
23
  export type { ScheduleMode, ScheduleConfig } from "../schedule.js";
23
24
  export { executeCodexTransaction } from "./executor.js";
@@ -20,6 +20,15 @@ export { defaultOnAudit, defaultResolveFireMode, TICK_INTERVAL_MS, LISTEN_TIMEOU
20
20
  export { parseCapabilityLine, computeTerminalIntent } from "./pure/capability.js";
21
21
  export { parseRuntimeArgKeys, validateRuntimeArgs, applyRuntimeArgs, runtimeArgKeysCollide, hashRuntimeArgs, } from "./pure/runtime-args.js";
22
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";
23
32
  // ── Consolidated schema installer (T1.6) ─────────────────────────────────────
24
33
  export { installSchema } from "./schema.js";
25
34
  // ── Headless executor (Phase 3: build/sign/simulate/fire behind the seams) ────
@@ -48,15 +48,40 @@ export interface PlannedLeg {
48
48
  * A step planner: given the step row + the injected seams, decides the legs
49
49
  * to build for the step's current pass. An empty array means "nothing to do
50
50
  * this pass" — `handleReplanStep` treats that like a cleared barrier.
51
+ *
52
+ * A planner may ALSO return `{ legs, yield? }` instead of a bare array, to
53
+ * additionally report a value for `runs-driver.ts` to store into the run's
54
+ * yield pool (`docs/work/khronoton-step-yield-carry/design.md`'s "Producing
55
+ * a yield") — see `normalizePlannerResult` below. The bare-array return
56
+ * stays valid forever; none of the 5 existing built-ins that don't produce a
57
+ * yield (`evict`/`inject`/`unstall`/`stoa-unwrap`) are forced to change.
58
+ * Deliberately a bare, unnamed `yield` value here — the NAME a yield is
59
+ * stored under always comes from the consuming step's own `step.yield_as`,
60
+ * decided by whoever wrote the step, never by the planner itself.
61
+ */
62
+ export type StepPlanner = (step: CodexCronotonStepRow, ctx: PlannerCtx) => Promise<PlannedLeg[] | {
63
+ legs: PlannedLeg[];
64
+ yield?: unknown;
65
+ }>;
66
+ /**
67
+ * Normalize a `StepPlanner`'s return value to the `{ legs, yield? }` shape
68
+ * regardless of which form the planner actually returned — the SINGLE
69
+ * shared normalizer `runs-driver.ts` and `handlers/steps.ts` both call, so
70
+ * neither hand-rolls its own array-vs-object check.
51
71
  */
52
- export type StepPlanner = (step: CodexCronotonStepRow, ctx: PlannerCtx) => Promise<PlannedLeg[]>;
72
+ export declare function normalizePlannerResult(result: Awaited<ReturnType<StepPlanner>>): {
73
+ legs: PlannedLeg[];
74
+ yield?: unknown;
75
+ };
53
76
  /**
54
77
  * Register (or replace) a named step planner. A module that owns a planner
55
78
  * calls this at module-eval time so the registry is populated by the time
56
79
  * `handleReplanStep` consults it.
57
80
  */
58
81
  export declare function registerStepPlanner(name: string, planner: StepPlanner): void;
59
- /** Read a registered step planner by name, or `undefined`. */
82
+ /** Read a registered step planner by name, or `undefined` — including for a
83
+ * name colliding with an `Object.prototype` member, since `STEP_PLANNERS` is
84
+ * prototype-less (see its own doc comment above). */
60
85
  export declare function getStepPlanner(name: string): StepPlanner | undefined;
61
86
  /**
62
87
  * Resolve a `mode:'planner'` step's registered planner AND build the
@@ -69,12 +94,25 @@ export declare function getStepPlanner(name: string): StepPlanner | undefined;
69
94
  * Returns `undefined` for an unregistered `planner_name` — callers decide
70
95
  * how to report that (a thrown `PlannerNotRegisteredError` for the real
71
96
  * driver, a 404 for the standalone-fire route).
97
+ *
98
+ * Also resolves any `{"$yield": "<name>"}` placeholder in the step's
99
+ * `planner_params_json` against `yieldPool` BEFORE a caller ever invokes the
100
+ * planner (`docs/work/khronoton-step-yield-carry/design.md`'s "Consuming a
101
+ * yield") — returned as a shallow-cloned `resolvedStep` with that field
102
+ * replaced by the resolved JSON string, so `ouronet.aqp-inject` and every
103
+ * other planner keep calling `parseJson(step.planner_params_json, {})`
104
+ * exactly as they do today and simply receive already-resolved values; zero
105
+ * planner-side changes needed. `yieldPool` defaults to `{}`, so every
106
+ * pre-Wave-3 call site (passing only `(step, seams)`) is unaffected — a step
107
+ * with no `$yield` references anywhere resolves byte-identical to before
108
+ * this parameter existed.
72
109
  */
73
110
  export declare function resolvePlannerFor(step: CodexCronotonStepRow, seams: {
74
111
  runtime: ChainRuntime;
75
112
  resolver: KeyResolver;
76
113
  config?: Partial<Config>;
77
- }): {
114
+ }, yieldPool?: Record<string, unknown>): {
78
115
  planner: StepPlanner;
79
116
  plannerCtx: PlannerCtx;
117
+ resolvedStep: CodexCronotonStepRow;
80
118
  } | undefined;