@ancientpantheon/khronoton-core 0.6.1 → 0.8.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.
@@ -141,7 +141,10 @@ export async function resumeCodexCronoton(ctx, req) {
141
141
  * DELETE /[id] — remove a codex cronoton. Confirm-gated. A row bound to a server
142
142
  * resolver is a SYSTEM cronoton: it is delete-locked (pause to disable instead),
143
143
  * so the handler loads the row first and refuses with 409 before the store's
144
- * unconditional delete would run (REQ-H05).
144
+ * unconditional delete would run (REQ-H05) — UNLESS an explicit `?force=1`
145
+ * (`"1"`/`"true"`) query param accompanies the request, which the operator sets
146
+ * only after accepting the system-delete warning; a forced delete is recorded in
147
+ * the audit trail as `forced: true`.
145
148
  */
146
149
  export async function deleteCodexCronoton(ctx, req) {
147
150
  return withConfirm(ctx, req, async () => {
@@ -149,7 +152,8 @@ export async function deleteCodexCronoton(ctx, req) {
149
152
  const row = storeGet(id, { db: ctx.db });
150
153
  if (!row)
151
154
  throw new CodexCronotonValidationError("not found");
152
- if (row.server_resolver) {
155
+ const force = req.query?.force === "1" || req.query?.force === "true";
156
+ if (row.server_resolver && !force) {
153
157
  return json(409, {
154
158
  error: "System cronoton — cannot be deleted. Pause it to disable instead.",
155
159
  protected: true,
@@ -161,7 +165,7 @@ export async function deleteCodexCronoton(ctx, req) {
161
165
  result: "ok",
162
166
  targetKind: "codex_cronoton",
163
167
  targetId: id,
164
- detail: { serverResolver: row.server_resolver ?? null },
168
+ detail: { serverResolver: row.server_resolver ?? null, forced: row.server_resolver ? force : false },
165
169
  });
166
170
  return json(200, { ok: true });
167
171
  });
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the sixteen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -13,7 +13,7 @@
13
13
  * Every re-export is `export type` where the symbol is a type, so the emitted
14
14
  * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
15
  */
16
- export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, } from "./read.js";
16
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, } from "./read.js";
17
17
  export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
18
18
  export type { CommitBody, CommitEnvelope, CommitSchedule } from "./cronoton.js";
19
19
  export { simulateCodexTx, executeNow, triggerCronoton, recoverFire } from "./execute.js";
@@ -3,7 +3,7 @@
3
3
  * framework-agnostic route surface over the `/server` store + executor. A
4
4
  * consumer adapts its framework's request/response into {@link HandlerRequest} /
5
5
  * {@link HandlerResponse}, injects a {@link HandlerContext} (db + runtime +
6
- * resolver + an {@link AuthSeam}), and calls the sixteen handlers below.
6
+ * resolver + an {@link AuthSeam}), and calls the seventeen handlers below.
7
7
  *
8
8
  * The read handlers keep their contract names here (aliasing their module's
9
9
  * `*Handler` implementations), so the barrel exposes the exact route contract
@@ -14,7 +14,7 @@
14
14
  * `.d.ts` stays fully erasable. Explicit `.js` extensions throughout.
15
15
  */
16
16
  // ── Read handlers (TC.2) — aliased to their contract names ────────────────────
17
- export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, } from "./read.js";
17
+ export { listHandler as listCodexCronotons, getHandler as getCodexCronoton, signersHandler as fetchSigners, firesHandler as fetchFires, resolversHandler as listResolvers, } from "./read.js";
18
18
  // ── Cronoton-lifecycle handlers (TC.3) ────────────────────────────────────────
19
19
  export { commitCodexCronoton, editCodexCronoton, pauseCodexCronoton, resumeCodexCronoton, deleteCodexCronoton, } from "./cronoton.js";
20
20
  // ── Execution handlers (TC.4) ─────────────────────────────────────────────────
@@ -21,6 +21,12 @@ export declare function listHandler(ctx: HandlerContext, request: HandlerRequest
21
21
  export declare function getHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
22
22
  /** `GET /signers` — the SECRET-FREE signer descriptors (never key material). */
23
23
  export declare function signersHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
24
+ /**
25
+ * `GET /resolvers` — the server-authoritative resolver registry: every registered
26
+ * server resolver with its `kind` and `evented` flag. Takes no params/query; the
27
+ * Builder consumes it to learn which resolver names are event-driven (scheduleless).
28
+ */
29
+ export declare function resolversHandler(ctx: HandlerContext, request: HandlerRequest): Promise<HandlerResponse>;
24
30
  /**
25
31
  * `GET /[id]/fires?limit&offset` — paginated fire history. The page size defaults
26
32
  * to 50 (REQ-G08) — overriding the store's own default of 20 — and both echoed
@@ -14,7 +14,7 @@
14
14
  */
15
15
  import { json, err, defaultSignerSource, } from "./http.js";
16
16
  import { withRead } from "./context.js";
17
- import { listCodexCronotons, getCodexCronoton, listFires, } from "../server/index.js";
17
+ import { listCodexCronotons, getCodexCronoton, listFires, listServerResolvers, } from "../server/index.js";
18
18
  /** First scalar of a query value (a repeated key arrives as an array); `undefined` if empty. */
19
19
  function firstScalar(raw) {
20
20
  const value = Array.isArray(raw) ? raw[0] : raw;
@@ -77,6 +77,14 @@ export async function signersHandler(ctx, request) {
77
77
  return json(200, { ok: true, signers });
78
78
  });
79
79
  }
80
+ /**
81
+ * `GET /resolvers` — the server-authoritative resolver registry: every registered
82
+ * server resolver with its `kind` and `evented` flag. Takes no params/query; the
83
+ * Builder consumes it to learn which resolver names are event-driven (scheduleless).
84
+ */
85
+ export async function resolversHandler(ctx, request) {
86
+ return withRead(ctx, request, async () => json(200, { ok: true, resolvers: listServerResolvers() }));
87
+ }
80
88
  /**
81
89
  * `GET /[id]/fires?limit&offset` — paginated fire history. The page size defaults
82
90
  * to 50 (REQ-G08) — overriding the store's own default of 20 — and both echoed
@@ -1,7 +1,8 @@
1
- import { L as ListCronotonsQuery, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, R as RecoverView, S as SimulateEnvelope, e as SimulateView, f as StartBatchView, g as RuntimeArgs } from '../context-D7LCfXdC.js';
2
- export { U as UseKhronotonResult, u as useKhronoton } from '../context-D7LCfXdC.js';
1
+ import { L as ListCronotonsQuery, R as ResolversView, C as CommitBody, a as CommitView, E as EditPatch, b as EditView, T as ToggleView, D as DeleteView, c as CancelBatchView, d as ExecuteView, e as RecoverView, S as SimulateEnvelope, f as SimulateView, g as StartBatchView, h as RuntimeArgs } from '../context-C1K08cmR.js';
2
+ export { U as UseKhronotonResult, u as useKhronoton } from '../context-C1K08cmR.js';
3
3
  import { C as CodexCronotonRow, a as CodexCronotonFireRow, M as ManualBatchView } from '../types-u_nUX1Bg.js';
4
4
  import 'react';
5
+ import '../seams-DapFZ4sM.js';
5
6
 
6
7
  /** The `useCronotons()` return shape — the list, its load state, and a refetch. */
7
8
  interface UseCronotonsView {
@@ -54,6 +55,15 @@ interface UseManualBatchResult {
54
55
  }
55
56
  declare function useManualBatch(id: string): UseManualBatchResult;
56
57
 
58
+ /** The `useServerResolvers()` return shape — the registry, its load state. */
59
+ interface UseServerResolversView {
60
+ /** The registered resolvers + their `evented` flag; `[]` before load / on error / when unsupported. */
61
+ resolvers: ResolversView["resolvers"];
62
+ loading: boolean;
63
+ error: Error | null;
64
+ }
65
+ declare function useServerResolvers(): UseServerResolversView;
66
+
57
67
  /** A successful action: the adapter body, untouched. */
58
68
  interface ActionOk<T> {
59
69
  ok: true;
@@ -76,7 +86,11 @@ interface GatedAction<Args extends unknown[], T> {
76
86
  type CreateAction = GatedAction<[CommitBody], CommitView>;
77
87
  type EditAction = GatedAction<[EditPatch], EditView>;
78
88
  type ToggleAction = GatedAction<[], ToggleView>;
79
- type DeleteAction = GatedAction<[], DeleteView>;
89
+ /** Run-time options for `remove.run(...)` — `force` deletes a server-resolver/system row. */
90
+ interface DeleteRunOpts {
91
+ force?: boolean;
92
+ }
93
+ type DeleteAction = GatedAction<[DeleteRunOpts?], DeleteView>;
80
94
  /** The bundle `useCronotonActions` returns. */
81
95
  interface CronotonActions {
82
96
  create: CreateAction;
@@ -140,4 +154,4 @@ declare function useRecoverFire(): UseExecuteActionResult<[
140
154
  requestKey: string
141
155
  ], RecoverView>;
142
156
 
143
- export { type ActionFail, type ActionOk, type ActionResult, type CreateAction, type CronotonActions, type DeleteAction, type EditAction, type GatedAction, type ToggleAction, type UseCronotonActionsOptions, type UseCronotonFiresOptions, type UseCronotonFiresResult, type UseCronotonView, type UseCronotonsView, type UseExecuteActionResult, type UseManualBatchResult, useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useSimulate, useStartBatch, useTrigger };
157
+ export { type ActionFail, type ActionOk, type ActionResult, type CreateAction, type CronotonActions, type DeleteAction, type EditAction, type GatedAction, type ToggleAction, type UseCronotonActionsOptions, type UseCronotonFiresOptions, type UseCronotonFiresResult, type UseCronotonView, type UseCronotonsView, type UseExecuteActionResult, type UseManualBatchResult, type UseServerResolversView, useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger };
@@ -1,2 +1,2 @@
1
- export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useSimulate, useStartBatch, useTrigger } from '../chunk-J7P2NCO4.js';
2
- export { useKhronoton } from '../chunk-5SUNXUSH.js';
1
+ export { useCancelBatch, useCronoton, useCronotonActions, useCronotonFires, useCronotons, useExecuteNow, useManualBatch, useRecoverFire, useServerResolvers, useSimulate, useStartBatch, useTrigger } from '../chunk-NNR4MYI3.js';
2
+ export { useKhronoton } from '../chunk-WLZXX2SQ.js';
@@ -1,7 +1,7 @@
1
1
  import { ReactNode } from 'react';
2
- import { H as HandlerRequest, h as HandlerResponse, K as KhronotonProviderProps, i as KhronotonAdapter, j as SignerSource } from '../context-D7LCfXdC.js';
3
- export { c as CancelBatchView, k as CodexSignerDescriptor, C as CommitBody, a as CommitView, l as ConfirmGate, m as ConfirmOpts, n as DEFAULT_EXPLORER_BASE, o as DEFAULT_PAGE_SIZE, p as DEFAULT_POLL_CADENCE_MS, D as DeleteView, E as EditPatch, b as EditView, d as ExecuteView, F as FiresQuery, q as FiresView, G as GetBatchView, r as GetCronotonView, s as KhronotonConfig, t as KhronotonSnapshot, L as ListCronotonsQuery, v as ListCronotonsView, R as RecoverView, w as RenderMultiTx, g as RuntimeArgs, x as ServerResolverOption, y as SignersView, S as SimulateEnvelope, e as SimulateView, f as StartBatchView, T as ToggleView, U as UseKhronotonResult, z as assertAdapter, A as emptySnapshot, u as useKhronoton } from '../context-D7LCfXdC.js';
4
- import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-BvPnTSmg.js';
2
+ import { H as HandlerRequest, i as HandlerResponse, K as KhronotonProviderProps, j as KhronotonAdapter, k as SignerSource } from '../context-C1K08cmR.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-C1K08cmR.js';
4
+ import { D as Database, C as ChainRuntime, K as KeyResolver, R as ResolveFireMode, O as OnAudit, a as Config } from '../seams-DapFZ4sM.js';
5
5
  export { a as CodexCronotonFireRow, C as CodexCronotonRow, M as ManualBatchView } from '../types-u_nUX1Bg.js';
6
6
 
7
7
  /**
@@ -1,5 +1,5 @@
1
- import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-5SUNXUSH.js';
2
- export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-5SUNXUSH.js';
1
+ import { assertAdapter, resolveConfig, KhronotonStaticContext, KhronotonStatusContext, NeedsConfirmError, installSchema, defaultOpenAuth, withConfirm, err, recoverFire, json, createManualBatch, manualBatchView, getCodexCronoton, validateRuntimeArgs, rowRuntimeArgKeys, applyRuntimeArgs, rowToDefinition, getServerResolver, resolveServerVars, executeCodexTransaction, CodexCronotonValidationError, deleteCodexCronoton, resumeCodexCronoton, pauseCodexCronoton, editCodexCronoton, commitCodexCronoton, withRead, listFires, listCodexCronotons, getActiveManualBatchForCronoton, cancelManualBatch, listServerResolvers, defaultSignerSource, fireByServerResolver, computeDefinitionFingerprint, recordFire, applyTerminalIntent } from '../chunk-WLZXX2SQ.js';
2
+ export { DEFAULT_EXPLORER_BASE, DEFAULT_PAGE_SIZE, DEFAULT_POLL_CADENCE_MS, NeedsConfirmError, assertAdapter, emptySnapshot, runGated, useKhronoton } from '../chunk-WLZXX2SQ.js';
3
3
  import { useRef, useState, useEffect } from 'react';
4
4
  import { jsx } from 'react/jsx-runtime';
5
5
 
@@ -120,6 +120,9 @@ function createFetchAdapter(baseUrl, opts = {}) {
120
120
  signers() {
121
121
  return request("GET", "/signers");
122
122
  },
123
+ resolvers() {
124
+ return request("GET", "/resolvers");
125
+ },
123
126
  // Lifecycle tier (confirm-gated)
124
127
  commit(body, confirm) {
125
128
  return request("POST", "", { body, confirmed: confirm?.confirmed });
@@ -134,7 +137,9 @@ function createFetchAdapter(baseUrl, opts = {}) {
134
137
  return request("PATCH", `/${id}/resume`, { confirmed: confirm?.confirmed });
135
138
  },
136
139
  delete(id, confirm) {
137
- return request("DELETE", `/${id}`, { confirmed: confirm?.confirmed });
140
+ return request("DELETE", `/${id}${confirm?.force ? "?force=1" : ""}`, {
141
+ confirmed: confirm?.confirmed
142
+ });
138
143
  },
139
144
  // Execution tier (confirm-gated; simulate/executeNow/trigger are 200-on-ok:false)
140
145
  simulate(envelope, confirm) {
@@ -228,6 +233,9 @@ async function signersHandler(ctx, request) {
228
233
  return json(200, { ok: true, signers });
229
234
  });
230
235
  }
236
+ async function resolversHandler(ctx, request) {
237
+ return withRead(ctx, request, async () => json(200, { ok: true, resolvers: listServerResolvers() }));
238
+ }
231
239
  async function firesHandler(ctx, request) {
232
240
  return withRead(ctx, request, async () => {
233
241
  const id = request.params?.id ?? "";
@@ -334,7 +342,8 @@ async function deleteCodexCronoton2(ctx, req) {
334
342
  const id = paramId(req);
335
343
  const row = getCodexCronoton(id, { db: ctx.db });
336
344
  if (!row) throw new CodexCronotonValidationError("not found");
337
- if (row.server_resolver) {
345
+ const force = req.query?.force === "1" || req.query?.force === "true";
346
+ if (row.server_resolver && !force) {
338
347
  return json(409, {
339
348
  error: "System cronoton \u2014 cannot be deleted. Pause it to disable instead.",
340
349
  protected: true
@@ -346,7 +355,7 @@ async function deleteCodexCronoton2(ctx, req) {
346
355
  result: "ok",
347
356
  targetKind: "codex_cronoton",
348
357
  targetId: id,
349
- detail: { serverResolver: row.server_resolver ?? null }
358
+ detail: { serverResolver: row.server_resolver ?? null, forced: row.server_resolver ? force : false }
350
359
  });
351
360
  return json(200, { ok: true });
352
361
  });
@@ -612,6 +621,9 @@ function createMemoryAdapter(opts) {
612
621
  signers() {
613
622
  return call(signersHandler, {});
614
623
  },
624
+ resolvers() {
625
+ return call(resolversHandler, {});
626
+ },
615
627
  // Lifecycle tier (confirm-gated)
616
628
  commit(body, confirm) {
617
629
  return call(commitCodexCronoton2, { body, confirmed: confirm?.confirmed });
@@ -630,7 +642,11 @@ function createMemoryAdapter(opts) {
630
642
  return call(resumeCodexCronoton2, { params: { id }, confirmed: confirm?.confirmed });
631
643
  },
632
644
  delete(id, confirm) {
633
- return call(deleteCodexCronoton2, { params: { id }, confirmed: confirm?.confirmed });
645
+ return call(deleteCodexCronoton2, {
646
+ params: { id },
647
+ query: confirm?.force ? { force: "1" } : void 0,
648
+ confirmed: confirm?.confirmed
649
+ });
634
650
  },
635
651
  // Execution tier (confirm-gated; simulate/executeNow/trigger are 200-on-ok:false)
636
652
  simulate(envelope, confirm) {
@@ -153,6 +153,16 @@ interface Database {
153
153
  exec(sql: string): unknown;
154
154
  prepare(sql: string): Statement;
155
155
  }
156
+ /**
157
+ * Carries the injected DB handle into store calls.
158
+ *
159
+ * Divergence from the Hub's `resolveDb(dep) = dep?.db ?? getDb()`: this package
160
+ * has no ambient `getDb()` fallback, so the handle is REQUIRED — the consumer
161
+ * always injects a handle at the call boundary.
162
+ */
163
+ interface DbDep {
164
+ db: Database;
165
+ }
156
166
  /** The structured event passed to an {@link OnAudit} sink. */
157
167
  interface AuditEvent {
158
168
  action: string;
@@ -200,4 +210,4 @@ interface Config {
200
210
  };
201
211
  }
202
212
 
203
- export type { ChainRuntime as C, Database as D, KeyResolver as K, OnAudit as O, ResolveFireMode as R, Config as a };
213
+ export type { ChainRuntime as C, Database as D, KeyResolver as K, OnAudit as O, ResolveFireMode as R, Config as a, DbDep as b };
@@ -42,6 +42,13 @@ export interface SettleOpts {
42
42
  */
43
43
  export interface SingleTxResolver {
44
44
  kind: "single-tx";
45
+ /**
46
+ * When true, this resolver is fired by an in-process EVENT, never by a
47
+ * schedule — a cronoton bound to it is scheduleless (the store forces
48
+ * `external_fireable = 1` / `next_fire_at = NULL`) and the Builder hides its
49
+ * schedule controls.
50
+ */
51
+ evented?: boolean;
45
52
  resolve(dep?: DbDep): ServerResolverResolution;
46
53
  settle(plan: unknown[], opts?: SettleOpts): void;
47
54
  }
@@ -53,6 +60,13 @@ export interface SingleTxResolver {
53
60
  */
54
61
  export interface MultiTxResolver {
55
62
  kind: "multi-tx";
63
+ /**
64
+ * When true, this resolver is fired by an in-process EVENT, never by a
65
+ * schedule — a cronoton bound to it is scheduleless (the store forces
66
+ * `external_fireable = 1` / `next_fire_at = NULL`) and the Builder hides its
67
+ * schedule controls.
68
+ */
69
+ evented?: boolean;
56
70
  run(opts: unknown): Promise<unknown>;
57
71
  }
58
72
  /** Either resolver kind; the `kind` field discriminates the union. */
@@ -65,6 +79,18 @@ export type ServerResolver = SingleTxResolver | MultiTxResolver;
65
79
  export declare function registerServerResolver(name: string, resolver: ServerResolver): void;
66
80
  /** Read a registered resolver entry (with its `kind`) by name, or `undefined`. */
67
81
  export declare function getServerResolver(name: string): ServerResolver | undefined;
82
+ /**
83
+ * Enumerate the registry as a flat, name-sorted list of `{ name, kind, evented }`
84
+ * — the server-authoritative source consumed by the `GET /resolvers` read handler
85
+ * and the Builder (to learn which resolver names are event-driven / scheduleless).
86
+ * `evented` is normalized to a boolean (`r.evented === true`) so consumers never
87
+ * see `undefined`. Sorted by `name` for deterministic responses.
88
+ */
89
+ export declare function listServerResolvers(): {
90
+ name: string;
91
+ kind: ServerResolver["kind"];
92
+ evented: boolean;
93
+ }[];
68
94
  /**
69
95
  * Resolve a named SINGLE-TX resolver's plan + payload WITHOUT firing — used by a
70
96
  * simulate/preview endpoint to show what a fire would produce. Returns `null`
@@ -37,6 +37,18 @@ export function registerServerResolver(name, resolver) {
37
37
  export function getServerResolver(name) {
38
38
  return SERVER_RESOLVERS[name];
39
39
  }
40
+ /**
41
+ * Enumerate the registry as a flat, name-sorted list of `{ name, kind, evented }`
42
+ * — the server-authoritative source consumed by the `GET /resolvers` read handler
43
+ * and the Builder (to learn which resolver names are event-driven / scheduleless).
44
+ * `evented` is normalized to a boolean (`r.evented === true`) so consumers never
45
+ * see `undefined`. Sorted by `name` for deterministic responses.
46
+ */
47
+ export function listServerResolvers() {
48
+ return Object.entries(SERVER_RESOLVERS)
49
+ .map(([name, r]) => ({ name, kind: r.kind, evented: r.evented === true }))
50
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
51
+ }
40
52
  /**
41
53
  * Resolve a named SINGLE-TX resolver's plan + payload WITHOUT firing — used by a
42
54
  * simulate/preview endpoint to show what a fire would produce. Returns `null`
@@ -18,6 +18,7 @@
18
18
  import crypto from "node:crypto";
19
19
  import { computeNextFire, InvalidScheduleConfigError, } from "../../schedule.js";
20
20
  import { runtimeArgKeysCollide } from "../pure/runtime-args.js";
21
+ import { getServerResolver } from "../resolvers.js";
21
22
  import { CodexCronotonValidationError, TerminalCronotonError } from "./errors.js";
22
23
  import { assertAutoGasGate, rowExternalFireable, rowRuntimeArgKeys, } from "./mappers.js";
23
24
  /** Compute the first next-fire, mapping engine errors to a typed reject. */
@@ -65,13 +66,30 @@ export function commitCodexCronoton(input, opts) {
65
66
  if (input.serverResolver && runtimeArgKeys.length > 0) {
66
67
  throw new CodexCronotonValidationError("server-resolver rows cannot declare runtime args");
67
68
  }
69
+ // One-resolver-one-cronoton: a server_resolver may bind AT MOST one cronoton.
70
+ // The finder returns the newest match, so a duplicate would silently shadow the
71
+ // first and fire the wrong template — reject it, naming the existing row.
72
+ if (input.serverResolver) {
73
+ const existing = findCodexCronotonIdByServerResolver(input.serverResolver, {
74
+ db: opts.db,
75
+ });
76
+ if (existing) {
77
+ throw new CodexCronotonValidationError(`server resolver "${input.serverResolver}" is already bound to cronoton ${existing} — delete it first`);
78
+ }
79
+ }
68
80
  const now = opts.now ?? new Date();
69
81
  // A SCHEDULER-OFF cronoton (externally fireable, OR declaring runtime args, OR
70
82
  // event-driven — a server-resolver the host fires via `executeNow`) fires on
71
83
  // demand, never on a timer — so it carries NO schedule: skip the next-fire
72
84
  // computation and store next_fire_at = NULL. The scheduler's
73
85
  // `next_fire_at IS NOT NULL` gate then skips it.
74
- const triggerOnly = input.externalFireable === true ||
86
+ // An EVENTED server resolver (per the registry) is host-fired on an in-process
87
+ // event, never on a timer — the store is authoritative: it forces the row
88
+ // external-fireable (external_fireable = 1) and scheduler-off, regardless of what
89
+ // the client sent, so the guarantee holds for every consumer.
90
+ const evented = getServerResolver(input.serverResolver ?? "")?.evented === true;
91
+ const externalFireable = input.externalFireable === true || evented;
92
+ const triggerOnly = externalFireable ||
75
93
  runtimeArgKeys.length > 0 ||
76
94
  input.eventDriven === true;
77
95
  const nextFireAt = triggerOnly
@@ -86,7 +104,7 @@ export function commitCodexCronoton(input, opts) {
86
104
  server_resolver, external_fireable, runtime_arg_keys, status,
87
105
  next_fire_at, last_fire_at, created_at, modified_at, created_by)
88
106
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active', ?, NULL, ?, ?, ?)`)
89
- .run(id, input.name.trim(), input.description, input.pactCode, JSON.stringify(input.config), input.payload ? JSON.stringify(input.payload) : null, JSON.stringify(input.gasPayer), JSON.stringify(input.signers), input.scheduleMode, JSON.stringify(input.scheduleConfig), input.serverResolver ?? null, input.externalFireable ? 1 : 0, runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null, nextFireAt, nowIso, nowIso, input.createdBy);
107
+ .run(id, input.name.trim(), input.description, input.pactCode, JSON.stringify(input.config), input.payload ? JSON.stringify(input.payload) : null, JSON.stringify(input.gasPayer), JSON.stringify(input.signers), input.scheduleMode, JSON.stringify(input.scheduleConfig), input.serverResolver ?? null, externalFireable ? 1 : 0, runtimeArgKeys.length > 0 ? JSON.stringify(runtimeArgKeys) : null, nextFireAt, nowIso, nowIso, input.createdBy);
90
108
  return { id, nextFireAt };
91
109
  }
92
110
  export function getCodexCronoton(id, dep) {
@@ -204,35 +222,56 @@ export function editCodexCronoton(id, patch, opts) {
204
222
  scheduleChanged = true;
205
223
  changedFields.push("schedule");
206
224
  }
207
- // A trigger-only row (externally fireable OR runtime-arg) has NO schedule (its
208
- // next_fire_at is NULL and the scheduler skips it) — never resurrect a next-fire
209
- // for it, even if a schedule patch slips through. Keep next_fire_at as-is (NULL).
210
- const rowTriggerOnly = rowExternalFireable(row) || rowRuntimeArgKeys(row).length > 0;
225
+ // Derive EVENTED-ness of both the PATCHED (post-edit) resolver and the row's
226
+ // CURRENT (pre-edit) resolver from the registry (authoritative). An edit that
227
+ // repoints onto an evented resolver — even WITHOUT the client eventDriven flag —
228
+ // must force scheduler-off + external-fireable, mirroring commit; an edit that
229
+ // repoints AWAY from an evented resolver must shed the evented-forced
230
+ // external_fireable and re-arm a real schedule.
231
+ const resolverName = patch.serverResolver !== undefined ? patch.serverResolver : row.server_resolver;
232
+ const evented = getServerResolver(resolverName ?? "")?.evented === true;
233
+ const prevEvented = getServerResolver(row.server_resolver ?? "")?.evented === true;
234
+ // The row's external_fireable is "genuine" (a user-set HMAC-fire flag to preserve)
235
+ // ONLY when it was NOT forced by a now-departed evented resolver. This lets a plain
236
+ // edit of a genuinely external-fireable row keep its flag, while an evented→
237
+ // non-evented repoint correctly drops the evented-forced flag.
238
+ const genuineExternalFireable = Boolean(rowExternalFireable(row)) && !prevEvented;
239
+ const rowSchedulerOff = evented || rowRuntimeArgKeys(row).length > 0 || genuineExternalFireable;
240
+ // A row that just LEFT an evented resolver must re-arm its schedule even if the
241
+ // edit carried no explicit schedule patch (else it would sit external_fireable=0 +
242
+ // next_fire_at=NULL — a dead row that never fires).
243
+ const eventedDeparted = prevEvented && !evented;
211
244
  // An event-driven edit forces the row scheduler-off (next_fire_at NULL). There is
212
- // no persisted event_driven column, so `rowTriggerOnly` can't see it — this patch
213
- // signal takes precedence and covers BOTH an event-driven→event-driven edit (keep
214
- // NULL) and a scheduled→event-driven conversion (clear the row's stale non-null
215
- // next_fire_at). Marking "schedule" ensures the UPDATE runs even when the clear is
216
- // the only change (a pure conversion), so the early-out below doesn't skip the write.
217
- if (patch.eventDriven === true) {
245
+ // no persisted event_driven column, so `rowSchedulerOff` can't see the departed
246
+ // case via the row alone — the patch/registry signals above drive this. Marking
247
+ // "schedule" ensures the UPDATE runs even when the next_fire_at change is the only
248
+ // change, so the early-out below doesn't skip the write.
249
+ if (patch.eventDriven === true || evented) {
218
250
  if (nextFireAt !== null && !changedFields.includes("schedule")) {
219
251
  changedFields.push("schedule");
220
252
  }
221
253
  nextFireAt = null;
222
254
  }
223
- else if (scheduleChanged && !rowTriggerOnly) {
255
+ else if ((scheduleChanged || eventedDeparted) && !rowSchedulerOff) {
224
256
  const next = computeNextOrReject(nextScheduleMode, JSON.parse(nextScheduleConfigJson), opts.now ?? new Date());
225
257
  nextFireAt = next.toISOString();
258
+ if (!changedFields.includes("schedule"))
259
+ changedFields.push("schedule");
226
260
  }
227
261
  if (changedFields.length === 0) {
228
262
  return { changedFields, nextFireAt };
229
263
  }
264
+ // An evented edit forces external_fireable = 1 (mirroring commit). Otherwise the
265
+ // edit PRESERVES a GENUINE (user-set) external-fireable flag, but DROPS one that
266
+ // was only forced by a now-departed evented resolver — so an evented→non-evented
267
+ // repoint doesn't leave the row permanently external-fireable/scheduler-off.
268
+ const nextExternalFireable = evented ? 1 : genuineExternalFireable ? 1 : 0;
230
269
  db.prepare(`UPDATE codex_cronotons
231
270
  SET name = ?, description = ?, pact_code = ?, config_json = ?,
232
271
  payload_json = ?, gas_payer_json = ?, signers_json = ?,
233
272
  schedule_mode = ?, schedule_config_json = ?, server_resolver = ?,
234
- next_fire_at = ?, modified_at = ?
235
- WHERE id = ?`).run(nextName, nextDescription, nextPactCode, nextConfigJson, nextPayloadJson, nextGasPayerJson, nextSignersJson, nextScheduleMode, nextScheduleConfigJson, nextServerResolver, nextFireAt, (opts.now ?? new Date()).toISOString(), id);
273
+ external_fireable = ?, next_fire_at = ?, modified_at = ?
274
+ WHERE id = ?`).run(nextName, nextDescription, nextPactCode, nextConfigJson, nextPayloadJson, nextGasPayerJson, nextSignersJson, nextScheduleMode, nextScheduleConfigJson, nextServerResolver, nextExternalFireable, nextFireAt, (opts.now ?? new Date()).toISOString(), id);
236
275
  return { changedFields, nextFireAt };
237
276
  }
238
277
  // ── Pause / resume / delete ──────────────────────────────────────────────────
package/dist/ui/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-J7P2NCO4.js';
2
- import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-5SUNXUSH.js';
1
+ import { useCronotons, useCronoton, useCronotonActions, useExecuteNow, useSimulate, useServerResolvers, useManualBatch, useStartBatch, useCancelBatch, useTrigger, useCronotonFires, useRecoverFire } from '../chunk-NNR4MYI3.js';
2
+ import { useKhronotonAdapter, useKhronotonConfig, parseRuntimeArgKeys, summariseSchedule, KhronotonStaticContext, useKhronoton, computeNextFire, InvalidScheduleConfigError } from '../chunk-WLZXX2SQ.js';
3
3
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
4
4
  import { lazy, forwardRef, createElement, useState, useEffect, useCallback, Suspense, useContext } from 'react';
5
5
 
@@ -312,7 +312,7 @@ function Badge({ children, style, ...rest }) {
312
312
 
313
313
  // src/ui/access.ts
314
314
  var ADMIN_ONLY_TITLE = "Ancient admins only";
315
- var SYSTEM_CRONOTON_DELETE_TITLE = "System cronoton \u2014 cannot be deleted. Pause it to disable instead.";
315
+ var SYSTEM_CRONOTON_DELETE_TITLE = "System cronoton \u2014 deleting removes the automaton's template; you'll be warned first.";
316
316
  var TERMINAL_PAUSE_RESUME_TITLE = "Terminal cronotons cannot be paused or resumed";
317
317
  var TERMINAL_EXECUTE_TITLE = "Terminal cronotons cannot be executed";
318
318
  var BATCH_ACTIVE_TITLE = "A batch is running \u2014 wait for it to finish or cancel it";
@@ -326,13 +326,13 @@ function canMutate(access) {
326
326
  var ENABLED = { disabled: false, title: void 0 };
327
327
  var WORKING = { disabled: true, title: void 0 };
328
328
  function deleteDisabled(access, row, opts = {}) {
329
- if (row.server_resolver) {
330
- return { disabled: true, title: SYSTEM_CRONOTON_DELETE_TITLE };
331
- }
332
329
  if (!canMutate(access)) {
333
330
  return { disabled: true, title: ADMIN_ONLY_TITLE };
334
331
  }
335
332
  if (opts.working) return WORKING;
333
+ if (row.server_resolver) {
334
+ return { disabled: false, title: SYSTEM_CRONOTON_DELETE_TITLE };
335
+ }
336
336
  return ENABLED;
337
337
  }
338
338
  function pauseResumeDisabled(access, row, opts) {
@@ -373,6 +373,9 @@ function newCronotonTier(access) {
373
373
  function deleteConfirm(name) {
374
374
  return `Delete codex cronoton "${name}"? Fire history is removed too.`;
375
375
  }
376
+ function deleteSystemConfirm(name, serverResolver) {
377
+ return `This is the automaton's "${serverResolver}" template. Deleting it stops that capability until it's recreated. Delete "${name}" anyway?`;
378
+ }
376
379
  function deletePasswordConfirm(name) {
377
380
  return `Confirm to delete codex cronoton "${name}".`;
378
381
  }
@@ -459,6 +462,11 @@ function RelativeTime({ iso, className }) {
459
462
  }, [iso, withinMinute]);
460
463
  return /* @__PURE__ */ jsx("time", { dateTime: iso, title: iso, className, style: { color: "var(--khr-text-dim)" }, children: formatRelative(iso, nowMs) });
461
464
  }
465
+
466
+ // src/ui/row-derive.ts
467
+ function isTriggerOnly(row) {
468
+ return row.external_fireable === 1 || parseRuntimeArgKeys(row.runtime_arg_keys).length > 0;
469
+ }
462
470
  var DEFAULT_LIST_ROBOTS = "noindex,nofollow";
463
471
  var DIM = { color: "var(--khr-text-dim)" };
464
472
  var MONO = {
@@ -473,16 +481,6 @@ function pactPreview(pactCode) {
473
481
  if (collapsed === "") return "(empty)";
474
482
  return collapsed.length > PACT_PREVIEW_MAX ? `${collapsed.slice(0, PACT_PREVIEW_MAX)}\u2026` : collapsed;
475
483
  }
476
- function isTriggerOnly(row) {
477
- const raw = row.runtime_arg_keys;
478
- if (!raw) return false;
479
- try {
480
- const keys = JSON.parse(raw);
481
- return Array.isArray(keys) && keys.length > 0;
482
- } catch {
483
- return false;
484
- }
485
- }
486
484
  function scheduleLine(row) {
487
485
  try {
488
486
  const config = JSON.parse(row.schedule_config_json);
@@ -513,9 +511,14 @@ function CronotonListRowView({
513
511
  const pr = pauseResumeDisabled(access, row, { working });
514
512
  const ex = executeDisabled(access, row, { working, batchActive: false });
515
513
  const handleDelete = () => {
514
+ const systemResolver = row.server_resolver;
515
+ const firstPrompt = systemResolver ? deleteSystemConfirm(row.name, systemResolver) : deleteConfirm(row.name);
516
516
  void withConfirm(
517
- deleteConfirm(row.name),
518
- () => withConfirm(deletePasswordConfirm(row.name), () => actions.remove.run())
517
+ firstPrompt,
518
+ () => withConfirm(
519
+ deletePasswordConfirm(row.name),
520
+ () => actions.remove.run(systemResolver ? { force: true } : void 0)
521
+ )
519
522
  );
520
523
  };
521
524
  const handleToggle = () => {
@@ -564,7 +567,7 @@ function CronotonListRowView({
564
567
  /* @__PURE__ */ jsx("div", { style: MONO, children: pactPreview(row.pact_code) }),
565
568
  /* @__PURE__ */ jsx("div", { style: { ...DIM, fontSize: "11px", marginTop: "3px" }, children: isTriggerOnly(row) ? "External trigger" : scheduleLine(row) })
566
569
  ] }),
567
- /* @__PURE__ */ jsx(Cell, { children: row.next_fire_at ? /* @__PURE__ */ jsx(RelativeTime, { iso: row.next_fire_at }) : EM_DASH }),
570
+ /* @__PURE__ */ jsx(Cell, { children: isTriggerOnly(row) ? /* @__PURE__ */ jsx("span", { style: DIM, children: "Evented" }) : row.next_fire_at ? /* @__PURE__ */ jsx(RelativeTime, { iso: row.next_fire_at }) : EM_DASH }),
568
571
  /* @__PURE__ */ jsx(Cell, { children: lastFireCell(row) }),
569
572
  /* @__PURE__ */ jsx(Cell, { children: /* @__PURE__ */ jsx(CronotonStatusBadge, { status: row.status }) }),
570
573
  /* @__PURE__ */ jsx(Cell, { children: access.tier === "logged-out" ? /* @__PURE__ */ jsx("span", { style: { ...DIM, fontSize: "11px" }, children: "view only" }) : /* @__PURE__ */ jsxs("div", { style: { display: "flex", gap: "6px", flexWrap: "wrap" }, children: [
@@ -1233,7 +1236,7 @@ function Loaded({
1233
1236
  const name = row.name;
1234
1237
  const terminal = TERMINAL_STATUSES2.has(row.status);
1235
1238
  const runtimeArgKeys = parseRuntimeArgKeys(row.runtime_arg_keys);
1236
- const triggerOnly = runtimeArgKeys.length > 0;
1239
+ const triggerOnly = isTriggerOnly(row);
1237
1240
  const working = actions.pause.pending || actions.resume.pending || actions.remove.pending || execute.pending;
1238
1241
  const isPaused = row.status === "paused";
1239
1242
  const toggle = isPaused ? actions.resume : actions.pause;
@@ -1243,11 +1246,15 @@ function Loaded({
1243
1246
  const pr = pauseResumeDisabled(access, row, { working });
1244
1247
  const ex = executeDisabled(access, row, { working, batchActive });
1245
1248
  const handleDelete = () => {
1249
+ const systemResolver = row.server_resolver;
1250
+ const firstPrompt = systemResolver ? deleteSystemConfirm(name, systemResolver) : deleteConfirm(name);
1246
1251
  void withConfirm(
1247
- deleteConfirm(name),
1248
- () => withConfirm(deletePasswordConfirm(name), () => actions.remove.run(), {
1249
- onSuccess: onNavigateToList
1250
- }),
1252
+ firstPrompt,
1253
+ () => withConfirm(
1254
+ deletePasswordConfirm(name),
1255
+ () => actions.remove.run(systemResolver ? { force: true } : void 0),
1256
+ { onSuccess: onNavigateToList }
1257
+ ),
1251
1258
  { alert: () => {
1252
1259
  } }
1253
1260
  );
@@ -1303,7 +1310,7 @@ function Loaded({
1303
1310
  }
1304
1311
  ) : null,
1305
1312
  /* @__PURE__ */ jsx(Card, { style: { marginTop: "18px", padding: "16px" }, children: /* @__PURE__ */ jsxs("div", { style: GRID_STYLE, children: [
1306
- /* @__PURE__ */ jsx(MetaCell, { label: "Schedule", children: triggerOnly ? "Trigger-only \u2014 no schedule" : scheduleLine2(row) }),
1313
+ /* @__PURE__ */ jsx(MetaCell, { label: "Schedule", children: triggerOnly ? "Evented" : scheduleLine2(row) }),
1307
1314
  /* @__PURE__ */ jsx(MetaCell, { label: "Status", children: /* @__PURE__ */ jsx(CronotonStatusBadge, { status: row.status }) }),
1308
1315
  /* @__PURE__ */ jsx(MetaCell, { label: "Next fire", children: /* @__PURE__ */ jsx(InstantCell, { iso: row.next_fire_at }) }),
1309
1316
  /* @__PURE__ */ jsx(MetaCell, { label: "Last fire", children: /* @__PURE__ */ jsx(InstantCell, { iso: row.last_fire_at }) }),
@@ -3648,6 +3655,7 @@ function Builder({
3648
3655
  const config = useKhronotonConfig();
3649
3656
  const actions = useCronotonActions(editId);
3650
3657
  const sim = useSimulate();
3658
+ const { resolvers } = useServerResolvers();
3651
3659
  const [state, setState] = useState(() => makeEmptyBuilderState());
3652
3660
  const [signers, setSigners] = useState([]);
3653
3661
  const [activeTab, setActiveTab] = useState("config");
@@ -3656,8 +3664,9 @@ function Builder({
3656
3664
  const [loadedEditId, setLoadedEditId] = useState(void 0);
3657
3665
  const isEdit = Boolean(editId);
3658
3666
  const editReady = !editId || loadedEditId === editId;
3667
+ const eventedNames = new Set(resolvers.filter((r) => r.evented).map((r) => r.name));
3659
3668
  const eventDrivenResolver = Boolean(
3660
- state.serverResolver && config.serverResolverOptions.find((o) => o.value === state.serverResolver)?.eventDriven
3669
+ state.serverResolver && (eventedNames.has(state.serverResolver) || config.serverResolverOptions.find((o) => o.value === state.serverResolver)?.eventDriven)
3661
3670
  );
3662
3671
  useEffect(() => {
3663
3672
  let active = true;
@@ -3693,6 +3702,7 @@ function Builder({
3693
3702
  setCommitting(true);
3694
3703
  try {
3695
3704
  const body = builderToCommit(state, { eventDriven: eventDrivenResolver });
3705
+ if (eventDrivenResolver) body.envelope.externalFireable = true;
3696
3706
  if (isEdit && editId) {
3697
3707
  const res = await actions.edit.run(body);
3698
3708
  if (res.ok) onDone?.(editId);