@ancientpantheon/khronoton-core 0.14.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.
- package/CHANGELOG.md +16 -0
- package/README.md +4 -0
- package/dist/{chunk-A5YODPKQ.js → chunk-24THBKR7.js} +66 -16
- package/dist/{chunk-WKI52IPY.js → chunk-VPVEIDNN.js} +1 -1
- package/dist/{context-P-rCtBbJ.d.ts → context-ec4m0UBZ.d.ts} +1 -1
- package/dist/handlers/execute.js +28 -41
- package/dist/hooks/index.d.ts +3 -3
- package/dist/hooks/index.js +2 -2
- package/dist/provider/index.d.ts +3 -3
- package/dist/provider/index.js +93 -45
- package/dist/server/fire-and-record.d.ts +47 -0
- package/dist/server/fire-and-record.js +85 -0
- package/dist/server/resolvers.js +7 -1
- package/dist/server/schema.js +9 -0
- package/dist/server/single-tx.d.ts +44 -0
- package/dist/server/single-tx.js +143 -0
- package/dist/server/store/cronoton.d.ts +21 -0
- package/dist/server/store/cronoton.js +72 -5
- package/dist/server/tick.js +38 -0
- package/dist/server/types.d.ts +31 -0
- package/dist/{types-uYSglFrJ.d.ts → types-DH7Ym8FQ.d.ts} +17 -0
- package/dist/ui/index.d.ts +1 -1
- package/dist/ui/index.js +2 -2
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,22 @@ All notable changes to `@ancientpantheon/khronoton-core`.
|
|
|
4
4
|
|
|
5
5
|
The engine's pre-extraction history lives in the AncientHoldings hub, whose inline scheduler ("Cronoton") this package extracts and generalises.
|
|
6
6
|
|
|
7
|
+
## 0.15.0 — 2026-11-21
|
|
8
|
+
|
|
9
|
+
**MINOR — a chained cronoton can now optionally try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically too expensive to mine.**
|
|
10
|
+
|
|
11
|
+
Every chained cronoton (0.13.0) always drove its work as N separate transactions, one per step, even for a chain cheap enough to easily fit in a single transaction with room to spare. There was no way to attempt a cheaper, faster single-transaction execution and fall back to the step-by-step chain only when genuinely needed. This release adds that as a new, opt-in decision — never mandatory, off by default — ahead of the existing chained/plain branch, implementing the `'custom'` mode (the sibling Default-mode topic, auto-composing the single-tx Pact code from the chain's own steps, stays explicitly deferred).
|
|
12
|
+
|
|
13
|
+
- **Two new `codex_cronotons` columns.** `try_single_tx_first INTEGER NOT NULL DEFAULT 0` and `single_tx_mode TEXT CHECK (single_tx_mode IN ('custom', 'default'))`, validated against the full allowed set (not just the literal `'default'`) at both commit and edit time — a raw out-of-enum string must never reach the SQL `CHECK` uncaught. When on, the row's own existing top-level `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/`signers_json` fields — already required, `NOT NULL`, and confirmed dead-weight placeholder data for any row that also has `codex_cronoton_steps` rows — are reinterpreted as the single-tx variant the operator hand-composes directly, exactly as for a plain one-shot cronoton. `editCodexCronoton` rejects enabling the flag on a zero-step row (nothing to fall back to) and now also requires `singleTxMode: 'custom'` to be set (or already persisted) whenever the flag is on, so the mode selector is never left meaningfully unset.
|
|
14
|
+
- **The decision, mirroring `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up.** At the exact point a chained row's work would normally begin (`tick.ts`'s due-row branch, `handlers/execute.ts`'s `executeNow` manual-trigger branch), a new shared `attemptSingleTxFirst` helper (`server/single-tx.ts`) simulates the row's own definition first: fits under the gas ceiling → fires it via the exact same plain one-shot path (`fireByServerResolver`/`recordFire`) a non-chained cronoton already uses, recorded as an ordinary fire row, the chained run/step machinery never touched; refused specifically for being too expensive (the executor's existing numeric-`gasUsed`-on-`{ok:false}` refuse-unmineable signal) → falls through to the existing chained-run path unchanged; any other simulate failure → propagates as a real error, never silently treated as "fall back to the chain"; fires but genuinely reverts for real → recorded as a failed fire, no chain retry in the same pass (Pact transactions are atomic — no partial state to recover from). A row bound to a registered **multi-tx** server resolver is refused by this decision before ever simulating or firing — inline-dispatching a multi-tx orchestrator would bypass `executeNow`'s own documented "never fire multi-tx inline" invariant (202-queued) on both the scheduler tick and the manual-trigger endpoint.
|
|
15
|
+
- **Shared fire-record-finalize-audit sequence, not a third hand-copy.** `handlers/execute.ts`'s own on-demand fire path and the new `attemptSingleTxFirst` both delegate to a new shared `server/fire-and-record.ts` (`recordAndFinalizeFire`/`fireAndRecord`) rather than each independently re-deriving the fire→record→finalize→audit sequence — split into two layers specifically because the single-tx path needs to inspect the `FireResult` (via the new `FireResult.postponed` field, set only by `resolvers.ts`'s own never-submitted-to-chain paths) before deciding whether to record anything at all, distinguishing a genuinely-never-submitted postpone from a real on-chain fire failure that would otherwise permanently orphan a one-time row. Both `tick.ts` and `handlers/execute.ts` thread an `actor` (`"scheduler"`/`"ancient"`) into the resulting `codex_cronoton.single_tx.fire`/`.fire_failed` audit event, matching every other fire path's own attribution.
|
|
16
|
+
- **The manual-batch "Execute Now ×N" rail now stops rather than bypasses the new guard.** `processDueManualBatchesOnce` fires a chained cronoton's raw top-level definition with no steps/single-tx awareness of its own; for a `try_single_tx_first=1` row this would have bypassed the gas-ceiling simulate-then-decide check entirely now that those fields are live operator code, not inert placeholder data. The batch is now auto-cancelled (mirroring the existing parent-inactive cancellation) rather than firing unchecked.
|
|
17
|
+
- Both existing gas-payer types (`type: "codex"` self-paid, `type: "gas-station"` sponsored) work for the single-tx attempt via the exact same executor/signer-planning path a plain one-shot cronoton already uses — no new gas-payer-specific code needed.
|
|
18
|
+
|
|
19
|
+
Reviewed via nectar across 6 rounds (correctness/conventions/security/tests lenses each round, adversarial validation throughout): **10 CONFIRMED findings fixed, 0 REFUTED, 1 left open as a harmless STYLISTIC nit** (an escaped-quote string literal instead of this file's usual backtick-template idiom). Standout findings: a **HIGH** in round 1 caught a server-resolver's "postponed, never submitted" fire result as structurally indistinguishable from a genuine on-chain failure, risking a permanently orphaned one-time row (fixed via the new `FireResult.postponed` field); a **HIGH** in round 2 caught `attemptSingleTxFirst` able to inline-dispatch a registered multi-tx orchestrator, bypassing `executeNow`'s own 202-queued invariant (fixed with an explicit kind guard); a **MEDIUM**-severity correctness finding in round 3 (initially flagged HIGH, narrowed on adversarial validation to the genuinely new risk only) caught the manual-batch rail's gas-ceiling bypass described above; a **MEDIUM** security finding in the same round caught single-tx fires carrying no `actor` attribution in their audit events, unlike every other fire path. Two findings were duplication/test-coverage gaps closed by extracting the shared `fire-and-record.ts` module and adding its own direct test file. Full history in `docs/work/khronoton-single-tx-custom/review.md`. Behavioral verification drove the real compiled `dist/` artifact through all three core decision-tree branches (off/fits/gas-refused) against a real in-memory DB and fake chain client, confirming each against design.md's acceptance criteria. Full design/plan/review in `docs/work/khronoton-single-tx-custom/` (Topic 1 of `docs/work/khronoton-single-tx-chain/design.md` — the sibling Default-mode topic stays deferred).
|
|
20
|
+
|
|
21
|
+
**1356 specs pass.**
|
|
22
|
+
|
|
7
23
|
## 0.14.0 — 2026-11-20
|
|
8
24
|
|
|
9
25
|
**MINOR — step-to-step yield carry: a chained run's steps can now hand a specific computed value forward to a later step, closing the one real gap 0.13.0's chained-runs feature shipped with.**
|
package/README.md
CHANGED
|
@@ -6,6 +6,8 @@ Khronoton is the "When do I act?" Constructor of the Pantheon architecture — t
|
|
|
6
6
|
|
|
7
7
|
## Status
|
|
8
8
|
|
|
9
|
+
**`0.15.0` on public npmjs** — **MINOR.** Released 2026-11-21. A chained cronoton can now optionally try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically too expensive to mine — never mandatory, off by default. New `try_single_tx_first`/`single_tx_mode` columns on `codex_cronotons`; when on, the row's own existing top-level `pact_code`/payload/config/gas-payer/signers fields (already-required, previously-dead-weight placeholder data for any row with steps) are reinterpreted as the operator's own hand-composed single-tx Pact code. A new shared `attemptSingleTxFirst` decision (`server/single-tx.ts`), consulted ahead of the existing chained/plain branch in both the scheduler tick and `executeNow`, mirrors `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up: fits under the gas ceiling → fires via the exact same plain one-shot path; refused specifically for being too expensive → falls through to the existing chain unchanged; any other simulate failure → a real error, never a silent fallback; fires but genuinely reverts → recorded as a failed fire, no chain retry (Pact transactions are atomic). A new shared `fire-and-record.ts` closes a hand-copy-triplication gap between `executeNow` and the new path. Reviewed via nectar across 6 rounds: a **HIGH** caught a server-resolver "postponed" result risking a permanently orphaned one-time row; a second **HIGH** caught the new decision able to inline-dispatch a registered multi-tx orchestrator, bypassing `executeNow`'s own 202-queued invariant; a **MEDIUM** caught the manual-batch "Execute Now ×N" rail bypassing the new gas-ceiling guard entirely for a single-tx-first row (now auto-cancelled instead); a second **MEDIUM** caught single-tx fires missing the `actor` audit attribution every other fire path records. **10 CONFIRMED findings fixed, 0 REFUTED.** **1356 specs pass.**
|
|
10
|
+
|
|
9
11
|
**`0.14.0` on public npmjs** — **MINOR.** Released 2026-11-20. Chained runs (0.13.0) can now carry a specific computed value from one step to a later one — a generic, flat, named-yield pool per run. Any step declares the name it produces a value under (`yield_as`); a `mode:'planner'` step's planner optionally returns `{ legs, yield }` instead of a bare array (zero changes forced on any existing planner); a `mode:'single'` step captures its confirmed leg's real on-chain return value. A later step references a prior yield with `{"$yield": "<name>"}` written directly into its own stored payload/params, resolved transparently before it executes — for planner-mode steps this means **zero code changes to any planner, built-in or custom** to consume a carried value. `ouronet.stoa-wrap` gained an `amountOverride` param to actually produce a usable yield. Reviewed via nectar across 4 rounds: two HIGH findings in round 1 (a confirmed leg with no on-chain `data` crashed yield capture after already being marked confirmed; the yield pool's `name in pool` check silently resolved a never-produced name like `"constructor"` to an inherited `Object.prototype` member instead of throwing) were fixed, and the identical prototype-chain gap was then found and fixed in the sibling `StepPlanner` registry (round 2) and a concurrent-attempt-double-bump race was found and fixed in the core driver (round 3), before round 4 came back fully clean. Behavioral verification drove the real `ouronet.stoa-wrap` → `ouronet.aqp-inject` chain against the actual compiled artifact, confirming inject's amount exactly matched wrap's actual used amount. **1317 specs pass.**
|
|
10
12
|
|
|
11
13
|
**`0.13.0` on public npmjs** — **MINOR.** Released 2026-11-20. A cronoton can now express a chained, multi-step workflow ("drain→wrap→inject→evict"-shaped) as one schedulable unit instead of being limited to a single one-shot transaction. Three new tables (`codex_cronoton_steps`/`codex_cronoton_runs`/`codex_cronoton_run_legs`) back a non-blocking driver (`runs-driver.ts`'s `driveRunOnce`/`advanceInFlightRunsOnce`, a third pass in `startKhronotonLoop`) built on a new non-blocking `"submit"` executor mode and a pure decision core (`pure/run-advance.ts`'s `advanceRun`) that decides submit/poll/advance/re-plan/fail purely from a run's and its legs' current state. A new `StepPlanner` registry ships five built-in planners ported from OuronetUI's real transaction-construction logic — `ouronet.aqp-evict`, `ouronet.aqp-inject`, `ouronet.aqp-unstall` (backed by a newly-ported generic gas-probe-and-pack algorithm, `pure/split-plan.ts`), `ouronet.stoa-wrap`, and `ouronet.stoa-unwrap` — every one of which builds Pact code with zero interpolated values in the executed code itself. New `executeNow` chained-row support, a widened `adaptMultiTxSummary`, a standalone per-step `POST .../steps/:index/{simulate,fire}` route, and new `GET /[id]/runs`/`GET /[id]/runs/[runId]/legs` read routes round out the observability surface. A plain one-shot cronoton's behavior is completely unchanged. Reviewed via nectar across all seven phases of this feature plus one additional cross-phase round after they shipped (33 rounds total, 73 CONFIRMED findings): four **CRITICAL** findings surfaced across the arc — a missing Pact module-namespace prefix and a Pact-code-injection vulnerability (both caught before ever shipping, in round 1 of the `ouronet.aqp-evict` planner's own review), a run-gets-permanently-stuck bug found only in a follow-up cross-phase pass (a planner throw on a run's first drive left it stranded forever with no recovery path), and a regression in that very fix (an overly broad catch that turned a benign concurrency race into a false permanent failure), caught by re-reviewing the fix itself. Multiple **HIGH** findings were also found and fixed, including a standalone-fire route that could bypass the paused/terminal guard every other fire route enforces, a genuine concurrency race in the core driver (fixed with a new claim-before-submit mechanism), and a read-tier handler leaking real transaction amounts and account identifiers. **1265 specs pass.**
|
|
@@ -360,6 +362,8 @@ npm install @ancientpantheon/khronoton-core
|
|
|
360
362
|
|
|
361
363
|
## Version history
|
|
362
364
|
|
|
365
|
+
**v0.15.0** — Single-tx-first Custom mode for chained cronotons. Every chained cronoton (0.13.0) always drove its work as N separate transactions, one per step, even for a chain cheap enough to easily fit in a single transaction. This release adds an opt-in, off-by-default decision to try a single-transaction variant first, falling back to the proven step-by-step chain only when that one transaction is specifically refused for being too expensive to mine — implementing only the `'custom'` branch (the sibling Default-mode topic, auto-composing the single-tx Pact code from the chain's own steps, stays explicitly deferred, blocked on a confirmed `TS01-C1.DPTF|C_Transmute` signature and a clean gasless-patron account identifier). **Schema.** Two new `codex_cronotons` columns: `try_single_tx_first INTEGER NOT NULL DEFAULT 0` and `single_tx_mode TEXT CHECK (single_tx_mode IN ('custom', 'default'))`, validated against the FULL allowed set (not just the literal `'default'`) at both commit and edit time in `store/cronoton.ts` — a raw out-of-enum string, possible at runtime since TypeScript's enum type is erased, must never reach the SQL `CHECK` uncaught. `editCodexCronoton` rejects enabling the flag on a zero-step row (nothing for it to ever fall back to) and — after a review finding caught the gap — now also requires the resolved `single_tx_mode` to be `'custom'` whenever the flag will be on, whether freshly patched or inherited from a prior edit, so the mode selector is never left meaningfully unset while the flag is live. When on, the row's own existing top-level `pact_code`/`payload_json`/`config_json`/`gas_payer_json`/`signers_json` fields (already required, `NOT NULL`, confirmed dead-weight placeholder data for any row that also has `codex_cronoton_steps` rows, since `tick.ts`'s chained-vs-plain branch never touches them once ≥1 step exists) are reinterpreted as the single-tx variant: the operator writes their own composed Pact code there directly, exactly as for a plain one-shot cronoton. **The decision (`server/single-tx.ts`'s new `attemptSingleTxFirst`), mirroring `ouronet.aqp-evict`'s own established try-then-fan-out precedent one level up.** Consulted at the exact point a chained row's work would normally begin — `tick.ts`'s due-row branch and `handlers/execute.ts`'s `executeNow` manual-trigger branch, both of which already decide "chained vs plain" on `steps.length > 0` — ahead of that existing decision, only when `try_single_tx_first` is on: (1) simulate the row's own definition via the existing `executeCodexTransaction(..., "simulate", ...)` seam; (2) fits under the gas ceiling → fire it via the exact same plain one-shot path (`fireByServerResolver`/`recordFire`) a non-chained cronoton already uses — the chained run/step machinery is never touched, the fire is recorded as an ordinary `codex_cronoton_fires` row; (3) refused specifically for being too expensive (a numeric `gasUsed` on an `{ok:false}` simulate result — the executor's own existing refuse-unmineable signal, the same one `ouronet.aqp-evict` already reads to decide "fan out instead") → fall through to the existing chained-run path, completely unchanged; (4) any other simulate failure (a genuine Pact error, unrelated to gas) → propagate as a real error, never silently treated as "fall back to the chain," mirroring `evict`'s own established discipline for the identical decision shape one level down; (5) the single-tx variant fires and then genuinely fails for real (a true on-chain revert, not a gas issue) → recorded as a failed fire exactly as a plain one-shot cronoton's failure is today, no fallback to the chain at this point — Pact transactions are atomic, so there's no partial state to recover from, and the underlying failure is a business-logic one the chained path would very likely hit too. A row bound to a registered **multi-tx** server resolver is refused by this decision before ever simulating or firing at all — `fireByServerResolver` awaits a multi-tx orchestrator's entire run inline, which is exactly what `executeNow`'s own plain-fire branch already refuses to do for every other row (202-queued, never fired inline); without this guard a `try_single_tx_first=1` row bound to one would have bypassed that invariant on both the scheduler tick and the manual-trigger endpoint, and lost the multi-tx `txKeys` breakdown besides. Both existing gas-payer types (`type: "codex"` self-paid, `type: "gas-station"` sponsored) work for the single-tx attempt via the identical executor/signer-planning path a plain one-shot cronoton already uses — no new gas-payer-specific code needed; the operator's own hand-written Pact code is responsible for satisfying whatever the gas station's capability actually requires. **A shared fire-record-finalize-audit sequence, not a third hand-copy.** `handlers/execute.ts`'s own on-demand fire path and `attemptSingleTxFirst` both delegate to a new shared `server/fire-and-record.ts` (`recordAndFinalizeFire`/`fireAndRecord`) — split into two layers specifically because the single-tx path needs to inspect the resulting `FireResult` (via a new `FireResult.postponed` field, set only by `resolvers.ts`'s own `postponed(...)` helper on its never-submitted-to-chain paths) *before* deciding whether to record anything at all, distinguishing a genuinely-never-submitted server-resolver postpone from a real on-chain fire failure — conflating the two would have permanently orphaned a one-time row (its `next_fire_at` already cleared by the claim, with no code path left to ever reselect it). Both `tick.ts` and `handlers/execute.ts` thread an `actor` (`"scheduler"`/`"ancient"` respectively) through to the resulting `codex_cronoton.single_tx.fire`/`.fire_failed` audit event, matching every other fire path's own attribution — a gap a review finding caught the new path missing entirely. **The manual-batch "Execute Now ×N" rail (`tick.ts`'s `processDueManualBatchesOnce`) now stops rather than bypasses the new guard.** That rail fires a chained cronoton's raw top-level definition directly with no steps/single-tx awareness of its own; for a `try_single_tx_first=1` row this would have bypassed the gas-ceiling simulate-then-decide check entirely now that those top-level fields are live operator-authored code rather than inert placeholder data — a genuinely new risk this topic's own reinterpretation of those fields introduces (the broader, pre-existing "manual batch ignores `codex_cronoton_steps` entirely" gap for an ORDINARY chained row predates this topic and is tracked separately). Fixed by auto-cancelling the batch, mirroring the rail's existing parent-inactive cancellation, rather than firing unchecked. Reviewed via nectar across 6 rounds (correctness/conventions/security/tests lenses each round, adversarial validation throughout): **10 CONFIRMED findings fixed, 0 REFUTED, 1 left open as a harmless STYLISTIC nit** (an escaped-quote string literal in one new error message instead of this file's usual backtick-template idiom for an embedded quote — zero functional impact, left for a future pass). Round 1 found and fixed a HIGH (the server-resolver postpone misclassification above) plus two MEDIUMs (the `fireAndRecord` triplication; the `singleTxMode` enum-validation gap checking only the literal `'default'`). Round 2's terminal pass caught the second HIGH (the multi-tx inline-dispatch bypass above) plus a MEDIUM-downgraded-to-LOW `SingleTxAttemptCtx`/`FireAndRecordCtx` duplication and two LOWs (`fire-and-record.ts` missing its own test file; a duplicated fire-dispatch options object plus a stale code comment). Round 3's terminal pass caught the manual-batch gas-ceiling bypass (initially flagged HIGH, narrowed on adversarial validation to MEDIUM once scoped to only the genuinely-new risk) plus a LOW (a stale hand-rebuilt ctx object in `execute.ts` instead of passing `ctx` straight through) and a MEDIUM security finding (the missing `actor` audit attribution). Round 4's terminal pass caught a MEDIUM-downgraded-to-LOW data-hygiene gap (enabling `trySingleTxFirst` without requiring `single_tx_mode` to resolve to `'custom'`, harmless today since no other value is reachable, but a trap once the deferred Default-mode topic needs to branch on it). Round 5's terminal pass caught the STYLISTIC nit above plus a genuine MEDIUM test-coverage gap (the new mode-inheritance guard's *success* path — a later edit flipping the flag on alone, relying on a previously-persisted `'custom'` value — was only ever exercised via its rejection branch, never its success branch). Round 6's terminal pass came back fully clean across all four lenses. Behavioral verification drove the real compiled `dist/` artifact — `@ancientpantheon/khronoton-core/server` resolved through the published package's own exports map, not source — through all three core decision-tree branches (`try_single_tx_first` off: byte-identical, exactly one preflight simulate call; fits: plain one-shot fire, zero run rows; gas-refused: falls through to a real driven chain reaching a real run row) against a real in-memory DB and a fake chain client at the system boundary, confirming each against design.md's acceptance criteria. Full design/plan/review in `docs/work/khronoton-single-tx-custom/` (Topic 1 of `docs/work/khronoton-single-tx-chain/design.md`). **1356 specs pass.**
|
|
366
|
+
|
|
363
367
|
**v0.14.0** — Step-to-step yield carry. 0.13.0's chained runs let each step either use a fixed baked-in value or re-probe live chain state at its own fire time — self-correcting planners like `ouronet.stoa-wrap` worked fine with this (wrap whatever balance currently sits in an account), but a drain→wrap→inject pipeline needs wrap and inject to both use the *exact* amount the previous step actually moved, since intermediate/target accounts can independently hold their own pre-existing balance. This release adds a generic, flat, named-yield pool per run, closing that gap without requiring every planner to become yield-aware. **Storage.** New `codex_cronoton_run_yields(run_id, name, value_json, step_index, created_at)` table, `UNIQUE(run_id, name)`, upserted via `ON CONFLICT ... DO UPDATE` (`store/yields.ts`'s `upsertYield`/`getYieldPool`) — a replanned step's freshest value always wins, no separate invalidation needed since nothing downstream of an unconfirmed step runs yet. New nullable `codex_cronoton_steps.yield_as` column, applying uniformly to both step modes — the step row itself always owns the yield's name, never the planner (avoiding a name-collision risk if a chain ever ran two wrap-shaped steps). **Producing a yield.** `StepPlanner`'s return type widened to `PlannedLeg[] | { legs: PlannedLeg[]; yield?: unknown }` (`planners/registry.ts`) — the bare-array return stays valid forever, so none of `evict`/`inject`/`unstall`/`stoa-unwrap` needed source changes. A `mode:'single'` step with `yield_as` set captures the confirmed leg's real on-chain return value (`ListenResult.result.data`, already flowing through `runs-driver.ts`'s `handlePoll` confirm loop, previously just discarded) under that name. `ouronet.stoa-wrap` is the one built-in that changed: a new optional `amountOverride` param skips its live `coin.get-balance` probe entirely when given (with its own zero-amount short-circuit, mirroring the probed path's `data === 0` → `[]`), and the planner now always returns `{ legs, yield: amount }` — the exact amount it used, whichever path produced it — instead of a bare array. **Consuming a yield.** A new pure helper (`pure/yields.ts`'s `resolveYieldRefs`) recursively walks a step's parsed `payload_json`/`planner_params_json`, substituting every `{"$yield": "<name>"}` placeholder against the run's pool. For `mode:'planner'` steps this resolution happens inside the widened `resolvePlannerFor` (now `resolvePlannerFor(step, seams, yieldPool = {})`), producing a shallow-cloned, already-resolved step row before the planner ever runs — `ouronet.aqp-inject` still just does `parseJson(step.planner_params_json, {})` and sees a concrete decimal string, with **zero code changes needed**. For `mode:'single'` steps, a shared `resolveSingleStepPayload` helper (extracted after a review finding caught `runs-driver.ts` and `handlers/steps.ts` each independently re-deriving the identical resolution sequence) does the equivalent for `payload_json`. An unresolvable reference throws `YieldNotFoundError` (a new public export, matching every other typed error this package throws) rather than silently resolving to `null` — propagating through the same `handleReplanStep` catch path `PlannerNotRegisteredError` already uses, terminalizing the run. The standalone per-step fire/simulate route (`handlers/steps.ts`) always resolves against an explicit empty pool — there is no run to source a yield from there, so a `$yield` reference fails loudly (caught and folded into the route's existing discriminated `{ok:false, reason}` result shape) instead of reaching the chain as a literal placeholder object. Reviewed via nectar across 4 rounds (correctness/conventions/security/tests/performance lenses, adversarial validation throughout): **12 CONFIRMED findings, 0 REFUTED, 2 validator-adjusted severity downgrades**. Round 1 found two HIGH findings — `upsertYield` crashing on a confirmed leg's `undefined` on-chain result (`JSON.stringify(undefined)` is not a bindable SQL value), thrown *after* `markLegConfirmed` had already committed, permanently stranding an otherwise-successful run (fixed: normalize `undefined` → `null`); and the yield pool's `name in pool` membership check walking the prototype chain, so a never-produced name like `"toString"`/`"constructor"`/`"__proto__"` silently resolved to an inherited `Object.prototype` member instead of throwing, defeating the feature's own "never silently guess" invariant (fixed: `Object.create(null)` pools in `getYieldPool` plus `Object.prototype.hasOwnProperty.call` checks in `resolveYieldRefs`) — plus two MEDIUMs (a misleading "planner not registered" 404 for a yield-resolution failure on a `mode:'single'` step, whose `planner_name` is always `null`, fixed via a discriminated failure-reason shape; `stoa-wrap`'s `amountOverride` path missing the zero-amount short-circuit the probed path has, fixed) and three LOWs (stale "six tables" doc comments after a 7th table was added; the single-mode resolution duplication now fixed by `resolveSingleStepPayload`; a static step list re-fetched every `driveRunOnce` inner-loop pass, now hoisted once per call). Round 2's terminal pass caught that the identical prototype-chain gap existed, unfixed, in the sibling `StepPlanner` registry (`planners/registry.ts`'s `STEP_PLANNERS`) — fixed the same way — plus a planner returning `{legs: [], yield}` silently discarding that yield because the empty-legs early return in `handleReplanStepInner` happened before the yield-write check (fixed: write the yield in that branch too), and a yield write racing ahead of a concurrent loser's `insertRunLeg` collision (fixed: leg inserts now run before the yield write, so a losing caller never reaches it). Round 3's terminal pass caught the identical ordering bug class one layer up: `bumpRunAttempt`/`touchRunDeadline` also ran before the leg-insert loop, so two concurrent genuine-replan racers could both bump a run's retry-attempt counter even though only one's legs ever land — silently burning through `maxReplanAttempts` roughly twice as fast as configured (fixed: moved after the leg-insert loop, alongside the yield write, so all "second-order" writes for a replan generation only commit for whichever caller actually won the race). Round 4's terminal pass came back fully clean across all 5 lenses, with the correctness lens specifically re-verifying the final `insertRunLeg → bumpRunAttempt/touchRunDeadline → upsertYield` ordering end to end (having been rewritten twice across rounds) against the three dedicated regression tests that now pin it. One further gap was caught only by behavioral verification against the real compiled artifact (not the lens passes): `YieldNotFoundError` had not been added to the package's public `server/index.ts` barrel, breaking the established convention that every custom typed error is public — fixed. Behavioral verification then drove the real registered `ouronet.stoa-wrap` → `ouronet.aqp-inject` chain (with `amountOverride: "77.0"`, `yieldAs: "wrappedAmount"`, and `amount: {"$yield":"wrappedAmount"}` respectively) via `driveRunOnce` against a real in-memory DB with a fake chain client at the system boundary: the run reached `succeeded`, and inject's submitted leg's `payload.amount` was exactly `"77.0"` — the literal value wrap actually used, never independently re-probed or statically pre-set. Full history in `docs/work/khronoton-step-yield-carry/design.md`, `plan.md`, and `review.md`. Released 2026-11-20. **1317 specs pass.**
|
|
364
368
|
|
|
365
369
|
**v0.13.0** — Chained multi-step cronoton runs. A cronoton was always exactly one scheduled Pact transaction; a workflow needing several transactions in sequence — some fanning out into a variable number of legs decided only at fire time — had no way to express itself as a single schedulable unit. This release adds that capability end to end, fully additive, across what was built and reviewed as seven sequential phases plus a follow-up cross-phase review. **Non-blocking submit.** The scheduler's tick awaits a fire's confirmation inline inside a single `running`-boolean-guarded pass (`server/loop.ts`) — fine for one transaction, impossible for a multi-leg chained run (serially awaiting four legs could freeze the entire scheduler for up to twenty minutes). A third `executeCodexTransaction` mode, `"submit"`, builds/signs/preflights/submits and returns without ever calling `listenWithTimeout`; `runFire`'s build-through-submit internals were extracted into a shared `submitTransaction` helper with zero change to `fire`'s own external behavior (its existing test suite runs unmodified as the proof). A new optional `ChainClient.pollRequestKeys(keys, chainId)` seam (implemented in `blockchain/stoachain.ts` over Kadena's batch `/poll`) polls every outstanding request key on a chain in one HTTP call per tick, not one per leg. **Schema.** Three new tables: `codex_cronoton_steps` (a cronoton's static step definitions, `mode: 'single' | 'planner'`, a `CHECK` enforcing exactly one shape is filled), `codex_cronoton_runs` (`status: 'planning' | 'awaiting' | 'advancing' | 'succeeded' | 'failed' | 'abandoned'`, `step_index`/`step_count`, `deadline_at`, `attempt`, with a partial `UNIQUE` index self-blocking a second non-terminal run per cronoton at the DB layer — a second `createRun` attempt throws a typed `RunAlreadyInFlightError`, never a raw constraint leak), and `codex_cronoton_run_legs` (`status: 'pending' | 'submitted' | 'confirmed' | 'failed'`, `request_key`, `attempt` as a generation marker, and a `claimed_at` lease column added partway through the arc to close a concurrency race — see below). A leg row is always written `pending` before any submission, mirroring the existing claim-before-fire discipline one level down; store functions (`store/runs.ts`/`store/steps.ts`) are decision-free CRUD, with every typed-error gap (`StepAlreadyExistsError`, `RunLegAlreadyExistsError`, `LegNotSubmittedError`) caught and closed during review, and a shared `isUniqueConstraintError` helper (`store/errors.ts`) replacing what review caught as a verbatim-duplicated copy between the two store files. **Pure decision core (`pure/run-advance.ts`).** `advanceRun(run, legs, now, policy)` is a stateless function returning one or more of six actions (`submit-leg`, `poll`, `advance-step`, `replan-step`, `fail-run`, `wait`) from a fixed-order decision table: a met barrier is checked before a passed deadline (confirmed legs always win); a serial step's mid-sequence failure re-plans immediately (a cursor-paged sequence's later legs become suspect the moment one fails); a parallel step's failure waits for every sibling leg to reach a terminal status first (the "3 of 4 confirm, one fails" case re-plans only once that picture is complete, never on the first failure). A cross-cutting invariant test (`tests/chained-run-invariants.test.ts`) proves `advance-step` is never returned unless every current-step leg is confirmed. **The driver (`runs-driver.ts`).** `driveRunOnce`/`advanceInFlightRunsOnce` execute `advanceRun`'s actions against the store and chain client, wired into `startKhronotonLoop` as a third pass (`codexCronotonTickOnce`'s own claimed-due-row loop branches into a create-run-and-submit-step-0 path for any row with ≥1 step row, reusing `driveRunOnce` for both "just created" and "Nth pass" rather than a second decision path). The schedule's own `next_fire_at` keeps advancing on every due tick regardless of a long-lived run's self-block — two deliberately independent clocks, proven end to end against a real in-memory DB. A prerequisite fix (generation-scoped legs: the previously-unwritten `attempt` column used as a generation marker, plus a new `bumpRunAttempt` store write) makes a genuine re-plan after a failure actually work — without it, a step whose barrier check filters on `step_index` alone would be permanently defeated the instant any leg ever failed once; this retroactively corrected a latent gap in `ouronet.aqp-evict`'s own re-plan path, not just the planners added afterward. **Five built-in planners**, registered through a new `StepPlanner` registry (`registerStepPlanner`/`getStepPlanner`, a plain module-level map mirroring the existing server-resolver registry precedent), ported faithfully from OuronetUI's real transaction-construction logic across a workspace boundary: `ouronet.aqp-evict` reads an on-chain `URHC_BuildEvictPlans` plan, tries one simulated `CC_FullEvictRewards` leg first, and fans out to one `CC_EvictSingleReward` leg per beneficiary only on an actual gas-ceiling refusal; `ouronet.aqp-inject` tries `CC_InjectFinalize` then `CC_Inject` and — unlike the human-facing UI flow it replaces — never fans out and never refuses, propagating a genuine error if both attempts fail, since there's no human in the loop to hand a refusal to; `ouronet.aqp-unstall` fans stale-member-score repair into `CCp_FvtFixSlice` batches sized by a newly-ported generic gas-probe-and-pack algorithm (`pure/split-plan.ts`'s `measureSize`/`planFromSizing`/`splitPlan`, ported verbatim from OuronetUI's `measureSplit.ts` including its two-probe sizing, shrink-and-retry confirmation loop, and secant-refit growth loop); `ouronet.stoa-wrap` and `ouronet.stoa-unwrap` exist as built-ins because hand-authoring a Pact signer capability's scope correctly is the dangerous part, independent of leg count — `stoa-wrap` reads the patron account's live STOA balance via `coin.get-balance` immediately before building its one leg (rather than trusting any inter-step-carried value) and returns `[]` rather than a doomed zero-amount leg when the balance is 0; `stoa-unwrap` conditionally composes a `coin.C_CreateAccount` + `LQD|C_UnwrapStoa` two-form transaction only when its target account probe shows it doesn't exist yet. Every planner builds Pact code with zero interpolated values in the executed code itself — every dynamic value flows through transaction payload and a `read-string`/`read-integer`/`read-msg`/`read-decimal`/`read-keyset` placeholder; only a leg's signer `capabilities` string is a documented, narrowly-scoped exception, made safe by shape-guarding every account string before it reaches either payload or capability line. **Observability and standalone fire.** `executeNow` (`handlers/execute.ts`) now recognizes a chained row (≥1 `codex_cronoton_steps` row), starts a real run via `createRun`+`driveRunOnce`, and returns a real HTTP 409 when a non-terminal run is already in flight. `adaptMultiTxSummary` (`server/resolvers.ts`) widens its existing duck-typed extraction to read an optional per-batch `ok` field (via a dedicated `toReportedOk` helper, never a naive `Boolean()` coercion) and reports genuine multi-tx failure instead of hardcoding `ok: true` — strictly additive. A new `handlers/steps.ts` adds `POST /cronotons/:id/steps/:index/simulate` and `POST /cronotons/:id/steps/:index/fire`, resolving a stored step by index (byte-identical leg construction to a real run, sharing `stepRowToDefinition`/a new shared `resolvePlannerFor` helper rather than reimplementing either) and deliberately bypassing the run/leg-table lifecycle — a preview/testing mechanism, not an alternate production fire path — behind the same confirm gate `executeNow` uses, correctly rejecting a fire (but not a simulate) against a paused or terminal cronoton. New `GET /[id]/runs` (paginated, newest-first) and `GET /[id]/runs/[runId]/legs` (404 if the run belongs to a different cronoton) make a run's full lifecycle and every leg's fire/confirm history visible through this package's own surface for the first time, with per-leg `signers`/capability data redacted from the response. **A genuine concurrency race, found and fixed in already-shipped Phase 3 code.** `driveRunOnce` was only ever called from inside the scheduler loop's own single-process re-entrancy guard until `executeNow`'s new chained-row branch invoked it directly from an HTTP handler — making a previously-deferred, previously-documented gap in `runs-driver.ts`'s own doc comment concretely reachable: the background sweep could pick up the same newly-created run and both callers could read and submit the same `pending` leg before either write landed. Fixed with a real claim-before-submit step: a new nullable `claimed_at` column on `codex_cronoton_run_legs` plus `claimLegForSubmit`/`releaseLegClaim` (a conditional `UPDATE ... WHERE status='pending' AND claimed_at IS NULL`, mirroring the existing due-row claim idiom one level down), proven by an end-to-end test driving two concurrent `driveRunOnce` calls on the same run and asserting the real chain submit happens exactly once. **A follow-up cross-phase review**, run after all six phases shipped and everything was green, found three more significant bugs no single phase's own review could see: a **CRITICAL** stuck-run bug (a planner throw on a run's very first drive — every real planner's first action is a live chain read, so a bad params blob, a genuine Pact failure, or a transient chain outage all trigger it — left the run permanently non-terminal, since `deadline_at` is never stamped before that point and no code path ever marked the run terminal, blocking that cronoton's one-run-at-a-time slot forever with no recovery short of direct DB surgery); a **HIGH** leak of real transfer amounts, account identifiers, and Pact capability lines through the read-tier `runLegsHandler` (now redacted, mirroring `toPublicCronotonView`'s field-by-field convention); and a **HIGH** uncached live `getBlockGasLimit()` fetch repeated on every leg submit and planner probe within a single driver pass, serialized behind the loop's single re-entrancy guard and so delaying every other scheduled fire in the same tick (now cached per chain with a short TTL). A dedicated terminal re-review of the CRITICAL fix then caught a real regression in it — the new terminalize-on-throw catch was broader than intended, turning a benign concurrent-insert race into a permanent run failure and silently discarding the replan retry budget on a transient re-plan error — fixed by narrowing the catch to only the genuinely-unrecoverable first-entry case. Reviewed via nectar across all seven phases of this feature plus the cross-phase round — **33 rounds total**, correctness/conventions/tests on every phase plus a security lens from Phase 3 onward (a funds-moving automaton porting real transaction-construction and signer-capability logic across a workspace boundary), **73 CONFIRMED findings fixed** (or resolved via documentation where that was the proportionate response — e.g. a lease-expiry edge case on the new claim mechanism, accepted as a bounded, already-self-recovering limitation rather than rushed new reconciliation machinery), **4 REFUTED** on adversarial validation, **2 downgraded to STYLISTIC**. One further real bug — binary-floating-point noise leaking into a signed capability line and transaction payload for realistic token balances — was caught only by behavioral verification against the real built artifact using a real measured value from the source handoff; no lens pass or unit test (all of which used clean round numbers) found it. Full history in `docs/work/khronoton-chained-runs/review.md`, its six phase-numbered siblings, and `docs/work/khronoton-chained-runs-cross-phase-review/review.md`. Released 2026-11-20. **1265 specs pass.**
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import crypto3, { randomUUID } from 'crypto';
|
|
2
2
|
import { createContext, useContext } from 'react';
|
|
3
3
|
|
|
4
4
|
// src/server/seams.ts
|
|
@@ -357,6 +357,13 @@ function installSchema(db) {
|
|
|
357
357
|
);
|
|
358
358
|
ensureColumn(db, "codex_cronoton_run_legs", "claimed_at", "TEXT");
|
|
359
359
|
ensureColumn(db, "codex_cronoton_steps", "yield_as", "TEXT");
|
|
360
|
+
ensureColumn(db, "codex_cronotons", "try_single_tx_first", "INTEGER NOT NULL DEFAULT 0");
|
|
361
|
+
ensureColumn(
|
|
362
|
+
db,
|
|
363
|
+
"codex_cronotons",
|
|
364
|
+
"single_tx_mode",
|
|
365
|
+
"TEXT CHECK (single_tx_mode IN ('custom', 'default'))"
|
|
366
|
+
);
|
|
360
367
|
}
|
|
361
368
|
|
|
362
369
|
// src/server/executor-signers.ts
|
|
@@ -1431,7 +1438,7 @@ async function dispatchMultiTxResolver(name, opts) {
|
|
|
1431
1438
|
return r.run(opts);
|
|
1432
1439
|
}
|
|
1433
1440
|
function postponed(error) {
|
|
1434
|
-
return { ok: false, mode: "fire", error, terminalIntent: null };
|
|
1441
|
+
return { ok: false, mode: "fire", error, terminalIntent: null, postponed: true };
|
|
1435
1442
|
}
|
|
1436
1443
|
function toReportedOk(value) {
|
|
1437
1444
|
if (typeof value === "boolean") return value;
|
|
@@ -1537,6 +1544,13 @@ async function fireWithServerResolver(definition, _row, opts = {}) {
|
|
|
1537
1544
|
}
|
|
1538
1545
|
return result;
|
|
1539
1546
|
}
|
|
1547
|
+
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1548
|
+
return dep.db.prepare(
|
|
1549
|
+
`SELECT * FROM codex_cronoton_steps
|
|
1550
|
+
WHERE codex_cronoton_id = ?
|
|
1551
|
+
ORDER BY step_index ASC`
|
|
1552
|
+
).all(codexCronotonId);
|
|
1553
|
+
}
|
|
1540
1554
|
|
|
1541
1555
|
// src/server/store/cronoton.ts
|
|
1542
1556
|
function computeNextOrReject(mode, config, now) {
|
|
@@ -1572,6 +1586,16 @@ function commitCodexCronoton(input, opts) {
|
|
|
1572
1586
|
throw new CodexCronotonValidationError("gasPayer.type must be a string");
|
|
1573
1587
|
}
|
|
1574
1588
|
assertAutoGasGate(input.config);
|
|
1589
|
+
if (input.singleTxMode !== void 0 && input.singleTxMode !== "custom") {
|
|
1590
|
+
throw new CodexCronotonValidationError(
|
|
1591
|
+
`singleTxMode must be "custom" (got ${JSON.stringify(input.singleTxMode)}) \u2014 "default" is not yet supported`
|
|
1592
|
+
);
|
|
1593
|
+
}
|
|
1594
|
+
if (input.trySingleTxFirst) {
|
|
1595
|
+
throw new CodexCronotonValidationError(
|
|
1596
|
+
"trySingleTxFirst cannot be set at commit time \u2014 this cronoton has no steps yet; add steps first, then enable it via an edit"
|
|
1597
|
+
);
|
|
1598
|
+
}
|
|
1575
1599
|
const runtimeArgKeys = input.runtimeArgKeys ?? [];
|
|
1576
1600
|
if (runtimeArgKeysCollide(input.payload ?? {}, runtimeArgKeys)) {
|
|
1577
1601
|
throw new CodexCronotonValidationError(
|
|
@@ -1598,15 +1622,16 @@ function commitCodexCronoton(input, opts) {
|
|
|
1598
1622
|
const externalFireable = input.externalFireable === true || evented;
|
|
1599
1623
|
const triggerOnly = externalFireable || runtimeArgKeys.length > 0 || input.eventDriven === true;
|
|
1600
1624
|
const nextFireAt = triggerOnly ? null : computeNextOrReject(input.scheduleMode, input.scheduleConfig, now).toISOString();
|
|
1601
|
-
const id =
|
|
1625
|
+
const id = crypto3.randomUUID();
|
|
1602
1626
|
const nowIso = now.toISOString();
|
|
1603
1627
|
opts.db.prepare(
|
|
1604
1628
|
`INSERT INTO codex_cronotons
|
|
1605
1629
|
(id, name, description, pact_code, config_json, payload_json,
|
|
1606
1630
|
gas_payer_json, signers_json, schedule_mode, schedule_config_json,
|
|
1607
|
-
server_resolver, external_fireable, runtime_arg_keys,
|
|
1631
|
+
server_resolver, external_fireable, runtime_arg_keys,
|
|
1632
|
+
try_single_tx_first, single_tx_mode, status,
|
|
1608
1633
|
next_fire_at, last_fire_at, created_at, modified_at, created_by)
|
|
1609
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`
|
|
1634
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`
|
|
1610
1635
|
).run(
|
|
1611
1636
|
id,
|
|
1612
1637
|
input.name.trim(),
|
|
@@ -1621,6 +1646,8 @@ function commitCodexCronoton(input, opts) {
|
|
|
1621
1646
|
input.serverResolver ?? null,
|
|
1622
1647
|
externalFireable ? 1 : 0,
|
|
1623
1648
|
runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null,
|
|
1649
|
+
input.trySingleTxFirst ? 1 : 0,
|
|
1650
|
+
input.singleTxMode ?? null,
|
|
1624
1651
|
nextFireAt,
|
|
1625
1652
|
nowIso,
|
|
1626
1653
|
nowIso,
|
|
@@ -1667,6 +1694,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1667
1694
|
let nextScheduleConfigJson = row.schedule_config_json;
|
|
1668
1695
|
let nextServerResolver = row.server_resolver;
|
|
1669
1696
|
let nextFireAt = row.next_fire_at;
|
|
1697
|
+
let nextTrySingleTxFirst = row.try_single_tx_first ?? 0;
|
|
1698
|
+
let nextSingleTxMode = row.single_tx_mode ?? null;
|
|
1670
1699
|
if (typeof patch.name === "string" && patch.name.trim() !== "" && patch.name.trim() !== row.name) {
|
|
1671
1700
|
nextName = patch.name.trim();
|
|
1672
1701
|
changedFields.push("name");
|
|
@@ -1706,6 +1735,31 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1706
1735
|
nextServerResolver = patch.serverResolver;
|
|
1707
1736
|
changedFields.push("serverResolver");
|
|
1708
1737
|
}
|
|
1738
|
+
if (patch.singleTxMode !== void 0 && patch.singleTxMode !== "custom") {
|
|
1739
|
+
throw new CodexCronotonValidationError(
|
|
1740
|
+
`singleTxMode must be "custom" (got ${JSON.stringify(patch.singleTxMode)}) \u2014 "default" is not yet supported`
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
const willBeTrySingleTxFirst = patch.trySingleTxFirst !== void 0 ? patch.trySingleTxFirst : row.try_single_tx_first === 1;
|
|
1744
|
+
if (willBeTrySingleTxFirst && listStepsForCronoton(id, { db }).length === 0) {
|
|
1745
|
+
throw new CodexCronotonValidationError(
|
|
1746
|
+
"trySingleTxFirst requires at least one codex_cronoton_steps row to fall back to \u2014 this cronoton has no steps"
|
|
1747
|
+
);
|
|
1748
|
+
}
|
|
1749
|
+
const willBeSingleTxMode = patch.singleTxMode !== void 0 ? patch.singleTxMode : row.single_tx_mode;
|
|
1750
|
+
if (willBeTrySingleTxFirst && willBeSingleTxMode !== "custom") {
|
|
1751
|
+
throw new CodexCronotonValidationError(
|
|
1752
|
+
'trySingleTxFirst requires singleTxMode: "custom" to be set (single_tx_mode is otherwise left meaningless)'
|
|
1753
|
+
);
|
|
1754
|
+
}
|
|
1755
|
+
if (patch.trySingleTxFirst !== void 0 && (patch.trySingleTxFirst ? 1 : 0) !== row.try_single_tx_first) {
|
|
1756
|
+
nextTrySingleTxFirst = patch.trySingleTxFirst ? 1 : 0;
|
|
1757
|
+
changedFields.push("trySingleTxFirst");
|
|
1758
|
+
}
|
|
1759
|
+
if (patch.singleTxMode !== void 0 && patch.singleTxMode !== row.single_tx_mode) {
|
|
1760
|
+
nextSingleTxMode = patch.singleTxMode;
|
|
1761
|
+
changedFields.push("singleTxMode");
|
|
1762
|
+
}
|
|
1709
1763
|
let scheduleChanged = false;
|
|
1710
1764
|
if (patch.scheduleMode && patch.scheduleConfig) {
|
|
1711
1765
|
nextScheduleMode = patch.scheduleMode;
|
|
@@ -1742,7 +1796,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1742
1796
|
SET name = ?, description = ?, pact_code = ?, config_json = ?,
|
|
1743
1797
|
payload_json = ?, gas_payer_json = ?, signers_json = ?,
|
|
1744
1798
|
schedule_mode = ?, schedule_config_json = ?, server_resolver = ?,
|
|
1745
|
-
external_fireable = ?,
|
|
1799
|
+
external_fireable = ?, try_single_tx_first = ?, single_tx_mode = ?,
|
|
1800
|
+
next_fire_at = ?, modified_at = ?
|
|
1746
1801
|
WHERE id = ?`
|
|
1747
1802
|
).run(
|
|
1748
1803
|
nextName,
|
|
@@ -1756,6 +1811,8 @@ function editCodexCronoton(id, patch, opts) {
|
|
|
1756
1811
|
nextScheduleConfigJson,
|
|
1757
1812
|
nextServerResolver,
|
|
1758
1813
|
nextExternalFireable,
|
|
1814
|
+
nextTrySingleTxFirst,
|
|
1815
|
+
nextSingleTxMode,
|
|
1759
1816
|
nextFireAt,
|
|
1760
1817
|
(opts.now ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1761
1818
|
id
|
|
@@ -1845,7 +1902,7 @@ function createManualBatch(input, opts) {
|
|
|
1845
1902
|
}
|
|
1846
1903
|
const now = opts.now ?? /* @__PURE__ */ new Date();
|
|
1847
1904
|
const nowIso = now.toISOString();
|
|
1848
|
-
const id =
|
|
1905
|
+
const id = crypto3.randomUUID();
|
|
1849
1906
|
db.prepare(
|
|
1850
1907
|
`INSERT INTO codex_cronoton_manual_batches
|
|
1851
1908
|
(id, codex_cronoton_id, total, completed, interval_seconds, status,
|
|
@@ -1897,14 +1954,7 @@ function computeDefinitionFingerprint(row) {
|
|
|
1897
1954
|
scheduleConfig: parseJson2(row.schedule_config_json, {})
|
|
1898
1955
|
};
|
|
1899
1956
|
const canonical = JSON.stringify(canonicalize(parts));
|
|
1900
|
-
return
|
|
1901
|
-
}
|
|
1902
|
-
function listStepsForCronoton(codexCronotonId, dep) {
|
|
1903
|
-
return dep.db.prepare(
|
|
1904
|
-
`SELECT * FROM codex_cronoton_steps
|
|
1905
|
-
WHERE codex_cronoton_id = ?
|
|
1906
|
-
ORDER BY step_index ASC`
|
|
1907
|
-
).all(codexCronotonId);
|
|
1957
|
+
return crypto3.createHash("sha256").update(canonical).digest("hex");
|
|
1908
1958
|
}
|
|
1909
1959
|
function createRun(input, dep) {
|
|
1910
1960
|
const id = randomUUID();
|
|
@@ -2042,7 +2092,7 @@ function markRunTerminal(runId, status, dep) {
|
|
|
2042
2092
|
}
|
|
2043
2093
|
}
|
|
2044
2094
|
function upsertYield(input, dep) {
|
|
2045
|
-
const id =
|
|
2095
|
+
const id = crypto3.randomUUID();
|
|
2046
2096
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
2047
2097
|
const value = input.value === void 0 ? null : input.value;
|
|
2048
2098
|
dep.db.prepare(
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-
|
|
1
|
+
import { useKhronotonAdapter, useKhronotonConfig, runGated } from './chunk-24THBKR7.js';
|
|
2
2
|
import { useState, useRef, useEffect, useCallback } from 'react';
|
|
3
3
|
|
|
4
4
|
function useCronotons(query) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ReactNode } from 'react';
|
|
2
|
-
import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-
|
|
2
|
+
import { b as CodexTxConfig, c as CodexGasPayer, d as CodexSigner, S as ScheduleMode, e as ScheduleConfig, C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from './types-DH7Ym8FQ.js';
|
|
3
3
|
import { b as DbDep, D as Database } from './seams-Co8Tq4ka.js';
|
|
4
4
|
|
|
5
5
|
/** A validated bag of runtime args — every value is a string (Pact `read-string`). */
|
package/dist/handlers/execute.js
CHANGED
|
@@ -23,7 +23,9 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { json, err } from "./http.js";
|
|
25
25
|
import { withConfirm } from "./context.js";
|
|
26
|
-
import { executeCodexTransaction,
|
|
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
|
|
57
|
-
* the
|
|
58
|
-
*
|
|
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
|
-
|
|
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 {
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -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-
|
|
2
|
-
export { U as UseKhronotonResult, u as useKhronoton } from '../context-
|
|
3
|
-
import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-
|
|
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
|
|
package/dist/hooks/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-
|
|
2
|
-
export { useKhronoton } from '../chunk-
|
|
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';
|
package/dist/provider/index.d.ts
CHANGED
|
@@ -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-
|
|
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-
|
|
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-
|
|
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
|
package/dist/provider/index.js
CHANGED
|
@@ -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-
|
|
2
|
-
export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-
|
|
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
|
|
385
|
-
|
|
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
|
|
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
|
|
574
|
+
const { result, fireId } = await fireAndRecord2(ctx, row, definition);
|
|
527
575
|
return json(200, {
|
|
528
576
|
ok: result.ok,
|
|
529
577
|
fireId,
|