@niscorp/tide 0.1.2 → 0.1.4

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 CHANGED
@@ -1,5 +1,54 @@
1
1
  # @niscorp/tide
2
2
 
3
+ ## 0.1.4
4
+
5
+ ### Patch Changes
6
+
7
+ - e9ad028: DOCS and DESIGN say what `catchUp: 'run'` does under `overlap: 'skip'`. Both are the defaults, and DOCS said `'run'` "fires every missed occurrence". It opens a run for each, and `overlap` is then asked of every one of them: occurrences missed together come due in one `advance` and are repeats of one another, so the oldest runs and each later one, the one that is on time included, is recorded `skipped` with an overlap note and a `run.skipped` event. The report's `skippedOccurrences` counts catch-up decisions and does not count those. `overlap: 'allow'` runs each missed occurrence (with `order: 'serial'`, one task at a time); `catchUp: 'latest'` runs only the newest. A test now holds this, and a source comment says it. No code changed.
8
+
9
+ **What to change:** nothing. A clock reflex on the default policy that should run every occurrence it missed says `overlap: 'allow'`.
10
+
11
+ - 1dfab19: DOCS.md says which occurrence `preview()` shows and what `fired` means. For a clock reflex it is the most recent occurrence at or before `now` (a one-shot's own date, even when that is still ahead), whether or not the reflex was armed then or is enabled now, so an `advance` at the same `now` may create no run. `fired: false` means `when` did not match the fact passed in or the fan-out failed; `fired: true` does not say a run is due. No code changed.
12
+
13
+ **What to change:** nothing.
14
+
15
+ ## 0.1.3
16
+
17
+ ### Patch Changes
18
+
19
+ - fe30458: Every package exports its `package.json`, so an app can say which version of a package it runs by reading it from the package:
20
+
21
+ ```ts
22
+ import prism from '@niscorp/prism/package.json' with { type: 'json' };
23
+ prism.version; // the version that is installed, not the range that asked for it
24
+ ```
25
+
26
+ Until now the `exports` map hid it, and the only way to the version was a path into `node_modules`. `check:packages` installs the tarballs and reads every package's version this way.
27
+
28
+ **What to change:** nothing. An app that read a version by path can read it by name.
29
+
30
+ - fc31d1d: The memory store keeps no key for a value that was never given. A row appended with `as: undefined` — every fact a host ingests — kept the key in `createMemoryStore()` and has none when it is read back from a database (moss's store). So a transform that looks at which keys a fact has saw two different facts: Prism's `$has`, `$keys` and `$entriesOf` answered differently over the two. And a transform that takes plain JSON (`prismTransform`) refused every fact-triggered reflex under the memory store, where a refused `when` is recorded as `fact.unmatched` and the reflex does not fire. A `cas` that sets `undefined` already removed the key; an append now does the same. `STORE_CONTRACT` is unchanged.
31
+
32
+ The README's quick example type-checks under `strict`, and its install block covers what it imports. It passes `prismTransform` from `@niscorp/prism` as the transform (`evaluate(config, source)` did not compile: a `Row` is not a `JsonValue`), its preview no longer reads a field off an `unknown` input, and the install block adds `@niscorp/prism` and `@niscorp/strata`. DESIGN.md's plain-Node example follows.
33
+
34
+ **What to change:** nothing in an app. A check that compares a memory-store row key for key against an object that spells out `undefined` values (`toStrictEqual`) leaves those keys out.
35
+
36
+ - 18626f8: `retry()` takes its task off the run's `failed` count whatever state the run is in.
37
+
38
+ The count used to come down only together with the rewind from `settled` to `fanned`. So the second of two tasks retried before either ran again, or a task retried while its run was still going, was reopened with `failed` left one too high. Two things followed: a run of six that ended with every task `done` said `done 6, failed 1`; and a run counting a failure it no longer had reached its total one task early, settled, and minted its run fact with false counts while a task was still pending — a reflex on `{ fact: { run } }` fired on it.
39
+
40
+ The count now comes down unconditionally, in the same transaction as the reopen; only the rewind waits for a settled run.
41
+
42
+ **What to change:** nothing. A host that retried failed tasks one at a time, with an `advance` between, to keep the counts right can retry them together.
43
+
44
+ - d2f0357: A run settles when its last tasks land at the same moment.
45
+
46
+ Recording an attempt read the run, decided whether it was complete, and then wrote the count. Two landings at once — two instances on one store, or two overlapping `advance` calls — each read the run before the other's count was in; neither settled it, and it stayed `fanned` with every task `done`. No run fact was minted, and a reflex with `overlap: 'skip'` recorded every later firing as skipped.
47
+
48
+ The count is now written first and the run read after it, and the run is settled by a `cas` from `fanned`, so it settles once. Nothing in the store contract changes: it uses `cas` and `query` as they are.
49
+
50
+ **What to change:** nothing.
51
+
3
52
  ## 0.1.2
4
53
 
5
54
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -356,6 +356,13 @@ on `(reflexId, cause)`, task claims are exactly-once through the store contract,
356
356
  non-monotonic `now` (clock skew between hosts) merely delays work — it cannot
357
357
  duplicate it.
358
358
 
359
+ **⟲ A run's last landings raced on one read.** Recording an attempt read the run,
360
+ decided "complete" from what it read, and then wrote the count. Two landings in the
361
+ same moment each read the run before the other's count was in: neither settled it, and
362
+ it stayed `fanned` with every task done — no run fact, and an `overlap: 'skip'` reflex
363
+ that never started again. The count is now written first and the run read after it, and
364
+ the run is settled by a `cas` from `fanned`, so it settles once.
365
+
359
366
  **⟲ There was a poll trigger, and there was a beat.** Polls existed for hosts with no
360
367
  write choke point: run a selection on an interval, diff a cursor, mint write facts for
361
368
  the delta. In this stack the DAL is the choke point — every application write becomes
@@ -468,6 +475,12 @@ The requirements doc calls this "the part that must not be hand-waved." In order
468
475
  failed, and re-settling must not send it again — and it is answered by `drained`, a
469
476
  flag on the run recording that its settlement has been announced. The run rewinds;
470
477
  the announcement does not repeat.
478
+ - **`retry()` takes its task off the count whatever the run is doing, and ⟲ it did
479
+ not.** The decrement rode on the rewind, and the rewind expects a `settled` run: the
480
+ second of two retries, or a retry pressed while the run was still going, reopened its
481
+ task and left `failed` one too high. The run then reached its total a task early — it
482
+ settled, and announced counts that were false, with work still out. The count now
483
+ comes down unconditionally; only the rewind waits for `settled`.
471
484
  - **Attempts are fenced.** A timeout marks the attempt failed and schedules a retry —
472
485
  but the timed-out effect may still be running. Each claim mints a token; recording a
473
486
  result requires the token to still be current, so a zombie completion is discarded
@@ -513,7 +526,10 @@ The requirements doc calls this "the part that must not be hand-waved." In order
513
526
  - **Catch-up is authored, not guessed.** After downtime, `'run'` fires missed
514
527
  occurrences late, `'skip'` drops them, `'latest'` fires only the most recent of
515
528
  several missed. Each leaves a run row saying which happened — a skipped run is a
516
- recorded decision. When a single advance would exceed the per-call cap, the watermark
529
+ recorded decision. `overlap` still governs what `'run'` opens: occurrences missed
530
+ together are due in one advance and are repeats of one another, so under the default
531
+ `overlap: 'skip'` the oldest runs and the rest are recorded as overlap skips, and it
532
+ is `overlap: 'allow'` that runs each. When a single advance would exceed the per-call cap, the watermark
517
533
  stops at the last occurrence actually materialized: **⟲** it used to jump to `now`
518
534
  regardless, so everything past the cap was unreachable forever with no row saying it
519
535
  had existed.
@@ -825,7 +841,7 @@ destructuring it produced a transaction that failed inside the library.
825
841
  ```ts
826
842
  const tide = createTide({
827
843
  store: createMemoryStore(), // or your own, held to STORE_CONTRACT
828
- transform: (config, source) => evaluate(config, source), // prism, or your own
844
+ transform: prismTransform, // prism, or your own
829
845
  select: async function* (q) { yield* (await pg.query(q.sql, q.params)).rows; },
830
846
  effects: {
831
847
  'mail.send': { run: (input) => mailer.send(input) },
package/DOCS.md CHANGED
@@ -221,9 +221,19 @@ type Policy = {
221
221
  event that exists exactly once, so it always opens a run whatever this says —
222
222
  discarding it would be data loss, and the tool for bounding concurrency
223
223
  without discarding is `order: 'serial'`, which queues.
224
- - **catchUp** — after downtime: `'run'` fires every missed occurrence,
224
+ - **catchUp** — after downtime: `'run'` opens a run for every missed occurrence,
225
225
  `'latest'` fires only the most recent, `'skip'` fires only what is inside
226
226
  `lateMs`. Every decision leaves a run row saying which happened.
227
+
228
+ `overlap` is then asked of each run `catchUp` opens, and the two defaults meet
229
+ here. Occurrences missed together come due in one `advance` and are repeats of
230
+ one another, so under `overlap: 'skip'` the **oldest** runs and every later
231
+ one, the one that is on time included, is recorded `skipped` with an overlap
232
+ note and a `run.skipped` event. The report's `skippedOccurrences` counts
233
+ catch-up decisions and does not count those. To run each missed occurrence,
234
+ say `overlap: 'allow'` (with `order: 'serial'` they run one task at a time); to
235
+ run only the newest, say `catchUp: 'latest'`. `catchUp: 'skip'` meets the same
236
+ rule when `lateMs` spans more than one occurrence.
227
237
  - **order: 'serial'** — one in-flight task at a time for that reflex. Enforced
228
238
  inside the claim, not by a filter applied around it.
229
239
 
@@ -240,7 +250,13 @@ the reflex selects what changed. Mechanisms that already exist, and no table.
240
250
 
241
251
  A template is a transform-config slot inside a reflex — `effect.input`, `when`
242
252
  and `select.query`. Tide stores, diffs and hashes them but never interprets
243
- them: they go to the `transform` seam verbatim (under moss, Prism).
253
+ them: they go to the `transform` seam verbatim (under moss, Prism —
254
+ `prismTransform` from `@niscorp/prism` fits the seam as it is).
255
+
256
+ What tide puts in `$` itself is plain JSON: a fact carries no key for a value
257
+ it was never given, in the memory store as in a database. What the host handed
258
+ over is the host's — a `row` its `select` answered, a write fact's `row`, a
259
+ signal's `payload`.
244
260
 
245
261
  ```
246
262
  $ = { params, // the reflex's knobs
@@ -392,8 +408,10 @@ its `payload` and `by` (default `'operator'`) recorded. Works on a
392
408
  retry(taskId, now): Promise<boolean>
393
409
  ```
394
410
  Reopens a `failed` task **and rewinds its run** from `settled` back to `fanned`,
395
- in one transaction, so the next `advance` actually claims it. `false` when the
396
- task does not exist or is not `failed`. The run keeps
411
+ in one transaction, so the next `advance` actually claims it. The task comes off
412
+ the run's `failed` count whether or not the run had settled, so retrying several
413
+ tasks at once, or one while the run is still going, leaves the counts true.
414
+ `false` when the task does not exist or is not `failed`. The run keeps
397
415
  `drained`, so re-settling does not announce a second time: the digest that
398
416
  already went out saying twelve failed is not sent again.
399
417
 
@@ -403,7 +421,12 @@ preview(reflexId, { now, fact? }): Promise<PreviewReport>
403
421
  Runs the real pipeline against real data and stubs exactly one function, the
404
422
  effect executor. Writes nothing. Returns the occurrence or fact, the selected
405
423
  rows by name, each unit's resolved input, and whatever the handler's `preview`
406
- hook renders.
424
+ hook renders. For a clock reflex the occurrence is the most recent one at or
425
+ before `now` (for a one-shot, its one date, even when that is still ahead),
426
+ whether or not the reflex was armed then or is enabled now, so an `advance` at
427
+ the same `now` may create no run. `fired` is `false`, with a `reason`, when
428
+ `when` does not match the `fact` passed in or the fan-out fails (the selection
429
+ throws, a unit key repeats); `true` does not say a run is due.
407
430
 
408
431
  ```typescript
409
432
  graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, warnings } over what is loaded
package/README.md CHANGED
@@ -8,24 +8,26 @@ Every nisc package answers one question: vex answers *what*, nova *how it looks*
8
8
 
9
9
  ```bash
10
10
  pnpm add @niscorp/tide zod
11
+ # The quick example fills the transform seam with Prism:
12
+ pnpm add @niscorp/prism @niscorp/strata
11
13
  ```
12
14
 
13
- `zod` is the only required peer; `@niscorp/cortex` is an optional one, used only by `@niscorp/tide/agent`. Storage, selection, transformation, effects and identity are seams the host fills.
15
+ `zod` is the only required peer; `@niscorp/cortex` is an optional one, used only by `@niscorp/tide/agent`. Storage, selection, transformation, effects and identity are seams the host fills — the example below fills transformation with Prism, which has `@niscorp/strata` as a peer of its own.
14
16
 
15
17
  ## Quick example
16
18
 
17
19
  ```typescript
18
20
  import { createTide, createMemoryStore } from '@niscorp/tide';
19
- import { evaluate } from '@niscorp/prism';
21
+ import { prismTransform } from '@niscorp/prism';
20
22
 
21
23
  const tide = createTide({
22
24
  store: createMemoryStore(),
23
- transform: (config, source) => evaluate(config, source),
25
+ transform: prismTransform,
24
26
  select: async (query) => db.rows(query),
25
27
  effects: {
26
28
  'mail.send': {
27
29
  run: (input) => mailer.send(input),
28
- preview: (input) => ({ channel: 'email', to: input.to }),
30
+ preview: (input) => ({ channel: 'email', input }),
29
31
  },
30
32
  },
31
33
  });
package/dist/agent.cjs CHANGED
@@ -59,8 +59,11 @@ var PolicySchema = zod.z.object({
59
59
  // billing run still going at the next tick must not double-start.
60
60
  overlap: zod.z.enum(["skip", "allow"]).default("skip"),
61
61
  catchUp: zod.z.enum(["run", "skip", "latest"]).default("run"),
62
- // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' fires
63
- // everything and 'latest' keeps the newest regardless of age.
62
+ // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' opens
63
+ // everything and 'latest' keeps the newest regardless of age. What
64
+ // `catchUp` opens still passes `overlap`: occurrences missed together are
65
+ // repeats of one another, so under 'skip' the oldest runs and the rest
66
+ // are recorded as overlap skips.
64
67
  lateMs: zod.z.number().int().positive().default(36e5),
65
68
  order: zod.z.enum(["any", "serial"]).default("any")
66
69
  }).strict();
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/reflex.schema.ts","../src/agent/reflex-agent.ts"],"names":["z","defineAgent"],"mappings":";;;;;;AAYO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AAEb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC,CAAA;AAE/D,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,EAAA,EAAIA,KAAA,CACD,KAAA,CAAM,CAACA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,IAAI,EAAE,CAAA,EAAGA,KAAA,CAAE,IAAA,CAAK,QAAQ,CAAA,EAAGA,KAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACjF,QAAA,EAAS,CACT,SAAS,yGAA0F,CAAA;AAAA,EACtG,EAAA,EAAIA,MAAE,MAAA,EAAO,CAAE,MAAM,IAAI,CAAA,CAAE,SAAS,iCAAiC,CAAA;AAAA,EACrE,EAAA,EAAIA,KAAA,CAAE,MAAA,EAAO,CAAE,SAAS,qBAAqB;AAC/C,CAAC,EACA,MAAA,EAAO,CACP,WAAA,CAAY,CAAC,OAAO,GAAA,KAAQ;AAC3B,EAAA,MAAM,IAAA,GAAO,CAAC,OAAA,KAAoB,GAAA,CAA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AAA,CAAE,KAAK,IAAI,CAAA;AACnH,EAAA,OAAO,CAAA,eAAA,EAAkB,MAAA,CAAO,IAAI,CAAA,iCAAA,EAA+B,MAAM,CAAA,CAAA,CAAA;AAC3E;AAKO,IAAM,iBAAA,GAAoB,CAAC,MAAA,KAChCC,kBAAA,CAA0B;AAAA,EACxB,EAAA,EAAI,aAAA;AAAA,EACJ,WAAA,EAAa,kGAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA,EACd,SAAS,CAAC,MAAM,eAAA,CAAgB,MAAA,CAAO,OAAO,CAAC,CAAA;AAAA,EAC/C,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ,eAAe,MAAM,CAAA;AAAA;AAAA;AAAA,IAG7B,QAAA,EAAU,CAAC,QAAA,KAAa;AACtB,MAAA,IAAI,CAAC,QAAQ,QAAA,CAAS,IAAI,GAAG,OAAO,EAAE,IAAI,IAAA,EAAK;AAC/C,MAAA,MAAM,OAAA,GAAU,aAAA,CAAc,MAAA,CAAO,OAAA,EAAS,SAAS,IAAI,CAAA;AAC3D,MAAA,OAAO,OAAA,KAAY,SAAY,EAAE,EAAA,EAAI,MAAK,GAAI,EAAE,OAAO,OAAA,EAAQ;AAAA,IACjE;AAAA;AAEJ,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Triggers — four kinds, closed.\n//\n// Structured on purpose: a reflex is shown to the operator it\n// affects, and `{ every: 'month', on: 1, at: '03:00' }` is\n// reviewable by the person it bills where `0 3 1 * *` is a\n// shibboleth. Cron-string sugar belongs in tooling, never in the\n// stored artifact.\n// ═══════════════════════════════════════════════════════════════\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\n// Seconds are optional: a one-shot can name the second it fires on.\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.string().regex(MMDD)])\n .optional()\n .describe('week → a weekday; month → 1..31 (clamped to month end); year → \"MM-DD\". Omitted for day.'),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n if (clock.every === 'week' && !(typeof clock.on === 'string' && WEEKDAYS.some((d) => d === clock.on)))\n fail('a weekly clock needs `on` as a weekday (mon..sun)');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\n// There is NO poll trigger, and the absence is a decision. Polls existed\n// for hosts with no write choke point — run a selection, diff a cursor,\n// mint write facts for the delta. In this stack the host's DAL IS the\n// choke point: every application write becomes a fact at the vex bridge,\n// so a poll could only ever re-discover what was already pushed, one\n// interval late. An external source with no choke point enters through an\n// importer that ingests write facts at the door — the same shape, without\n// a reflex secretly re-querying.\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\n// ── narrowing helpers: the union is structural, so every consumer\n// would otherwise re-derive these three checks ───────────────────\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Policy — the execution semantics, as authored data.\n//\n// Everything the requirements doc said \"must not be hand-waved\",\n// declared per reflex rather than guessed by the engine.\n// ═══════════════════════════════════════════════════════════════\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\n// THERE IS NO COALESCE, and its absence is the design.\n//\n// It cost two port methods, a table, an exactly-once promise and a\n// `DELETE … RETURNING` on every tick, and nothing ever set it — its only\n// driver was one test. A digest that genuinely needs batching is a DELAYED\n// RUN: the first fact of a group mints one at `now + window` with\n// `cause: 'coalesce:<key>:<start>'`, the rest collide on\n// UNIQUE(reflexId, cause) and are refused, and when it comes due the reflex\n// selects what changed. Mechanisms that already exist, and no new table.\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n // May a firing start while the previous one is unsettled? The long\n // billing run still going at the next tick must not double-start.\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // How late is \"missed\"? Only `catchUp: 'skip'` reads it — 'run' fires\n // everything and 'latest' keeps the newest regardless of age.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\n// Every field defaults, so the empty policy is a real, complete policy —\n// which is what lets a reflex omit `policy` entirely and still be governed.\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Reflex — the artifact.\n//\n// A trigger, an optional selection, exactly one effect, a policy.\n// A straight arc from stimulus to response with no deliberation\n// between: there is no step language here, and a multi-step flow\n// is a CHAIN of reflexes joined by committed rows.\n//\n// `select.query` and every template are `unknown` ON PURPOSE. The\n// moment tide validates a query it owns a query language; the\n// moment it evaluates an expression it owns an evaluator. Both\n// exist in the stack already, behind seams. Tide stores, diffs and\n// hashes these blobs, and hands them over verbatim.\n// ═══════════════════════════════════════════════════════════════\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\n// ═══════════════════════════════════════════════════════════════\n// Draft — a reflex as it is WRITTEN, before it is saved.\n//\n// What a model writes: a name, an intent, a trigger and an effect — and\n// nothing that is the host's (who it runs as, its policy, whether it is\n// enabled). Which triggers, and whether the extra fields a data-driven\n// automation needs, are the CALLER'S choice (`draftSchemaOf`): a draft may\n// only use what its host can run, the way it may only name the effects its\n// host offers. That schema is what the model is shown, and what it is held\n// to; what is stored is still the full ReflexSchema, completed when the\n// draft is saved (`anchorDraft`).\n//\n// One trigger exists only here: the TIMER — \"this long from now\". A timer\n// is sugar, never stored. `now` is only known when somebody saves the\n// draft, so the host anchors it then, and what is stored and run is an\n// ordinary one-shot clock — which survives a restart, because it names an\n// instant rather than a distance from one.\n// ═══════════════════════════════════════════════════════════════\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\n// The trigger kinds a draft can be offered, by name.\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\n// The fields beyond name, intent, trigger and effect a draft can be offered —\n// for automations that select rows or test a fact before they act.\nexport type DraftField = 'params' | 'select' | 'when';\n\n// What the caller offers a draft: its trigger kinds (every kind, if it names\n// none) and its extra fields (none, if it names none).\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name for this automation.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\n// The widest draft: every trigger, every extra field — the TYPE every\n// narrower draft is, and what `anchorDraft` completes.\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\n// The draft schema for what the caller offers — tide's own pieces, each with\n// the description it already has: the widest draft, cut to the chosen fields,\n// its trigger narrowed to the chosen kinds. Nothing is restated here.\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\n// The default draft: every trigger kind, no extra fields.\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n","// ═══════════════════════════════════════════════════════════\n// @niscorp/tide/agent — the reflex agent\n// ═══════════════════════════════════════════════════════════\n//\n// Given what somebody wants automated — \"every Monday at nine, send the\n// digest\" — and what the host offers (its effects; which triggers and fields\n// a draft may use), the reflex agent answers with ONE of three things: a\n// reflex DRAFT, a QUESTION back when the request can be read more than one\n// way, or a REFUSAL when no offered effect does it. It does not schedule\n// anything, and it does not wait: a question ends the run like any answer.\n//\n// The host shows the person what came back — with the agent's reasoning, so\n// they can see how they were read. When they answer it, or correct a draft\n// they have not saved (\"no, I meant…\"), the host runs the agent again over the\n// CONVERSATION — each request, the agent's answer as it gave it, the latest\n// words — as the turns of a chat (`reflexConversation`), which is what these\n// models read natively. A draft is a document to be read and saved; the host\n// anchors it when it is saved (`anchorDraft` — a timer becomes a clock then)\n// and loads it, and from then on it runs with no model at all. That is the\n// point: the model writes the automation once, instead of being asked, on\n// every tick, whether there is anything to do.\n//\n// The same pattern as @niscorp/prism/agent and @niscorp/vex/agent: the\n// package's own schema is the output, cortex validates it in the loop and\n// feeds failures back. Cortex is an optional peer — the rest of @niscorp/tide\n// does not need it.\n//\n// const agent = createReflexAgent({ effects: [\n// { name: 'digest.send', description: 'Send the weekly digest to the team.', input: z.object({}) },\n// ], triggers: ['clock', 'timer'] });\n// const result = await agent.run({ intent, now, tz }, { llm }).result;\n// if (result.ok && isDraft(result.output.data)) {\n// // …shown to the person; when they save it:\n// await tide.load([{ ...anchorDraft(result.output.data, { at: Date.now(), tz }), as: owner }], { at: Date.now() });\n// }\n//\n// A factory, not a constant, because what is offered is the host's: the\n// draft's shape is built from the triggers and fields the host names\n// (`draftSchemaOf`), and a draft naming an effect the host does not offer — or\n// an input that effect's own schema refuses — is sent back to the model to\n// correct, in the same run. What each part of an answer IS lives in the\n// schemas' .describe() calls, which ride the wire with them. The instructions\n// carry what steers the answer as a whole: what to put first in `reasoning`\n// (the whole request, as the conversation now has it); how people say times\n// (a time of day that could be morning or evening is asked about; nothing\n// repeats unless the person says so; no time that has passed); how a reply\n// joins the request before it; asking about everything undecided at once; and\n// never putting one effect in the place of another. No worked example: the\n// only correct one would use the host's own effects, which tide does not know.\n\nimport { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, type DraftChoice, type ReflexDraft } from '../schemas';\n\n// An effect the host offers: its registered name, a description — one to\n// three sentences on what it does and what it is for, which is what the model\n// decides by — and the schema its input must satisfy.\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\n// The agent's answer for what the caller offers: a draft of THAT shape\n// (`draftSchemaOf`), a question, or a refusal.\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\n// The default answer: a draft with every trigger kind and no extra fields.\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\n// THE CONVERSATION SO FAR, as the agent's input: each earlier request and the\n// agent's answer to it — a question, a draft the person has not saved, a\n// refusal — as it gave it, reasoning first; then the person's latest words.\n// The turns of a chat, not a field to be read, because a reply or a\n// correction (\"no, I meant…\") is only understood beside what it answers.\n// Pass what this returns to `run` in place of a single input.\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a time of day that could fall in the morning or the evening, with nothing in the conversation saying which, is two different times — ask which. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// The offered effects, as the agent reads them: name, description, and the\n// JSON Schema of its input — converted by the schema's OWN zod, whichever copy\n// made it (a caller's schema may come from another).\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\n// What is wrong with a draft's effect, as a correction the model can act on —\n// or nothing. The effect is the host's vocabulary, so it is checked against the\n// host's own schemas: an effect nobody offered, or an input its schema refuses.\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\n// `triggers` / `fields`: what a draft may use here (`draftSchemaOf`) — every\n// trigger kind and no extra fields, unless the caller says otherwise. The draft\n// may only use what its host can run, as it may only name its host's effects.\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects)],\n output: {\n schema: answerSchemaOf(config),\n // Corrected in the run, tools and context still warm. Only a draft\n // names an effect; a question or a refusal has nothing to check here.\n validate: (envelope) => {\n if (!isDraft(envelope.data)) return { ok: true };\n const problem = effectProblem(config.effects, envelope.data);\n return problem === undefined ? { ok: true } : { retry: problem };\n },\n },\n });\n"]}
1
+ {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/reflex.schema.ts","../src/agent/reflex-agent.ts"],"names":["z","defineAgent"],"mappings":";;;;;;AAYO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK,CAAA;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AAEb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC,CAAA;AAE/D,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,EAAA,EAAIA,KAAA,CACD,KAAA,CAAM,CAACA,KAAA,CAAE,MAAA,EAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,IAAI,EAAE,CAAA,EAAGA,KAAA,CAAE,IAAA,CAAK,QAAQ,CAAA,EAAGA,KAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACjF,QAAA,EAAS,CACT,SAAS,yGAA0F,CAAA;AAAA,EACtG,EAAA,EAAIA,MAAE,MAAA,EAAO,CAAE,MAAM,IAAI,CAAA,CAAE,SAAS,iCAAiC,CAAA;AAAA,EACrE,EAAA,EAAIA,KAAA,CAAE,MAAA,EAAO,CAAE,SAAS,qBAAqB;AAC/C,CAAC,EACA,MAAA,EAAO,CACP,WAAA,CAAY,CAAC,OAAO,GAAA,KAAQ;AAC3B,EAAA,MAAM,IAAA,GA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,CAAA,EAAA,EAAK,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA,CAAE,KAAK,IAAI,CAAA;AACnH,EAAA,OAAO,CAAA,eAAA,EAAkB,MAAA,CAAO,IAAI,CAAA,iCAAA,EAA+B,MAAM,CAAA,CAAA,CAAA;AAC3E;AAKO,IAAM,iBAAA,GAAoB,CAAC,MAAA,KAChCC,kBAAA,CAA0B;AAAA,EACxB,EAAA,EAAI,aAAA;AAAA,EACJ,WAAA,EAAa,kGAAA;AAAA,EACb,YAAA,EAAc,YAAA;AAAA,EACd,SAAS,CAAC,MAAM,eAAA,CAAgB,MAAA,CAAO,OAAO,CAAC,CAAA;AAAA,EAC/C,MAAA,EAAQ;AAAA,IACN,MAAA,EAAQ,eAAe,MAAM,CAAA;AAAA;AAAA;AAAA,IAG7B,QAAA,EAAU,CAAC,QAAA,KAAa;AACtB,MAAA,IAAI,CAAC,QAAQ,QAAA,CAAS,IAAI,GAAG,OAAO,EAAE,IAAI,IAAA,EAAK;AAC/C,MAAA,MAAM,OAAA,GAAU,aAAA,CAAc,MAAA,CAAO,OAAA,EAAS,SAAS,IAAI,CAAA;AAC3D,MAAA,OAAO,OAAA,KAAY,SAAY,EAAE,EAAA,EAAI,MAAK,GAAI,EAAE,OAAO,OAAA,EAAQ;AAAA,IACjE;AAAA;AAEJ,CAAC","file":"agent.cjs","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Triggers — four kinds, closed.\n//\n// Structured on purpose: a reflex is shown to the operator it\n// affects, and `{ every: 'month', on: 1, at: '03:00' }` is\n// reviewable by the person it bills where `0 3 1 * *` is a\n// shibboleth. Cron-string sugar belongs in tooling, never in the\n// stored artifact.\n// ═══════════════════════════════════════════════════════════════\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\n// Seconds are optional: a one-shot can name the second it fires on.\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.string().regex(MMDD)])\n .optional()\n .describe('week → a weekday; month → 1..31 (clamped to month end); year → \"MM-DD\". Omitted for day.'),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n if (clock.every === 'week' && !(typeof clock.on === 'string' && WEEKDAYS.some((d) => d === clock.on)))\n fail('a weekly clock needs `on` as a weekday (mon..sun)');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\n// There is NO poll trigger, and the absence is a decision. Polls existed\n// for hosts with no write choke point — run a selection, diff a cursor,\n// mint write facts for the delta. In this stack the host's DAL IS the\n// choke point: every application write becomes a fact at the vex bridge,\n// so a poll could only ever re-discover what was already pushed, one\n// interval late. An external source with no choke point enters through an\n// importer that ingests write facts at the door — the same shape, without\n// a reflex secretly re-querying.\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\n// ── narrowing helpers: the union is structural, so every consumer\n// would otherwise re-derive these three checks ───────────────────\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Policy — the execution semantics, as authored data.\n//\n// Everything the requirements doc said \"must not be hand-waved\",\n// declared per reflex rather than guessed by the engine.\n// ═══════════════════════════════════════════════════════════════\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\n// THERE IS NO COALESCE, and its absence is the design.\n//\n// It cost two port methods, a table, an exactly-once promise and a\n// `DELETE … RETURNING` on every tick, and nothing ever set it — its only\n// driver was one test. A digest that genuinely needs batching is a DELAYED\n// RUN: the first fact of a group mints one at `now + window` with\n// `cause: 'coalesce:<key>:<start>'`, the rest collide on\n// UNIQUE(reflexId, cause) and are refused, and when it comes due the reflex\n// selects what changed. Mechanisms that already exist, and no new table.\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n // May a firing start while the previous one is unsettled? The long\n // billing run still going at the next tick must not double-start.\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // How late is \"missed\"? Only `catchUp: 'skip'` reads it — 'run' opens\n // everything and 'latest' keeps the newest regardless of age. What\n // `catchUp` opens still passes `overlap`: occurrences missed together are\n // repeats of one another, so under 'skip' the oldest runs and the rest\n // are recorded as overlap skips.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\n// Every field defaults, so the empty policy is a real, complete policy —\n// which is what lets a reflex omit `policy` entirely and still be governed.\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Reflex — the artifact.\n//\n// A trigger, an optional selection, exactly one effect, a policy.\n// A straight arc from stimulus to response with no deliberation\n// between: there is no step language here, and a multi-step flow\n// is a CHAIN of reflexes joined by committed rows.\n//\n// `select.query` and every template are `unknown` ON PURPOSE. The\n// moment tide validates a query it owns a query language; the\n// moment it evaluates an expression it owns an evaluator. Both\n// exist in the stack already, behind seams. Tide stores, diffs and\n// hashes these blobs, and hands them over verbatim.\n// ═══════════════════════════════════════════════════════════════\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\n// ═══════════════════════════════════════════════════════════════\n// Draft — a reflex as it is WRITTEN, before it is saved.\n//\n// What a model writes: a name, an intent, a trigger and an effect — and\n// nothing that is the host's (who it runs as, its policy, whether it is\n// enabled). Which triggers, and whether the extra fields a data-driven\n// automation needs, are the CALLER'S choice (`draftSchemaOf`): a draft may\n// only use what its host can run, the way it may only name the effects its\n// host offers. That schema is what the model is shown, and what it is held\n// to; what is stored is still the full ReflexSchema, completed when the\n// draft is saved (`anchorDraft`).\n//\n// One trigger exists only here: the TIMER — \"this long from now\". A timer\n// is sugar, never stored. `now` is only known when somebody saves the\n// draft, so the host anchors it then, and what is stored and run is an\n// ordinary one-shot clock — which survives a restart, because it names an\n// instant rather than a distance from one.\n// ═══════════════════════════════════════════════════════════════\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\n// The trigger kinds a draft can be offered, by name.\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\n// The fields beyond name, intent, trigger and effect a draft can be offered —\n// for automations that select rows or test a fact before they act.\nexport type DraftField = 'params' | 'select' | 'when';\n\n// What the caller offers a draft: its trigger kinds (every kind, if it names\n// none) and its extra fields (none, if it names none).\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name for this automation.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\n// The widest draft: every trigger, every extra field — the TYPE every\n// narrower draft is, and what `anchorDraft` completes.\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\n// The draft schema for what the caller offers — tide's own pieces, each with\n// the description it already has: the widest draft, cut to the chosen fields,\n// its trigger narrowed to the chosen kinds. Nothing is restated here.\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\n// The default draft: every trigger kind, no extra fields.\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n","// ═══════════════════════════════════════════════════════════\n// @niscorp/tide/agent — the reflex agent\n// ═══════════════════════════════════════════════════════════\n//\n// Given what somebody wants automated — \"every Monday at nine, send the\n// digest\" — and what the host offers (its effects; which triggers and fields\n// a draft may use), the reflex agent answers with ONE of three things: a\n// reflex DRAFT, a QUESTION back when the request can be read more than one\n// way, or a REFUSAL when no offered effect does it. It does not schedule\n// anything, and it does not wait: a question ends the run like any answer.\n//\n// The host shows the person what came back — with the agent's reasoning, so\n// they can see how they were read. When they answer it, or correct a draft\n// they have not saved (\"no, I meant…\"), the host runs the agent again over the\n// CONVERSATION — each request, the agent's answer as it gave it, the latest\n// words — as the turns of a chat (`reflexConversation`), which is what these\n// models read natively. A draft is a document to be read and saved; the host\n// anchors it when it is saved (`anchorDraft` — a timer becomes a clock then)\n// and loads it, and from then on it runs with no model at all. That is the\n// point: the model writes the automation once, instead of being asked, on\n// every tick, whether there is anything to do.\n//\n// The same pattern as @niscorp/prism/agent and @niscorp/vex/agent: the\n// package's own schema is the output, cortex validates it in the loop and\n// feeds failures back. Cortex is an optional peer — the rest of @niscorp/tide\n// does not need it.\n//\n// const agent = createReflexAgent({ effects: [\n// { name: 'digest.send', description: 'Send the weekly digest to the team.', input: z.object({}) },\n// ], triggers: ['clock', 'timer'] });\n// const result = await agent.run({ intent, now, tz }, { llm }).result;\n// if (result.ok && isDraft(result.output.data)) {\n// // …shown to the person; when they save it:\n// await tide.load([{ ...anchorDraft(result.output.data, { at: Date.now(), tz }), as: owner }], { at: Date.now() });\n// }\n//\n// A factory, not a constant, because what is offered is the host's: the\n// draft's shape is built from the triggers and fields the host names\n// (`draftSchemaOf`), and a draft naming an effect the host does not offer — or\n// an input that effect's own schema refuses — is sent back to the model to\n// correct, in the same run. What each part of an answer IS lives in the\n// schemas' .describe() calls, which ride the wire with them. The instructions\n// carry what steers the answer as a whole: what to put first in `reasoning`\n// (the whole request, as the conversation now has it); how people say times\n// (a time of day that could be morning or evening is asked about; nothing\n// repeats unless the person says so; no time that has passed); how a reply\n// joins the request before it; asking about everything undecided at once; and\n// never putting one effect in the place of another. No worked example: the\n// only correct one would use the host's own effects, which tide does not know.\n\nimport { z } from 'zod';\nimport type { ZodType } from 'zod';\nimport { defineAgent, type AgentDefinition, type Message } from '@niscorp/cortex';\nimport { draftSchemaOf, type DraftChoice, type ReflexDraft } from '../schemas';\n\n// An effect the host offers: its registered name, a description — one to\n// three sentences on what it does and what it is for, which is what the model\n// decides by — and the schema its input must satisfy.\nexport type OfferedEffect = { name: string; description: string; input: ZodType };\n\nexport const ReflexAgentInputSchema = z.object({\n intent: z.string().describe(\"The person's words — a request, or, later in the conversation, their reply to your question.\"),\n now: z\n .string()\n .describe('The current local date and time, \"YYYY-MM-DDTHH:MM\", in `tz` — what a date or a time of day in the request is read against.'),\n tz: z.string().describe('The IANA timezone the person is in. Every clock the reflex names uses it.'),\n});\n\nexport type ReflexAgentInput = z.infer<typeof ReflexAgentInputSchema>;\n\nexport const ReflexQuestionSchema = z\n .object({ question: z.string().min(1).describe(\"One short question in the person's language, naming what it chooses between.\") })\n .strict()\n .describe('Ask instead of writing a draft when the request can be read as different automations and nothing in its words or the conversation so far decides which.');\n\nexport const ReflexRefusalSchema = z\n .object({ refused: z.string().min(1).describe('Why none of the offered effects does it, in words for the person who asked.') })\n .strict()\n .describe('Refuse instead of writing a draft when none of the offered effects does what was asked. Only for that: a request that is unclear is a question, not a refusal.');\n\nexport type ReflexQuestion = z.infer<typeof ReflexQuestionSchema>;\nexport type ReflexRefusal = z.infer<typeof ReflexRefusalSchema>;\nexport type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;\n\n// The agent's answer for what the caller offers: a draft of THAT shape\n// (`draftSchemaOf`), a question, or a refusal.\nexport const answerSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexAnswer> =>\n z.union([\n draftSchemaOf(choice).describe('Write the draft when the request — with the conversation so far — says what should happen and what sets it off.'),\n ReflexQuestionSchema,\n ReflexRefusalSchema,\n ]);\n\n// The default answer: a draft with every trigger kind and no extra fields.\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\n// THE CONVERSATION SO FAR, as the agent's input: each earlier request and the\n// agent's answer to it — a question, a draft the person has not saved, a\n// refusal — as it gave it, reasoning first; then the person's latest words.\n// The turns of a chat, not a field to be read, because a reply or a\n// correction (\"no, I meant…\") is only understood beside what it answers.\n// Pass what this returns to `run` in place of a single input.\nexport const reflexConversation = (conversation: {\n now: string;\n tz: string;\n earlier: readonly { request: string; answer: ReflexAnswer; reasoning?: string | undefined }[];\n latest: string;\n}): Message[] => [\n ...conversation.earlier.flatMap((turn): Message[] => [\n { role: 'user', content: JSON.stringify({ intent: turn.request, now: conversation.now, tz: conversation.tz }) },\n { role: 'assistant', content: JSON.stringify({ ...(turn.reasoning === undefined ? {} : { reasoning: turn.reasoning }), data: turn.answer }) },\n ]),\n { role: 'user', content: JSON.stringify({ intent: conversation.latest, now: conversation.now, tz: conversation.tz }) },\n];\n\nconst INSTRUCTIONS = `You are Tide's reflex agent. Somebody describes an automation; you answer with ONE of three things, as the OUTPUT SCHEMA describes: a reflex draft that does it (a trigger, exactly one of the offered effects, and its input), a question back, or a refusal.\n\nYour envelope's \\`data\\` is that answer. In \\`reasoning\\`, first restate the whole request as the conversation now has it; then decide. The answer must validate against the OUTPUT SCHEMA (its descriptions say what each part is); a draft must name one of the OFFERED EFFECTS and give it an input its schema accepts.\n\nTimes: a time of day that could fall in the morning or the evening, with nothing in the conversation saying which, is two different times — ask which. An automation happens once unless the person says it repeats. Never write a time that has already passed.\n\nA reply answers your last question: together with the request before it, it is one request — keep what the request said, and add what the reply decides.\n\nWhen you ask, ask about everything still undecided in one question, so one reply can settle it.\n\nEffects: when the request names something to be done that no offered effect does — a channel, a device, an action — refuse it; never put a different effect in its place.`;\n\n// The offered effects, as the agent reads them: name, description, and the\n// JSON Schema of its input — converted by the schema's OWN zod, whichever copy\n// made it (a caller's schema may come from another).\nconst describeEffects = (effects: readonly OfferedEffect[]): string =>\n `OFFERED EFFECTS — a draft names exactly one, by \\`name\\`; choose by its \\`description\\`:\\n${JSON.stringify(\n effects.map((effect) => ({ name: effect.name, description: effect.description, input: effect.input['~standard'].jsonSchema.output({ target: 'draft-07' }) })),\n )}`;\n\n// What is wrong with a draft's effect, as a correction the model can act on —\n// or nothing. The effect is the host's vocabulary, so it is checked against the\n// host's own schemas: an effect nobody offered, or an input its schema refuses.\nexport const effectProblem = (effects: readonly OfferedEffect[], reflex: Pick<ReflexDraft, 'effect'>): string | undefined => {\n const effect = effects.find((candidate) => candidate.name === reflex.effect.name);\n if (effect === undefined) return `The effect \"${reflex.effect.name}\" is not offered. Name one of: ${effects.map((candidate) => candidate.name).join(', ')}.`;\n const parsed = effect.input.safeParse(reflex.effect.input);\n if (parsed.success) return undefined;\n const issues = parsed.error.issues.map((issue) => `${issue.path.join('.') || 'input'}: ${issue.message}`).join('; ');\n return `The input for \"${effect.name}\" does not fit its schema — ${issues}.`;\n};\n\n// `triggers` / `fields`: what a draft may use here (`draftSchemaOf`) — every\n// trigger kind and no extra fields, unless the caller says otherwise. The draft\n// may only use what its host can run, as it may only name its host's effects.\nexport const createReflexAgent = (config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer> =>\n defineAgent<ReflexAnswer>({\n id: 'tide.reflex',\n description: 'Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.',\n instructions: INSTRUCTIONS,\n context: [() => describeEffects(config.effects)],\n output: {\n schema: answerSchemaOf(config),\n // Corrected in the run, tools and context still warm. Only a draft\n // names an effect; a question or a refusal has nothing to check here.\n validate: (envelope) => {\n if (!isDraft(envelope.data)) return { ok: true };\n const problem = effectProblem(config.effects, envelope.data);\n return problem === undefined ? { ok: true } : { retry: problem };\n },\n },\n });\n"]}
package/dist/agent.js CHANGED
@@ -1,4 +1,4 @@
1
- import { draftSchemaOf } from './chunk-PJNVL4OD.js';
1
+ import { draftSchemaOf } from './chunk-UEG3UZDG.js';
2
2
  import { z } from 'zod';
3
3
  import { defineAgent } from '@niscorp/cortex';
4
4
 
@@ -60,8 +60,11 @@ var PolicySchema = z.object({
60
60
  // billing run still going at the next tick must not double-start.
61
61
  overlap: z.enum(["skip", "allow"]).default("skip"),
62
62
  catchUp: z.enum(["run", "skip", "latest"]).default("run"),
63
- // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' fires
64
- // everything and 'latest' keeps the newest regardless of age.
63
+ // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' opens
64
+ // everything and 'latest' keeps the newest regardless of age. What
65
+ // `catchUp` opens still passes `overlap`: occurrences missed together are
66
+ // repeats of one another, so under 'skip' the oldest runs and the rest
67
+ // are recorded as overlap skips.
65
68
  lateMs: z.number().int().positive().default(36e5),
66
69
  order: z.enum(["any", "serial"]).default("any")
67
70
  }).strict();
@@ -192,5 +195,5 @@ var draftSchemaOf = (choice = {}) => {
192
195
  var ReflexDraftSchema = draftSchemaOf();
193
196
 
194
197
  export { ClockOnceSchema, ClockRecurringSchema, ClockTriggerSchema, ClockUnitSchema, DRAFT_TRIGGERS, EffectRefSchema, FactInputSchema, FactKindSchema, ManualTriggerSchema, OpSchema, PolicySchema, ReflexDraftSchema, ReflexSchema, RetrySchema, RunTriggerSchema, SelectionSchema, SignalTriggerSchema, TimerSchema, TimerTriggerSchema, TriggerSchema, WEEKDAYS, WriteTriggerSchema, clockOf, draftSchemaOf, factOf, isManual, isRecurring };
195
- //# sourceMappingURL=chunk-PJNVL4OD.js.map
196
- //# sourceMappingURL=chunk-PJNVL4OD.js.map
198
+ //# sourceMappingURL=chunk-UEG3UZDG.js.map
199
+ //# sourceMappingURL=chunk-UEG3UZDG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/fact.schema.ts","../src/schemas/reflex.schema.ts"],"names":["z","require"],"mappings":";;;AAYO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AAEb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkB,EAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC;AAE/D,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,EAAA,EAAI,CAAA,CACD,KAAA,CAAM,CAAC,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,IAAI,EAAE,CAAA,EAAG,CAAA,CAAE,IAAA,CAAK,QAAQ,CAAA,EAAG,CAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACjF,QAAA,EAAS,CACT,SAAS,yGAA0F,CAAA;AAAA,EACtG,EAAA,EAAI,EAAE,MAAA,EAAO,CAAE,MAAM,IAAI,CAAA,CAAE,SAAS,iCAAiC,CAAA;AAAA,EACrE,EAAA,EAAI,CAAA,CAAE,MAAA,EAAO,CAAE,SAAS,qBAAqB;AAC/C,CAAC,EACA,MAAA,EAAO,CACP,WAAA,CAAY,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CAAA;AACxF,EAAA,MAAM,EAAA,GAAmC,IAAA,CAAK,MAAA,KAAW,CAAA,GAAI,KAAA,GAAQA,CAAAA,CAAE,KAAA,CAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAC,CAAA;AAC7F,EAAA,MAAM,MAAM,CAAC,KAAA,KAA+B,OAAO,MAAA,EAAQ,QAAA,CAAS,KAAK,CAAA,IAAK,KAAA;AAC9E,EAAA,MAAM,IAAA,GAA8C;AAAA,IAClD,EAAA,EAAI,IAAA;AAAA,IACJ,MAAA,EAAQ,IAAA;AAAA,IACR,MAAA,EAAQ,IAAA;AAAA,IACR,EAAA,EAAI,IAAA;AAAA,IACJ,GAAI,IAAI,QAAQ,CAAA,GAAI,EAAE,MAAA,EAAQ,IAAA,KAAkB,EAAC;AAAA,IACjD,GAAI,IAAI,QAAQ,CAAA,GAAI,EAAE,MAAA,EAAQ,IAAA,KAAkB,EAAC;AAAA,IACjD,GAAI,IAAI,MAAM,CAAA,GAAI,EAAE,IAAA,EAAM,IAAA,KAAkB;AAAC,GAC/C;AACA,EAAA,OAAO,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,CAAE,MAAA,CAAO,EAAE,EAAA,EAAI,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,WAAW,CAAA;AACrF;AAGO,IAAM,oBAAoB,aAAA","file":"chunk-UEG3UZDG.js","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Triggers — four kinds, closed.\n//\n// Structured on purpose: a reflex is shown to the operator it\n// affects, and `{ every: 'month', on: 1, at: '03:00' }` is\n// reviewable by the person it bills where `0 3 1 * *` is a\n// shibboleth. Cron-string sugar belongs in tooling, never in the\n// stored artifact.\n// ═══════════════════════════════════════════════════════════════\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\n// Seconds are optional: a one-shot can name the second it fires on.\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.string().regex(MMDD)])\n .optional()\n .describe('week → a weekday; month → 1..31 (clamped to month end); year → \"MM-DD\". Omitted for day.'),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n if (clock.every === 'week' && !(typeof clock.on === 'string' && WEEKDAYS.some((d) => d === clock.on)))\n fail('a weekly clock needs `on` as a weekday (mon..sun)');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\n// There is NO poll trigger, and the absence is a decision. Polls existed\n// for hosts with no write choke point — run a selection, diff a cursor,\n// mint write facts for the delta. In this stack the host's DAL IS the\n// choke point: every application write becomes a fact at the vex bridge,\n// so a poll could only ever re-discover what was already pushed, one\n// interval late. An external source with no choke point enters through an\n// importer that ingests write facts at the door — the same shape, without\n// a reflex secretly re-querying.\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\n// ── narrowing helpers: the union is structural, so every consumer\n// would otherwise re-derive these three checks ───────────────────\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Policy — the execution semantics, as authored data.\n//\n// Everything the requirements doc said \"must not be hand-waved\",\n// declared per reflex rather than guessed by the engine.\n// ═══════════════════════════════════════════════════════════════\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\n// THERE IS NO COALESCE, and its absence is the design.\n//\n// It cost two port methods, a table, an exactly-once promise and a\n// `DELETE … RETURNING` on every tick, and nothing ever set it — its only\n// driver was one test. A digest that genuinely needs batching is a DELAYED\n// RUN: the first fact of a group mints one at `now + window` with\n// `cause: 'coalesce:<key>:<start>'`, the rest collide on\n// UNIQUE(reflexId, cause) and are refused, and when it comes due the reflex\n// selects what changed. Mechanisms that already exist, and no new table.\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n // May a firing start while the previous one is unsettled? The long\n // billing run still going at the next tick must not double-start.\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // How late is \"missed\"? Only `catchUp: 'skip'` reads it — 'run' opens\n // everything and 'latest' keeps the newest regardless of age. What\n // `catchUp` opens still passes `overlap`: occurrences missed together are\n // repeats of one another, so under 'skip' the oldest runs and the rest\n // are recorded as overlap skips.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\n// Every field defaults, so the empty policy is a real, complete policy —\n// which is what lets a reflex omit `policy` entirely and still be governed.\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { OpSchema } from './trigger.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Fact — the public intake contract.\n//\n// Tide's whole ingestion surface. Anything that can produce this\n// shape can drive tide; nothing else about the producer is tide's\n// business. A host that sees its own writes pushes them — the vex\n// bridge is that host. Either way, what arrives is this.\n// ═══════════════════════════════════════════════════════════════\n\nexport const FactKindSchema = z.enum(['write', 'signal', 'manual', 'run']);\n\nexport const FactInputSchema = z\n .object({\n kind: FactKindSchema,\n\n // write facts\n entity: z.string().optional().describe('Which table or entity was written.'),\n op: OpSchema.optional().describe('Ops are distinct stimuli — \"only on create\" is op: \"insert\".'),\n row: z.record(z.string(), z.unknown()).optional().describe('The row, as the write returned it.'),\n\n // signal facts\n name: z.string().optional().describe('Which named intake this arrived on.'),\n payload: z.unknown().optional().describe('The event body — validated at the HOST boundary before it gets here.'),\n\n // run facts (minted by tide when a run settles — the fan-in mechanism)\n reflex: z.string().optional(),\n runId: z.string().optional(),\n occurrence: z.string().optional().describe('The calendar key, when the clock was the cause.'),\n stats: z\n .object({ total: z.number().int(), done: z.number().int(), failed: z.number().int() })\n .strict()\n .optional(),\n\n // manual facts (minted by `fire`)\n target: z.string().optional().describe('The one reflex a manual fact is aimed at.'),\n by: z.string().optional().describe('Who fired it — recorded on the firing as manual:<who>.'),\n\n at: z.number().int().describe('Supplied by the caller. Tide reads no clocks.'),\n notBefore: z.number().int().optional().describe('A delayed fact — timers as data, visible and queryable.'),\n dedupeKey: z.string().optional().describe('Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error.'),\n cause: z.string().optional().describe('Set by tide when an effect emits — the causality chain.'),\n })\n .strict()\n // THE UNION IS ENFORCED, because an unenforced one is worse than none.\n //\n // `{ kind: 'write' }` with no entity used to parse, store, match nothing,\n // get marked delivered, and vanish — the producer had no way to learn its\n // fact was never going to wake anything. Each kind names the fields that\n // make it addressable, and a fact that cannot be addressed is refused at\n // the intake rather than swallowed by the matcher.\n .superRefine((fact, ctx) => {\n const require = (field: keyof typeof fact, why: string) => {\n if (fact[field] === undefined)\n ctx.addIssue({ code: 'custom', message: `a ${fact.kind} fact needs \\`${String(field)}\\` — ${why}`, path: [field] });\n };\n const refuse = (field: keyof typeof fact) => {\n if (fact[field] !== undefined)\n ctx.addIssue({ code: 'custom', message: `\\`${String(field)}\\` is not part of a ${fact.kind} fact`, path: [field] });\n };\n\n if (fact.kind === 'write') {\n require('entity', 'it is what a write trigger matches on');\n refuse('name');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'signal') {\n require('name', 'it is which named intake this arrived on');\n refuse('entity');\n refuse('op');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'manual') {\n require('target', 'a manual fact is aimed at exactly one reflex');\n refuse('entity');\n refuse('name');\n refuse('runId');\n }\n if (fact.kind === 'run') {\n require('reflex', 'it is whose run settled');\n require('runId', 'it is which run settled');\n refuse('entity');\n refuse('name');\n refuse('target');\n }\n });\n\nexport type FactInput = z.infer<typeof FactInputSchema>;\nexport type FactKind = z.infer<typeof FactKindSchema>;\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Reflex — the artifact.\n//\n// A trigger, an optional selection, exactly one effect, a policy.\n// A straight arc from stimulus to response with no deliberation\n// between: there is no step language here, and a multi-step flow\n// is a CHAIN of reflexes joined by committed rows.\n//\n// `select.query` and every template are `unknown` ON PURPOSE. The\n// moment tide validates a query it owns a query language; the\n// moment it evaluates an expression it owns an evaluator. Both\n// exist in the stack already, behind seams. Tide stores, diffs and\n// hashes these blobs, and hands them over verbatim.\n// ═══════════════════════════════════════════════════════════════\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\n// ═══════════════════════════════════════════════════════════════\n// Draft — a reflex as it is WRITTEN, before it is saved.\n//\n// What a model writes: a name, an intent, a trigger and an effect — and\n// nothing that is the host's (who it runs as, its policy, whether it is\n// enabled). Which triggers, and whether the extra fields a data-driven\n// automation needs, are the CALLER'S choice (`draftSchemaOf`): a draft may\n// only use what its host can run, the way it may only name the effects its\n// host offers. That schema is what the model is shown, and what it is held\n// to; what is stored is still the full ReflexSchema, completed when the\n// draft is saved (`anchorDraft`).\n//\n// One trigger exists only here: the TIMER — \"this long from now\". A timer\n// is sugar, never stored. `now` is only known when somebody saves the\n// draft, so the host anchors it then, and what is stored and run is an\n// ordinary one-shot clock — which survives a restart, because it names an\n// instant rather than a distance from one.\n// ═══════════════════════════════════════════════════════════════\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\n// The trigger kinds a draft can be offered, by name.\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\n// The fields beyond name, intent, trigger and effect a draft can be offered —\n// for automations that select rows or test a fact before they act.\nexport type DraftField = 'params' | 'select' | 'when';\n\n// What the caller offers a draft: its trigger kinds (every kind, if it names\n// none) and its extra fields (none, if it names none).\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name for this automation.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\n// The widest draft: every trigger, every extra field — the TYPE every\n// narrower draft is, and what `anchorDraft` completes.\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\n// The draft schema for what the caller offers — tide's own pieces, each with\n// the description it already has: the widest draft, cut to the chosen fields,\n// its trigger narrowed to the chosen kinds. Nothing is restated here.\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\n// The default draft: every trigger kind, no extra fields.\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n"]}
package/dist/index.cjs CHANGED
@@ -62,8 +62,11 @@ var PolicySchema = zod.z.object({
62
62
  // billing run still going at the next tick must not double-start.
63
63
  overlap: zod.z.enum(["skip", "allow"]).default("skip"),
64
64
  catchUp: zod.z.enum(["run", "skip", "latest"]).default("run"),
65
- // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' fires
66
- // everything and 'latest' keeps the newest regardless of age.
65
+ // How late is "missed"? Only `catchUp: 'skip'` reads it — 'run' opens
66
+ // everything and 'latest' keeps the newest regardless of age. What
67
+ // `catchUp` opens still passes `overlap`: occurrences missed together are
68
+ // repeats of one another, so under 'skip' the oldest runs and the rest
69
+ // are recorded as overlap skips.
67
70
  lateMs: zod.z.number().int().positive().default(36e5),
68
71
  order: zod.z.enum(["any", "serial"]).default("any")
69
72
  }).strict();
@@ -964,23 +967,15 @@ var record = async (deps, task, token, settlement) => deps.store.transact(async
964
967
  const admissions = [];
965
968
  for (const emit of settlement.emits) admissions.push(await admitFact(tx, emit, deps.maxChainFacts));
966
969
  if (settles) {
970
+ await tx.cas(
971
+ "run",
972
+ task.runId,
973
+ {},
974
+ { done: { inc: settlement.state === "done" ? 1 : 0 }, failed: { inc: settlement.state === "failed" ? 1 : 0 } }
975
+ );
967
976
  const [run] = await tx.query({ table: "run", where: { id: task.runId }, limit: 1 });
968
- if (run !== void 0) {
969
- const done = run.done + (settlement.state === "done" ? 1 : 0);
970
- const failed = run.failed + (settlement.state === "failed" ? 1 : 0);
971
- const complete = done + failed >= run.total && run.settledAt === void 0;
972
- await tx.cas(
973
- "run",
974
- run.id,
975
- {},
976
- {
977
- done: { inc: settlement.state === "done" ? 1 : 0 },
978
- failed: { inc: settlement.state === "failed" ? 1 : 0 },
979
- state: complete ? "settled" : run.state,
980
- settledAt: complete ? settlement.at : run.settledAt
981
- }
982
- );
983
- }
977
+ if (run !== void 0 && run.done + run.failed >= run.total && run.settledAt === void 0)
978
+ await tx.cas("run", run.id, { state: "fanned" }, { state: "settled", settledAt: settlement.at });
984
979
  }
985
980
  return admissions;
986
981
  });
@@ -994,7 +989,8 @@ var reopenTask = async (deps, taskId, now) => deps.store.transact(async (tx) =>
994
989
  { state: "pending", notBefore: now, error: void 0, settledAt: void 0, token: void 0, claimedUntil: 0 }
995
990
  );
996
991
  if (!reopened) return false;
997
- await tx.cas("run", task.runId, { state: "settled" }, { state: "fanned", failed: { inc: -1 }, settledAt: void 0 });
992
+ await tx.cas("run", task.runId, {}, { failed: { inc: -1 } });
993
+ await tx.cas("run", task.runId, { state: "settled" }, { state: "fanned", settledAt: void 0 });
998
994
  return true;
999
995
  });
1000
996
  var settleRuns = async (deps, now) => {
@@ -1445,7 +1441,8 @@ var createMemoryStore = () => {
1445
1441
  if (collides) return void 0;
1446
1442
  }
1447
1443
  sequence += 1;
1448
- const row = PRIMARY_KEY[table] === "id" ? { ...candidate, id: candidate.id ?? `${ID_PREFIX[table]}_${sequence}` } : { ...candidate };
1444
+ const given = Object.fromEntries(Object.entries(candidate).filter(([, value]) => value !== void 0));
1445
+ const row = PRIMARY_KEY[table] === "id" ? { ...given, id: given.id ?? `${ID_PREFIX[table]}_${sequence}` } : given;
1449
1446
  tables[table].set(keyOf(table, row), row);
1450
1447
  return row;
1451
1448
  };