@ancientpantheon/khronoton-core 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +83 -3
  3. package/dist/PactCodeMirror-HQTGE2K3.js +64 -0
  4. package/dist/chunk-DK4CDPXH.js +379 -0
  5. package/dist/chunk-U3F5HEHO.js +1639 -0
  6. package/dist/context-BKtdrA2B.d.ts +363 -0
  7. package/dist/handlers/batch.d.ts +21 -0
  8. package/dist/handlers/batch.js +57 -0
  9. package/dist/handlers/context.d.ts +94 -0
  10. package/dist/handlers/context.js +75 -0
  11. package/dist/handlers/cronoton.d.ts +70 -0
  12. package/dist/handlers/cronoton.js +165 -0
  13. package/dist/handlers/execute.d.ts +30 -0
  14. package/dist/handlers/execute.js +227 -0
  15. package/dist/handlers/http.d.ts +85 -0
  16. package/dist/handlers/http.js +84 -0
  17. package/dist/handlers/index.d.ts +27 -0
  18. package/dist/handlers/index.js +34 -0
  19. package/dist/handlers/read.d.ts +29 -0
  20. package/dist/handlers/read.js +94 -0
  21. package/dist/hooks/index.d.ts +143 -0
  22. package/dist/hooks/index.js +2 -0
  23. package/dist/provider/index.d.ts +421 -0
  24. package/dist/provider/index.js +675 -0
  25. package/dist/server/executor-signers.d.ts +29 -0
  26. package/dist/server/executor-signers.js +60 -0
  27. package/dist/server/executor.d.ts +53 -0
  28. package/dist/server/executor.js +280 -0
  29. package/dist/server/index.d.ts +27 -0
  30. package/dist/server/index.js +51 -0
  31. package/dist/server/loop.d.ts +36 -0
  32. package/dist/server/loop.js +51 -0
  33. package/dist/server/pure/capability.d.ts +31 -0
  34. package/dist/server/pure/capability.js +63 -0
  35. package/dist/server/pure/fingerprint.d.ts +8 -0
  36. package/dist/server/pure/fingerprint.js +44 -0
  37. package/dist/server/pure/runtime-args.d.ts +34 -0
  38. package/dist/server/pure/runtime-args.js +99 -0
  39. package/dist/server/resolvers.d.ts +140 -0
  40. package/dist/server/resolvers.js +200 -0
  41. package/dist/server/schema.d.ts +31 -0
  42. package/dist/server/schema.js +93 -0
  43. package/dist/server/seams.d.ts +231 -0
  44. package/dist/server/seams.js +34 -0
  45. package/dist/server/store/claim.d.ts +59 -0
  46. package/dist/server/store/claim.js +97 -0
  47. package/dist/server/store/cronoton.d.ts +79 -0
  48. package/dist/server/store/cronoton.js +268 -0
  49. package/dist/server/store/errors.d.ts +26 -0
  50. package/dist/server/store/errors.js +40 -0
  51. package/dist/server/store/fires.d.ts +77 -0
  52. package/dist/server/store/fires.js +170 -0
  53. package/dist/server/store/index.d.ts +26 -0
  54. package/dist/server/store/index.js +33 -0
  55. package/dist/server/store/manual-batch.d.ts +38 -0
  56. package/dist/server/store/manual-batch.js +110 -0
  57. package/dist/server/store/mappers.d.ts +21 -0
  58. package/dist/server/store/mappers.js +62 -0
  59. package/dist/server/tick.d.ts +83 -0
  60. package/dist/server/tick.js +235 -0
  61. package/dist/server/types.d.ts +220 -0
  62. package/dist/server/types.js +14 -0
  63. package/dist/types-u_nUX1Bg.d.ts +222 -0
  64. package/dist/ui/index.d.ts +235 -0
  65. package/dist/ui/index.js +3646 -0
  66. package/dist/ui.css +35 -0
  67. package/package.json +64 -5
@@ -0,0 +1,38 @@
1
+ import type { Config, DbDep } from "../seams.js";
2
+ import type { CodexManualBatchRow } from "../types.js";
3
+ export declare function getManualBatch(id: string, dep: DbDep): CodexManualBatchRow | null;
4
+ /** The one active batch for a cronoton (at most one is allowed at a time). */
5
+ export declare function getActiveManualBatchForCronoton(cronotonId: string, dep: DbDep): CodexManualBatchRow | null;
6
+ export interface CreateManualBatchInput {
7
+ cronotonId: string;
8
+ total: number;
9
+ createdBy: string;
10
+ }
11
+ interface CreateManualBatchOpts extends DbDep {
12
+ now?: Date;
13
+ /** Overrides the default count bounds and inter-fire cadence. */
14
+ config?: Partial<Config>;
15
+ }
16
+ /**
17
+ * Create a manual execution batch. Validates the count bounds, that the parent
18
+ * cronoton exists + is active + is NOT one-time (a single fire spends a one-time
19
+ * entry, so batching it is meaningless), and that no batch is already running
20
+ * for it. `next_at = now` so the first fire is picked up on the next worker tick.
21
+ */
22
+ export declare function createManualBatch(input: CreateManualBatchInput, opts: CreateManualBatchOpts): CodexManualBatchRow;
23
+ /** Active batches with a due slot (`next_at <= now`), oldest-first. */
24
+ export declare function fetchDueManualBatches(now: Date, limit: number, dep: DbDep): CodexManualBatchRow[];
25
+ /**
26
+ * Atomically claim one fire slot of a batch BEFORE the inline fire (mirrors
27
+ * claimDueCodexCronoton): a single conditional UPDATE increments `completed`,
28
+ * advances `next_at` (+interval, or NULL on the final slot) and flips status to
29
+ * 'completed' on the last slot. The WHERE clause re-asserts the due predicate so
30
+ * two racing claimers see exactly one win. Returns true when this caller won the
31
+ * slot (changes === 1) and should fire.
32
+ */
33
+ export declare function claimManualBatchFire(batch: CodexManualBatchRow, now: Date, dep: DbDep): boolean;
34
+ /** Operator (or auto) cancel of an active batch. Idempotent: ok=false if not active. */
35
+ export declare function cancelManualBatch(id: string, dep: DbDep): {
36
+ ok: boolean;
37
+ };
38
+ export {};
@@ -0,0 +1,110 @@
1
+ /**
2
+ * manual-batch — the create / due-fetch / claim / cancel lifecycle for
3
+ * `codex_cronoton_manual_batches` ("Execute Now ×N").
4
+ *
5
+ * The centerpiece is {@link claimManualBatchFire}: a single conditional UPDATE
6
+ * that increments `completed`, advances `next_at` (+interval, or NULL on the
7
+ * final slot) and flips `status` to 'completed' on the last slot IN THE SAME
8
+ * statement. The WHERE clause re-asserts the due predicate so two racing
9
+ * claimers see exactly one win — the once-only guarantee mirrored from
10
+ * {@link claimDueCodexCronoton}.
11
+ *
12
+ * Count bounds and inter-fire cadence read from an OPTIONAL injected config
13
+ * ({@link Config.manualBatch}); the exported constants back them as DEFAULTS.
14
+ */
15
+ import crypto from "node:crypto";
16
+ import { getCodexCronoton } from "./cronoton.js";
17
+ import { CodexCronotonValidationError, ManualBatchActiveError, MANUAL_BATCH_INTERVAL_SECONDS, MANUAL_BATCH_MAX, MANUAL_BATCH_MIN, } from "./errors.js";
18
+ export function getManualBatch(id, dep) {
19
+ const row = dep.db
20
+ .prepare("SELECT * FROM codex_cronoton_manual_batches WHERE id = ?")
21
+ .get(id);
22
+ return row ?? null;
23
+ }
24
+ /** The one active batch for a cronoton (at most one is allowed at a time). */
25
+ export function getActiveManualBatchForCronoton(cronotonId, dep) {
26
+ const row = dep.db
27
+ .prepare(`SELECT * FROM codex_cronoton_manual_batches
28
+ WHERE codex_cronoton_id = ? AND status = 'active'
29
+ ORDER BY created_at DESC LIMIT 1`)
30
+ .get(cronotonId);
31
+ return row ?? null;
32
+ }
33
+ /**
34
+ * Create a manual execution batch. Validates the count bounds, that the parent
35
+ * cronoton exists + is active + is NOT one-time (a single fire spends a one-time
36
+ * entry, so batching it is meaningless), and that no batch is already running
37
+ * for it. `next_at = now` so the first fire is picked up on the next worker tick.
38
+ */
39
+ export function createManualBatch(input, opts) {
40
+ const db = opts.db;
41
+ const { min, max, intervalSeconds } = opts.config?.manualBatch ?? {
42
+ min: MANUAL_BATCH_MIN,
43
+ max: MANUAL_BATCH_MAX,
44
+ intervalSeconds: MANUAL_BATCH_INTERVAL_SECONDS,
45
+ };
46
+ const total = Math.trunc(input.total);
47
+ if (!Number.isFinite(input.total) || total < min || total > max) {
48
+ throw new CodexCronotonValidationError(`count must be an integer between ${min} and ${max}`);
49
+ }
50
+ const cronoton = getCodexCronoton(input.cronotonId, { db });
51
+ if (!cronoton)
52
+ throw new CodexCronotonValidationError("not found");
53
+ if (cronoton.status !== "active") {
54
+ throw new CodexCronotonValidationError(`cannot batch-execute a codex cronoton with status '${cronoton.status}'`);
55
+ }
56
+ if (cronoton.schedule_mode === "one-time") {
57
+ throw new CodexCronotonValidationError("one-time codex cronotons cannot be batch-executed (a single fire spends them)");
58
+ }
59
+ if (getActiveManualBatchForCronoton(input.cronotonId, { db })) {
60
+ throw new ManualBatchActiveError();
61
+ }
62
+ const now = opts.now ?? new Date();
63
+ const nowIso = now.toISOString();
64
+ const id = crypto.randomUUID();
65
+ db.prepare(`INSERT INTO codex_cronoton_manual_batches
66
+ (id, codex_cronoton_id, total, completed, interval_seconds, status,
67
+ next_at, created_at, modified_at, created_by)
68
+ VALUES (?, ?, ?, 0, ?, 'active', ?, ?, ?, ?)`).run(id, input.cronotonId, total, intervalSeconds, nowIso, nowIso, nowIso, input.createdBy);
69
+ return getManualBatch(id, { db });
70
+ }
71
+ /** Active batches with a due slot (`next_at <= now`), oldest-first. */
72
+ export function fetchDueManualBatches(now, limit, dep) {
73
+ return dep.db
74
+ .prepare(`SELECT * FROM codex_cronoton_manual_batches
75
+ WHERE status = 'active' AND next_at IS NOT NULL AND next_at <= ?
76
+ ORDER BY next_at ASC LIMIT ?`)
77
+ .all(now.toISOString(), limit);
78
+ }
79
+ /**
80
+ * Atomically claim one fire slot of a batch BEFORE the inline fire (mirrors
81
+ * claimDueCodexCronoton): a single conditional UPDATE increments `completed`,
82
+ * advances `next_at` (+interval, or NULL on the final slot) and flips status to
83
+ * 'completed' on the last slot. The WHERE clause re-asserts the due predicate so
84
+ * two racing claimers see exactly one win. Returns true when this caller won the
85
+ * slot (changes === 1) and should fire.
86
+ */
87
+ export function claimManualBatchFire(batch, now, dep) {
88
+ const db = dep.db;
89
+ const nowIso = now.toISOString();
90
+ const nextAtIso = new Date(now.getTime() + batch.interval_seconds * 1000).toISOString();
91
+ const result = db
92
+ .prepare(`UPDATE codex_cronoton_manual_batches
93
+ SET completed = completed + 1,
94
+ next_at = CASE WHEN completed + 1 < total THEN ? ELSE NULL END,
95
+ status = CASE WHEN completed + 1 < total THEN 'active' ELSE 'completed' END,
96
+ modified_at = ?
97
+ WHERE id = ? AND status = 'active' AND next_at IS NOT NULL
98
+ AND next_at <= ? AND completed < total`)
99
+ .run(nextAtIso, nowIso, batch.id, nowIso);
100
+ return result.changes === 1;
101
+ }
102
+ /** Operator (or auto) cancel of an active batch. Idempotent: ok=false if not active. */
103
+ export function cancelManualBatch(id, dep) {
104
+ const result = dep.db
105
+ .prepare(`UPDATE codex_cronoton_manual_batches
106
+ SET status = 'cancelled', next_at = NULL, modified_at = ?
107
+ WHERE id = ? AND status = 'active'`)
108
+ .run(new Date().toISOString(), id);
109
+ return { ok: result.changes === 1 };
110
+ }
@@ -0,0 +1,21 @@
1
+ import type { CodexCronotonRow, CodexManualBatchRow, CodexTxConfig, CodexTxDefinition, ManualBatchView } from '../types.js';
2
+ /**
3
+ * The single mapper from a `codex_cronotons` row to the `CodexTxDefinition`
4
+ * consumed by the executor. `scheduleKind` is `'one-time'` ONLY for the
5
+ * one-time mode; all other six modes map to `'recurring'`.
6
+ */
7
+ export declare function rowToDefinition(row: CodexCronotonRow): CodexTxDefinition;
8
+ /** True when the row is opted into external (HMAC-endpoint) firing. */
9
+ export declare function rowExternalFireable(row: CodexCronotonRow): boolean;
10
+ /** The declared runtime-arg keys for the row; empty for ordinary rows. */
11
+ export declare function rowRuntimeArgKeys(row: CodexCronotonRow): string[];
12
+ /**
13
+ * AUTO-gas commit-gate: an `autoGasLimit === true` row cannot be committed
14
+ * without a concrete positive numeric `gasLimit` (the prior simulate's
15
+ * calibrated output, supplied by the client). The API does NOT re-run a
16
+ * simulate at commit time — it enforces the presence of a concrete limit so the
17
+ * autonomous fire always has one (the tick never has a human to calibrate).
18
+ */
19
+ export declare function assertAutoGasGate(config: CodexTxConfig): void;
20
+ /** Project a raw batch row onto the client-facing view (clamping remaining). */
21
+ export declare function manualBatchView(row: CodexManualBatchRow): ManualBatchView;
@@ -0,0 +1,62 @@
1
+ import { parseRuntimeArgKeys } from '../pure/runtime-args.js';
2
+ import { AutoGasGateError } from './errors.js';
3
+ function parseJson(json, fallback) {
4
+ if (json == null)
5
+ return fallback;
6
+ return JSON.parse(json);
7
+ }
8
+ /**
9
+ * The single mapper from a `codex_cronotons` row to the `CodexTxDefinition`
10
+ * consumed by the executor. `scheduleKind` is `'one-time'` ONLY for the
11
+ * one-time mode; all other six modes map to `'recurring'`.
12
+ */
13
+ export function rowToDefinition(row) {
14
+ return {
15
+ pactCode: row.pact_code,
16
+ config: parseJson(row.config_json, {}),
17
+ payload: parseJson(row.payload_json, {}),
18
+ gasPayer: parseJson(row.gas_payer_json, {
19
+ type: 'gas-station',
20
+ }),
21
+ signers: parseJson(row.signers_json, []),
22
+ scheduleKind: row.schedule_mode === 'one-time' ? 'one-time' : 'recurring',
23
+ serverResolver: row.server_resolver ?? undefined,
24
+ };
25
+ }
26
+ /** True when the row is opted into external (HMAC-endpoint) firing. */
27
+ export function rowExternalFireable(row) {
28
+ return row.external_fireable === 1;
29
+ }
30
+ /** The declared runtime-arg keys for the row; empty for ordinary rows. */
31
+ export function rowRuntimeArgKeys(row) {
32
+ return parseRuntimeArgKeys(row.runtime_arg_keys);
33
+ }
34
+ /**
35
+ * AUTO-gas commit-gate: an `autoGasLimit === true` row cannot be committed
36
+ * without a concrete positive numeric `gasLimit` (the prior simulate's
37
+ * calibrated output, supplied by the client). The API does NOT re-run a
38
+ * simulate at commit time — it enforces the presence of a concrete limit so the
39
+ * autonomous fire always has one (the tick never has a human to calibrate).
40
+ */
41
+ export function assertAutoGasGate(config) {
42
+ if (config.autoGasLimit !== true)
43
+ return;
44
+ if (!Number.isFinite(config.gasLimit) || config.gasLimit <= 0) {
45
+ throw new AutoGasGateError();
46
+ }
47
+ }
48
+ /** Project a raw batch row onto the client-facing view (clamping remaining). */
49
+ export function manualBatchView(row) {
50
+ return {
51
+ id: row.id,
52
+ codexCronotonId: row.codex_cronoton_id,
53
+ total: row.total,
54
+ completed: row.completed,
55
+ remaining: Math.max(0, row.total - row.completed),
56
+ intervalSeconds: row.interval_seconds,
57
+ status: row.status,
58
+ nextAt: row.next_at,
59
+ createdBy: row.created_by,
60
+ createdAt: row.created_at,
61
+ };
62
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The server tick — the async select → claim → fire → record → finalize → audit
3
+ * sequence, lifted from the Hub `lib/codex-cronoton/tick.ts` into a pure
4
+ * ctx-taking form.
5
+ *
6
+ * The Hub reached its DB, audit log, and fire dispatcher through ambient globals
7
+ * (`getDb()`, `logAuditFromWorker`, a `stoicism-mint` re-export). Here every one
8
+ * of those is injected on {@link TickCtx} and threaded explicitly: `{ db }` into
9
+ * each store call, `{ db, resolveFireMode }` into the fire record, the full
10
+ * `{ runtime, resolver, config, db, deps }` into {@link fireByServerResolver},
11
+ * and `onAudit(...)` for the two audit action strings.
12
+ *
13
+ * ── CLAIM-BEFORE-FIRE / once-only contract (LOAD-BEARING) ─────────────────────
14
+ * Because the fire runs inline and can block for minutes, each due row's
15
+ * `next_fire_at` MUST be advanced (recurring) or cleared (one-time) atomically
16
+ * BEFORE the await via {@link claimDueCodexCronoton}:
17
+ * - claim wins (true) → the row is no longer due/re-selectable; fire it.
18
+ * - claim lost (false) → an overlapping tick or a manual Execute-Now already
19
+ * claimed it → SKIP (no fire).
20
+ * The per-row atomic claim is the PRIMARY double-fire guard.
21
+ *
22
+ * ── Failure policy ────────────────────────────────────────────────────────────
23
+ * Single attempt, no retry, no backoff, NO auto-pause. Exactly ONE fire row per
24
+ * fire. A recurring FAILURE stays `active` (its next_fire_at was already advanced
25
+ * by the claim — the failure lives only in fire history). A one-time fire applies
26
+ * the executor's terminal intent (success → completed, failure → error). The fire
27
+ * dispatcher NEVER throws — the tick reads `result.ok`; the surrounding try/catch
28
+ * isolates only orchestration errors (rowToDefinition parse, recordFire write).
29
+ *
30
+ * The ONLY status write this tick issues is the one-time terminal transition via
31
+ * {@link applyTerminalIntent}. It NEVER writes `status='paused'` and issues NO
32
+ * post-fire recurring advance (the claim already advanced it).
33
+ */
34
+ import type { ChainRuntime, Config, Database, KeyResolver, OnAudit, ResolveFireMode } from "./seams.js";
35
+ /**
36
+ * The injected context the tick runs against — a structural SUPERSET of the
37
+ * executor's `{ runtime, resolver }`, so {@link fireByServerResolver} receives
38
+ * `runtime`+`resolver`+`db` straight off it. Every host capability the Hub tick
39
+ * reached for ambiently arrives here.
40
+ */
41
+ export interface TickCtx {
42
+ db: Database;
43
+ resolver: KeyResolver;
44
+ runtime: ChainRuntime;
45
+ onAudit: OnAudit;
46
+ resolveFireMode: ResolveFireMode;
47
+ config: Config;
48
+ }
49
+ export interface CodexTickResult {
50
+ /** Rows that fired successfully (result ok:true). */
51
+ firedIds: string[];
52
+ /** Rows that fired but the dispatcher returned ok:false (fired-and-failed). */
53
+ failedIds: string[];
54
+ /** Rows skipped without firing (lost claim, or an orchestration error). */
55
+ skippedIds: string[];
56
+ }
57
+ /**
58
+ * Select → claim → fire → record → finalize → audit for every due codex
59
+ * cronoton. Fires INLINE via {@link fireByServerResolver} (map §8 divergence #3:
60
+ * always through the dispatcher, never the executor directly).
61
+ */
62
+ export declare function codexCronotonTickOnce(now: Date, ctx: TickCtx): Promise<CodexTickResult>;
63
+ export interface CodexManualBatchTickResult {
64
+ /** Batch ids that fired a slot successfully this tick. */
65
+ firedIds: string[];
66
+ /** Batch ids that fired a slot but the dispatcher returned ok:false. */
67
+ failedIds: string[];
68
+ /** Batch ids skipped (lost claim / orchestration error). */
69
+ skippedIds: string[];
70
+ /** Batch ids auto-cancelled because the parent cronoton is no longer active. */
71
+ cancelledIds: string[];
72
+ }
73
+ /**
74
+ * Process due manual-execution batches — the "Execute Now ×N" rail. For each
75
+ * batch with a due slot it fires the PARENT cronoton ONCE (the same shared fire +
76
+ * fire-row recording as the scheduled tick), spaced by the batch's interval. Each
77
+ * slot is CLAIMED before the inline fire so an overlapping tick cannot double-fire
78
+ * it. A batch fire records a fire row + a `manual_fire` audit (actor 'ancient',
79
+ * via 'manual_batch', attributed to the batch's creator) and NEVER advances the
80
+ * cronoton's own schedule. If the parent has left 'active', the batch is
81
+ * auto-cancelled instead of fired.
82
+ */
83
+ export declare function processDueManualBatchesOnce(now: Date, ctx: TickCtx): Promise<CodexManualBatchTickResult>;
@@ -0,0 +1,235 @@
1
+ /**
2
+ * The server tick — the async select → claim → fire → record → finalize → audit
3
+ * sequence, lifted from the Hub `lib/codex-cronoton/tick.ts` into a pure
4
+ * ctx-taking form.
5
+ *
6
+ * The Hub reached its DB, audit log, and fire dispatcher through ambient globals
7
+ * (`getDb()`, `logAuditFromWorker`, a `stoicism-mint` re-export). Here every one
8
+ * of those is injected on {@link TickCtx} and threaded explicitly: `{ db }` into
9
+ * each store call, `{ db, resolveFireMode }` into the fire record, the full
10
+ * `{ runtime, resolver, config, db, deps }` into {@link fireByServerResolver},
11
+ * and `onAudit(...)` for the two audit action strings.
12
+ *
13
+ * ── CLAIM-BEFORE-FIRE / once-only contract (LOAD-BEARING) ─────────────────────
14
+ * Because the fire runs inline and can block for minutes, each due row's
15
+ * `next_fire_at` MUST be advanced (recurring) or cleared (one-time) atomically
16
+ * BEFORE the await via {@link claimDueCodexCronoton}:
17
+ * - claim wins (true) → the row is no longer due/re-selectable; fire it.
18
+ * - claim lost (false) → an overlapping tick or a manual Execute-Now already
19
+ * claimed it → SKIP (no fire).
20
+ * The per-row atomic claim is the PRIMARY double-fire guard.
21
+ *
22
+ * ── Failure policy ────────────────────────────────────────────────────────────
23
+ * Single attempt, no retry, no backoff, NO auto-pause. Exactly ONE fire row per
24
+ * fire. A recurring FAILURE stays `active` (its next_fire_at was already advanced
25
+ * by the claim — the failure lives only in fire history). A one-time fire applies
26
+ * the executor's terminal intent (success → completed, failure → error). The fire
27
+ * dispatcher NEVER throws — the tick reads `result.ok`; the surrounding try/catch
28
+ * isolates only orchestration errors (rowToDefinition parse, recordFire write).
29
+ *
30
+ * The ONLY status write this tick issues is the one-time terminal transition via
31
+ * {@link applyTerminalIntent}. It NEVER writes `status='paused'` and issues NO
32
+ * post-fire recurring advance (the claim already advanced it).
33
+ */
34
+ import { fetchDueCodexCronotons, claimDueCodexCronoton, applyTerminalIntent, } from "./store/claim.js";
35
+ import { rowToDefinition } from "./store/mappers.js";
36
+ import { recordFire } from "./store/fires.js";
37
+ import { computeDefinitionFingerprint } from "./pure/fingerprint.js";
38
+ import { fetchDueManualBatches, claimManualBatchFire, cancelManualBatch, } from "./store/manual-batch.js";
39
+ import { getCodexCronoton } from "./store/cronoton.js";
40
+ import { fireByServerResolver } from "./resolvers.js";
41
+ import { TICK_BATCH_LIMIT } from "./seams.js";
42
+ /**
43
+ * One multi-tx `onTx` collector + the `FireTxKey[]` it fills, threaded into
44
+ * {@link fireByServerResolver} so an INLINE multi-tx fire records the per-tx
45
+ * breakdown. A no-op for single-tx/no-resolver rows (the single-tx path never
46
+ * invokes `onTx`), so it is safe to pass unconditionally.
47
+ */
48
+ function makeTxKeyCollector() {
49
+ const txKeys = [];
50
+ return {
51
+ txKeys,
52
+ deps: {
53
+ onTx: (tx) => txKeys.push({
54
+ kind: tx.kind,
55
+ chainId: tx.chainId,
56
+ requestKey: tx.requestKey,
57
+ ok: tx.ok,
58
+ }),
59
+ },
60
+ };
61
+ }
62
+ /**
63
+ * Select → claim → fire → record → finalize → audit for every due codex
64
+ * cronoton. Fires INLINE via {@link fireByServerResolver} (map §8 divergence #3:
65
+ * always through the dispatcher, never the executor directly).
66
+ */
67
+ export async function codexCronotonTickOnce(now, ctx) {
68
+ const firedIds = [];
69
+ const failedIds = [];
70
+ const skippedIds = [];
71
+ const due = fetchDueCodexCronotons(now, ctx.config?.tickBatchLimit ?? TICK_BATCH_LIMIT, {
72
+ db: ctx.db,
73
+ });
74
+ for (const row of due) {
75
+ try {
76
+ const claimed = claimDueCodexCronoton(row, now, { db: ctx.db });
77
+ if (!claimed) {
78
+ skippedIds.push(row.id);
79
+ continue;
80
+ }
81
+ const scheduleKind = row.schedule_mode === "one-time" ? "one-time" : "recurring";
82
+ const definition = rowToDefinition(row);
83
+ const { txKeys, deps: collectDeps } = makeTxKeyCollector();
84
+ const result = await fireByServerResolver(definition, row, {
85
+ runtime: ctx.runtime,
86
+ resolver: ctx.resolver,
87
+ config: ctx.config,
88
+ db: ctx.db,
89
+ deps: collectDeps,
90
+ });
91
+ const fingerprint = computeDefinitionFingerprint(row);
92
+ const fireId = recordFire({
93
+ codexCronotonId: row.id,
94
+ jobId: null,
95
+ firedAt: now.toISOString(),
96
+ status: result.ok ? "success" : "failure",
97
+ requestKey: result.requestKey,
98
+ chainId: result.chainId,
99
+ errorMessage: result.error,
100
+ chainResponse: result.rawResult,
101
+ definitionFingerprint: fingerprint,
102
+ txKeys,
103
+ }, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
104
+ // Recurring: next_fire_at was already advanced by the claim (a failed
105
+ // recurring stays active — no post-fire advance). One-time: next_fire_at
106
+ // was already cleared by the claim — apply the terminal status.
107
+ if (scheduleKind === "one-time") {
108
+ applyTerminalIntent(row.id, result.terminalIntent, { db: ctx.db });
109
+ }
110
+ await ctx.onAudit({
111
+ action: result.ok ? "codex_cronoton.fire" : "codex_cronoton.fire_failed",
112
+ result: result.ok ? "success" : "failure",
113
+ targetKind: "codex_cronoton",
114
+ targetId: row.id,
115
+ detail: {
116
+ codexCronotonId: row.id,
117
+ fireId,
118
+ requestKey: result.requestKey,
119
+ chainId: result.chainId,
120
+ actor: "scheduler",
121
+ scheduleKind,
122
+ terminalStatus: result.terminalIntent?.status,
123
+ definitionFingerprint: fingerprint,
124
+ errorMessage: result.error,
125
+ message: result.error,
126
+ },
127
+ });
128
+ if (result.ok)
129
+ firedIds.push(row.id);
130
+ else
131
+ failedIds.push(row.id);
132
+ }
133
+ catch (err) {
134
+ // Orchestration error (rowToDefinition parse, recordFire write). The claim
135
+ // already advanced/cleared next_fire_at, so this row will NOT re-arm;
136
+ // isolate the failure and continue to the next row. Surface the diagnostic
137
+ // (matching the Hub) so a "fired but the fire-record write failed" case is
138
+ // never silent — the id also lands in skippedIds.
139
+ console.error(`khronoton tick: codex cronoton ${row.id} skipped after an orchestration error`, err);
140
+ skippedIds.push(row.id);
141
+ }
142
+ }
143
+ return { firedIds, failedIds, skippedIds };
144
+ }
145
+ /**
146
+ * Process due manual-execution batches — the "Execute Now ×N" rail. For each
147
+ * batch with a due slot it fires the PARENT cronoton ONCE (the same shared fire +
148
+ * fire-row recording as the scheduled tick), spaced by the batch's interval. Each
149
+ * slot is CLAIMED before the inline fire so an overlapping tick cannot double-fire
150
+ * it. A batch fire records a fire row + a `manual_fire` audit (actor 'ancient',
151
+ * via 'manual_batch', attributed to the batch's creator) and NEVER advances the
152
+ * cronoton's own schedule. If the parent has left 'active', the batch is
153
+ * auto-cancelled instead of fired.
154
+ */
155
+ export async function processDueManualBatchesOnce(now, ctx) {
156
+ const firedIds = [];
157
+ const failedIds = [];
158
+ const skippedIds = [];
159
+ const cancelledIds = [];
160
+ const due = fetchDueManualBatches(now, ctx.config?.tickBatchLimit ?? TICK_BATCH_LIMIT, {
161
+ db: ctx.db,
162
+ });
163
+ for (const batch of due) {
164
+ try {
165
+ const cronoton = getCodexCronoton(batch.codex_cronoton_id, { db: ctx.db });
166
+ if (!cronoton || cronoton.status !== "active") {
167
+ // Parent paused / deleted / terminal — stop the batch.
168
+ cancelManualBatch(batch.id, { db: ctx.db });
169
+ cancelledIds.push(batch.id);
170
+ continue;
171
+ }
172
+ const claimed = claimManualBatchFire(batch, now, { db: ctx.db });
173
+ if (!claimed) {
174
+ skippedIds.push(batch.id);
175
+ continue;
176
+ }
177
+ const batchIndex = batch.completed + 1;
178
+ const definition = rowToDefinition(cronoton);
179
+ const { txKeys, deps: collectDeps } = makeTxKeyCollector();
180
+ const result = await fireByServerResolver(definition, cronoton, {
181
+ runtime: ctx.runtime,
182
+ resolver: ctx.resolver,
183
+ config: ctx.config,
184
+ db: ctx.db,
185
+ deps: collectDeps,
186
+ });
187
+ const fingerprint = computeDefinitionFingerprint(cronoton);
188
+ const fireId = recordFire({
189
+ codexCronotonId: cronoton.id,
190
+ jobId: null,
191
+ firedAt: now.toISOString(),
192
+ status: result.ok ? "success" : "failure",
193
+ requestKey: result.requestKey,
194
+ chainId: result.chainId,
195
+ errorMessage: result.error,
196
+ chainResponse: result.rawResult,
197
+ definitionFingerprint: fingerprint,
198
+ txKeys,
199
+ }, { db: ctx.db, resolveFireMode: ctx.resolveFireMode });
200
+ await ctx.onAudit({
201
+ action: result.ok ? "codex_cronoton.manual_fire" : "codex_cronoton.fire_failed",
202
+ result: result.ok ? "success" : "failure",
203
+ targetKind: "codex_cronoton",
204
+ targetId: cronoton.id,
205
+ detail: {
206
+ codexCronotonId: cronoton.id,
207
+ fireId,
208
+ actor: "ancient",
209
+ via: "manual_batch",
210
+ batchId: batch.id,
211
+ batchIndex,
212
+ batchTotal: batch.total,
213
+ scheduleKind: "recurring",
214
+ createdBy: batch.created_by,
215
+ requestKey: result.requestKey,
216
+ chainId: result.chainId,
217
+ definitionFingerprint: fingerprint,
218
+ errorMessage: result.error,
219
+ message: result.error,
220
+ },
221
+ });
222
+ if (result.ok)
223
+ firedIds.push(batch.id);
224
+ else
225
+ failedIds.push(batch.id);
226
+ }
227
+ catch (err) {
228
+ // Isolate the per-batch orchestration failure and surface the diagnostic
229
+ // (matching the Hub) rather than dropping it silently.
230
+ console.error(`khronoton tick: manual batch ${batch.id} skipped after an orchestration error`, err);
231
+ skippedIds.push(batch.id);
232
+ }
233
+ }
234
+ return { firedIds, failedIds, skippedIds, cancelledIds };
235
+ }