@niscorp/tide 0.1.12 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,79 @@
1
1
  # @niscorp/tide
2
2
 
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 909ae6b: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app relied on the reflex agent answering a draft whose one-shot clock names a date that does not exist; such a draft now goes back to the model in the same run, which costs one more model call.
8
+
9
+ The reflex agent (`@niscorp/tide/agent`) sends back a draft whose one-shot clock names a date that does not exist (`{ clock: { at: '2026-02-30T10:00' } }`, which would fire on 2 March), for the model to correct in the same run, whatever its reasoning says. It accepted such a draft.
10
+
11
+ - 5eb6e6c: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app relied on a run whose fan-out failed in a host seam being tried again on the very next `advance`; it is now tried after the reflex's retry wait (with the default policy 60 s, then 120 s, then 240 s).
12
+
13
+ A run whose fan-out fails in a host seam (a database down, a broken template) stays `pending` as before, and is tried again after a wait taken from the reflex's own `policy.retry` (`baseMs`, growing by `backoff` over the first `max` deferrals, then staying that long). While it waits, the pending runs behind it fan out: a page of such runs no longer keeps every other run from fanning out. After the n-th deferral the wait is `baseMs · 2^(min(n, max) − 1)` (exponential) or `baseMs` (fixed), never more than the largest whole number of milliseconds; a large `max` makes a long wait (`max: 20` with the default `baseMs`: 364 days). The waits are kept in each engine's memory, so after a restart a deferred run is tried once at once and then waits again; a run another engine fans out or skips is forgotten on the next pass. A run whose reflex a load left out is still skipped on the next `advance`.
14
+
15
+ - 1c2b7ce: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app relied on the early firing time in Pacific/Auckland, Antarctica/McMurdo or Pacific/Chatham on the two transition days a year.
16
+
17
+ A clock time inside a daylight-saving transition now resolves as documented in zones at +12 and +13 too. In Pacific/Auckland and Antarctica/McMurdo, a daily 02:00 on the spring-forward day (2026-09-27) fired at 01:00, before the asked time; it fires at 03:00, past the gap. In the repeated hour in autumn it took the second occurrence; it takes the first. In Pacific/Chatham the times just before the transition moved too: on 2026-09-27, 02:00–02:30 fired an hour early, and on 2026-04-05, 02:00–02:30 an hour late; they fire on time. Occurrence keys do not change, so no run is opened twice or lost. No other zone moves.
18
+
19
+ - 069efde: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app relied on a `manual` fact ingested under one identity (or none) running a reflex of another identity, or on `ingest` accepting a `kind: 'run'` fact.
20
+
21
+ A `manual` fact now passes the identity check before it skips `enabled` and arming: `ingest({ kind: 'manual', target: 'b.refund' }, { as: 'tenant-a' })` no longer runs tenant B's reflex. `fire` mints the fact under the reflex's own identity, so firing by hand works as before, on a disabled reflex too.
22
+
23
+ `ingest` refuses a `run` fact with `invalid_fact`: tide mints one when a run settles, and an ingested one would forge that settlement.
24
+
25
+ - 85f1536: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app's tests on `createMemoryStore()` relied on which tasks a claim takes when the claim limit bites and a reflex has `order: 'serial'`.
26
+
27
+ The memory store claims the serial groups (`onePer.only`) first, one row each, and gives what they leave of the limit to the other rows, as the Postgres store does. With limit 1, a parallel task ordered first and a serial task second, it claimed the parallel one and Postgres the serial one; both now claim the serial one. Nothing changes when the limit does not bite. The docs say a host's own store should do the same.
28
+
29
+ - d7f10ac: BREAKING — approved by moccadroid (owner), 2026-11-22: nothing unless an app sorted or parsed the ids of tide's Postgres rows by their old shape (`fact_mwi60d3d_1`) — including a sort on `created_at` that breaks ties on `id`: runs made in one advance share `created_at`, and UUIDs order them at random; break such ties on `due_at`.
30
+
31
+ The Postgres store mints the ids of new `fact`, `run` and `task` rows as UUIDs. They were the time and a per-process counter, so two processes on one database could mint the same id in the same millisecond, and the second write failed (`duplicate key value violates unique constraint "tide_fact_pkey"`); under moss that write fact was lost. Rows already written keep their ids; no table changes. The memory store keeps its `fact_1` ids.
32
+
33
+ ### Patch Changes
34
+
35
+ - 8bf0c30: On the Postgres store, a fact payload, an effect input or an output that is a string which is not JSON text (`'hello'`, `'msg_8812'`) reads back as that string. It threw, and stopped `ingest`, every `advance` and the ledger reads that met it. A string that is JSON text reads back as it did.
36
+
37
+ `load` calls run one at a time, in the order they are made: two that overlapped could finish out of order and load the earlier set, bringing back a reflex the later one had taken out.
38
+
39
+ An `advance` before the first `load` no longer skips pending runs as "reflex is no longer loaded": fan-out waits until the engine's first load has finished. After it, a run whose reflex a load left out is skipped as before.
40
+
41
+ `load(reflexes, { at, resume: true })` is a new opt-in for the load a process makes when it starts: a reflex this engine has never loaded keeps its stored watermark, so its `catchUp` decides what the downtime runs and a one-shot clock due during a restart fires after it. Without `resume`, `load` re-baselines as before.
42
+
43
+ `advance` takes an optional `clock`, and the driver passes its own `now`. Given one, each task's lease starts again just before its effect, never to end before the claim's, and the effect runs only if the task is still this claim's: a task late in a slow pass, whose lease had run out and which another instance had claimed again, no longer runs twice. That is one more write per task. Without `clock`, nothing changes.
44
+
45
+ `load` warns about a one-shot clock whose date does not exist (`2026-02-30`), naming the day it fires on (2026-03-02). The reflex loads and fires as before.
46
+
47
+ The docs say that a `dedupeKey` is unique across the whole ledger and not per identity, that `duplicate_unit` is never thrown to a caller, that a spring-forward time shifts by the length of the gap, and what `sweep`'s `tasks` horizon removes.
48
+
49
+ - 9e5c5e3: `load` warns about a reflex whose `timeoutMs` is not shorter than `leaseMs`, and still loads it.
50
+
51
+ A settled run is marked announced in the same transaction as the run fact that announces it, one run at a time: a failed write no longer loses the fact, the run is announced on a later advance, and the runs after it are announced meanwhile.
52
+
53
+ Facts delayed by `notBefore` no longer keep a due fact from its reflex: the matcher reads only the facts that are due.
54
+
55
+ The tasks of a reflex that is not loaded are no longer claimed, so they spend no attempt while it is away.
56
+
57
+ `ledger.facts({ reflexId })` reads only that reflex's facts instead of the whole fact table. The docs describe what `sweep` removes and drop the history they carried.
58
+
59
+ The Postgres store no longer sets aside room in a claim for every `order: 'serial'` reflex before it knows whether one has work: with as many serial reflexes as the advance's `limit`, other tasks were never claimed. Serial reflexes are still claimed first.
60
+
61
+ - Updated dependencies [48138de]
62
+ - Updated dependencies [da3037e]
63
+ - Updated dependencies [e957628]
64
+ - Updated dependencies [c30562a]
65
+ - Updated dependencies [efd2368]
66
+ - Updated dependencies [ca26810]
67
+ - Updated dependencies [800a541]
68
+ - Updated dependencies [9c5367b]
69
+ - Updated dependencies [322f241]
70
+ - Updated dependencies [61b15e4]
71
+ - Updated dependencies [7e8f6d4]
72
+ - Updated dependencies [5c52ef5]
73
+ - Updated dependencies [66eb934]
74
+ - @niscorp/cortex@0.2.0
75
+ - @niscorp/strata@0.2.0
76
+
3
77
  ## 0.1.12
4
78
 
5
79
  ### Patch Changes
package/DESIGN.md CHANGED
@@ -342,7 +342,10 @@ advance({ now, limit }) — ONE committed increment; the driver's v
342
342
  │ a question the fact already answers); a declared selection is
343
343
  │ ENRICHMENT, re-run under the reflex's own principal — the guard
344
344
  │ that re-checks reality. Duplicate unitKey refuses the run
345
- │ loudly; a transient seam failure DEFERS it.
345
+ │ loudly; a transient seam failure DEFERS it. Before the engine's
346
+ │ first load has finished this pass does nothing: every pending run
347
+ │ would read as one whose reflex was taken out. After it, a run whose
348
+ │ reflex a load left out is skipped, a load of nothing included.
346
349
  ├─ 4 CLAIM due tasks and lapsed leases, in one statement — exactly-once,
347
350
  │ `order: 'serial'` honoured inside the claim, `attempt`
348
351
  │ incremented as part of it, one fencing token per claim
@@ -437,9 +440,10 @@ archaeology project.
437
440
  **Retention is a policy, not an accident.** The ledger grows without bound unless told
438
441
  otherwise; `sweep(now, { facts?, runs?, tasks? })` deletes settled rows past a horizon,
439
442
  and the default is *keep forever*, which is the only honest default when the rows are
440
- billing history. Deleting a run takes its tasks with it — **⟲** independent horizons
441
- per table meant sweeping tasks could destroy the `UNIQUE(runId, unit)` row that *is*
442
- the "this unit already ran" record, and a restore would then re-charge the invoice.
443
+ billing history. Deleting a run takes its tasks with it. The `tasks` horizon removes
444
+ tasks settled before it whatever their run, and with them the record of a unit's
445
+ output. It never causes a second run: a run never fans out again, and `retry()` needs
446
+ the task it reopens.
443
447
 
444
448
  ### Execution semantics
445
449
 
@@ -462,7 +466,11 @@ The requirements doc calls this "the part that must not be hand-waved." In order
462
466
  `TideError` is tide's own refusal — a duplicate unit key, a missing `select` seam —
463
467
  so the reflex is wrong and will be wrong again next time: the run is `skipped`, with
464
468
  a note. Anything else came out of a host seam, and the run stays `pending` to be
465
- retried, which is a row past its due time that a query can see. **⟲** Every throw
469
+ retried after the reflex's retry wait, which is a row past its due time that a query
470
+ can see. **⟲** It was retried on every `advance`, read oldest first: a page of runs
471
+ whose database was down filled every pass, and no run behind them fanned out. The
472
+ wait is pacing only, so it lives in the engine's memory, not a column: a restart
473
+ costs one early attempt per deferred run, and loses nothing. **⟲** Every throw
466
474
  used to skip; because runs are idempotent on `(reflexId, cause)`, the occurrence
467
475
  could never re-materialize, so one unreachable database destroyed that night's
468
476
  billing run permanently — and since `skipped` is not `settled`, everything waiting on
@@ -500,6 +508,14 @@ The requirements doc calls this "the part that must not be hand-waved." In order
500
508
  `overlap: 'skip'` reflex was blocked permanently. The alternative designs — a reaper
501
509
  process, a heartbeat table, a liveness service — all add an organ; expiry adds a
502
510
  column, and the fencing token is what makes it safe.
511
+ - **A lease starts again as its effect starts.** One claim takes up to `limit` tasks and
512
+ runs them one after another, all leased from the advance's `now`; a late task could
513
+ start after its lease ran out, be claimed again by another instance, and run twice.
514
+ Tide reads no clock, so it cannot know how long a pass has taken; the host can. Given
515
+ `advance({ clock })` (the driver passes its own), the engine renews each task's lease
516
+ with a compare-and-set on this claim's token and attempt just before the effect, and
517
+ runs the effect only if that lands. Claiming fewer tasks was the alternative: it cost
518
+ throughput everywhere and still ran a task twice, since fan-out runs before the claim.
503
519
  - **Emits are buffered, validated, and narrowed.** `ctx.emit` facts commit with the
504
520
  successful attempt, in the same transaction; a throwing attempt discards its buffer,
505
521
  or every retry of an emit-then-throw handler would double-mint facts and fire the
@@ -580,7 +596,10 @@ rationalisation on top, and it failed open.
580
596
 
581
597
  **Identity equality** stops a fact crossing between tenants at every door —
582
598
  ingest (the bridge stamps `as` from the WRITE's own scope, mapped by the
583
- app's naming rule), fire, emit, and run-settlement. And within one tenant, a
599
+ app's naming rule), fire, emit, and run-settlement. A `manual` fact passes the
600
+ identity check before it skips enablement and arming: ⟲ it skipped both, so a
601
+ manual fact ingested as one tenant ran another tenant's reflex, disabled or not.
602
+ And `ingest` refuses a `run` fact: only the settler mints one. Within one tenant, a
584
603
  write fact is a STREAM: every reflex watching the entity hears the same fact,
585
604
  which is what makes "welcome them" and "tell the desk" two reflexes instead
586
605
  of one with two jobs.
@@ -599,9 +618,13 @@ rather than carefully avoided. The calendar edges are decided, not discovered:
599
618
 
600
619
  - `every: 'month', on: 31` **clamps to the last day of the month** — February bills on
601
620
  the 28th (29th), because "skip February" is never what a billing rule means.
602
- - A local time erased by spring-forward resolves to the **first valid instant after**;
603
- a local time that fall-back makes ambiguous takes the **first occurrence**. The key
604
- is identical either way.
621
+ - A local time erased by spring-forward is **shifted forward by the length of the gap**
622
+ (Vienna 02:30 → 03:30), as Temporal's `disambiguation: 'compatible'`; a local time
623
+ that fall-back makes ambiguous takes the **first occurrence**. The key is identical
624
+ either way. **⟲** The offset was probed half a day either side of the guess; in zones
625
+ at +12 and +13 a transition lies just outside that, so Auckland's 02:00 on the
626
+ spring-forward day fired at 01:00 and its repeated hour took the second occurrence.
627
+ It is probed a day either side: no zone is more than 14 h from UTC.
605
628
  - Timezone resolution uses the platform's IANA data (`Intl`), keeping the dependency
606
629
  count at zero. "03:00 in Vienna" and "03:00 in Denver" are both honest.
607
630
 
@@ -620,6 +643,19 @@ A **paused** reflex materializes nothing and keeps its watermark moving. A refle
620
643
  *entering* the loaded set re-baselines to the `at` passed to `load`. Both say the same
621
644
  thing: coming back is not the same as never having left.
622
645
 
646
+ What an engine knows of "entering" is its own memory, so after a restart every reflex
647
+ enters, and downtime is re-baselined away: `catchUp` never meets it. `load(…, { resume:
648
+ true })` is the opt-in that hands downtime to `catchUp`: a reflex this engine has never
649
+ loaded keeps the watermark the store has. A reflex left out of a load and brought back
650
+ by the same engine still re-baselines. Across a restart the engine cannot tell a reflex
651
+ that was away from one that was down — that needs a durable record of each reflex's
652
+ absence — so `resume` belongs on the load a process makes when it starts, never on an
653
+ engine made per request, whose every load would run what was missed since the last.
654
+ Whether `resume` should be the default is open.
655
+
656
+ Loads run one at a time, in the order they are called, so the set swapped in last is the
657
+ set passed last.
658
+
623
659
  **⟲ This is where the worst defect in the package lived.** A disarmed reflex was
624
660
  skipped outright, which froze its watermark at the moment of the pause. Eight days off
625
661
  meant eight occurrences materialized the instant it came back — and eight real effects
package/DOCS.md CHANGED
@@ -77,7 +77,11 @@ no reflexes are loaded. Signal and manual facts are always stored.
77
77
 
78
78
  `leaseMs` is the recovery story for a process that dies between the effect and
79
79
  the record. A task still `claimed` past its lease is claimable again; the
80
- fencing token is what makes that safe.
80
+ fencing token is what makes that safe. An effect whose `timeoutMs` is not
81
+ shorter than the lease can still be running when another instance claims its
82
+ task again, so `load` names each such reflex in `warnings`; it loads it all
83
+ the same. With a `clock` passed to `advance`, as the driver does, a task's
84
+ lease starts as its effect starts rather than when its claim was made.
81
85
 
82
86
  ---
83
87
 
@@ -181,7 +185,8 @@ for monthly, `2026-03-07` for daily/weekly, `2026` for yearly. A DST transition
181
185
  can move the instant a key fires at but cannot mint a second key or lose one.
182
186
  Day-31 clamps to month end (February bills on the 28th). An erased
183
187
  spring-forward local time shifts past the gap; an ambiguous fall-back time takes
184
- the first occurrence. Both match Temporal's `disambiguation: 'compatible'`.
188
+ the first occurrence. Both match Temporal's `disambiguation: 'compatible'`, in
189
+ every zone, those at +12 and +13 (Auckland, Chatham) included.
185
190
 
186
191
  A clock reflex with **no arming time** establishes its baseline on the first
187
192
  `advance` and mints nothing — materializing from the epoch would backfill decades.
@@ -193,6 +198,17 @@ nothing, not eight occurrences waiting to be minted the moment it comes back.
193
198
  A reflex that *enters* the loaded set re-baselines to the `at` passed to `load`,
194
199
  for the same reason: coming back is not the same as never having left.
195
200
 
201
+ **A restart re-baselines too, unless the load says `resume`.** An engine knows
202
+ only what it has loaded itself, so after a restart every reflex enters the set
203
+ and the downtime is passed over: a daily reflex down three days runs nothing
204
+ for them, and a one-shot clock due during the restart never fires.
205
+ `load(reflexes, { at, resume: true })` hands the downtime to each reflex's
206
+ `catchUp` instead: a reflex this engine has never loaded keeps the watermark
207
+ the store has. One left out of a load and brought back by the same engine
208
+ still re-baselines. Pass it on the load a process makes when it starts — not
209
+ on an engine made for each request, whose every load would then run what was
210
+ missed since the one before.
211
+
196
212
  **There is no poll.** A data change is a write fact the host pushes when it
197
213
  sees its own write; an external source with no write choke point enters through
198
214
  an importer that ingests write facts at the door. A poll could only re-discover
@@ -308,9 +324,8 @@ $ = { params, // the reflex's knobs
308
324
  ```
309
325
 
310
326
  Truthiness is one predicate, shared by the matcher and by `preview`: `false`,
311
- `null`, `undefined`, `0`, `''` and `[]` are all falsy. They used to disagree,
312
- and a `when` returning an empty list previewed as "this will fire" and then
313
- didn't — the exact surprise preview exists to eliminate.
327
+ `null`, `undefined`, `0`, `''` and `[]` are all falsy, so a `when` that
328
+ previews as "this will fire" fires.
314
329
 
315
330
  The honest cost of opacity: a typo'd `$ref` cannot be caught at load. It
316
331
  surfaces at `preview()` — which is why preview is the authoring loop's inner
@@ -342,8 +357,7 @@ type FactInput = {
342
357
  refuses the key fields of the others (`entity`, `name`, `target`, `runId`; a
343
358
  `signal` also refuses `op`). The rest are not checked by kind: a `write`
344
359
  accepts `payload`, `reflex`, `stats` and `by`. `{ kind: 'write' }` with no entity
345
- used to parse, store, match nothing, get marked delivered and vanish, with no
346
- way for the producer to learn its fact was never going to wake anything.
360
+ is refused by `ingest`, so the producer learns its fact could never wake anything.
347
361
 
348
362
  **Ops are distinct stimuli.** "Only on create" is `op: 'insert'`. Things that
349
363
  happen exactly once ride inserts naturally when the domain models intent as
@@ -358,24 +372,36 @@ cancellation token.
358
372
 
359
373
  **Dedupe is keyed on `(kind, entity, name, dedupeKey)`.** `entity` is in the key
360
374
  because two sources over different tables whose event ids happen to agree are
361
- not duplicates of each other, and without it one of them loses its rows.
375
+ not duplicates of each other, and without it one of them loses its rows. The
376
+ identity `ingest` is given is not in the key: a `dedupeKey` is unique across
377
+ the whole ledger, so two tenants ingesting the same event id under one kind,
378
+ entity and name keep only the first. A host whose keys are unique only within
379
+ a tenant puts the tenant in the key (`'tenant-a:evt_1'`).
362
380
 
363
381
  ---
364
382
 
365
383
  ## Verbs
366
384
 
367
385
  ```typescript
368
- load(reflexes, options?: { at?: number; isolate?: boolean }): Promise<LoadReport>
386
+ load(reflexes, options?: { at?: number; isolate?: boolean; resume?: boolean }): Promise<LoadReport>
369
387
  ```
370
388
  Validates, hashes versions, derives and verifies the graph, and arms. `at` is
371
389
  the host's boot time; arming persists, so a restart does not reopen the past.
390
+ `resume` is under [Triggers](#triggers): what a restart does to the occurrences it
391
+ missed. Loads run one at a time, in the order they are called: a second call
392
+ resolves after the first, and the set it was given is the one loaded. Before
393
+ the first load, `advance` matches no fact and fans out no run; both wait for it.
372
394
  `LoadReport` carries `{ loaded, cycles, blind, warnings, refused }` — guarded
373
395
  cycles are legal and reported; effects with no `writes` are reported as
374
- blind edges; `refused` has one entry for each reason `isolate` left a reflex
375
- out, as `{ reflexId, code, message }` (`reflexId` is undefined for one with no
376
- string `id`),
396
+ blind edges; `warnings` names a reflex that subscribes to its own run, a
397
+ reflex whose `timeoutMs` is not shorter than `leaseMs`, and a one-shot clock
398
+ whose date does not exist (`2026-02-30`), with the day it fires on (2 March);
399
+ `refused` has one entry for each reason `isolate` left a reflex out, as
400
+ `{ reflexId, code, message }` (`reflexId` is undefined for one with no string
401
+ `id`),
377
402
  and is empty without it. Calling it again is how a host changes what is running,
378
- including turning one off.
403
+ including turning one off. The tasks of a reflex left out are not claimed until
404
+ a load brings it back, so they spend no attempt while it is away.
379
405
 
380
406
  ```typescript
381
407
  ingest(fact: FactInput, options?: { as?: string; cause?: string; depth?: number }): Promise<Fact | undefined>
@@ -383,7 +409,8 @@ ingest(fact: FactInput, options?: { as?: string; cause?: string; depth?: number
383
409
  One write. Undefined means a `dedupeKey` collision — a refusal, not an error,
384
410
  announced as `fact.deduped` so a repeat is never mistaken for silence — or,
385
411
  under `storeUnwatchedWrites: false`, a write nothing watches, dropped silently.
386
- A fact that does not parse throws `invalid_fact`.
412
+ A fact that does not parse throws `invalid_fact`, and so does a `run` fact: tide
413
+ mints one when a run settles, and one ingested would forge that settlement.
387
414
  Matching happens in `advance`, against whatever is loaded when the fact comes
388
415
  due, which is what lets a delayed fact meet the reflexes of the day it fires.
389
416
 
@@ -394,8 +421,8 @@ signal. It is a second argument rather than a field on the fact because the
394
421
  fact shape is what a webhook body parses into: an identity a caller can choose
395
422
  is not an identity.
396
423
 
397
- The rule is strict — a fact with no identity reaches only reflexes with no
398
- identity. A single-tenant host names no `as` anywhere and is unaffected;
424
+ The rule is strict, and a `manual` fact keeps it too — a fact with no identity
425
+ reaches only reflexes with no identity. A single-tenant host names no `as` anywhere and is unaffected;
399
426
  a multi-tenant host that forgets one gets silence rather than a leak. An event
400
427
  that genuinely concerns every tenant is ingested once per tenant, by the only
401
428
  party that can know which those are.
@@ -409,13 +436,23 @@ inside the fact is discarded. Anything else ingests with neither: `depth`
409
436
  defaults to 0.
410
437
 
411
438
  ```typescript
412
- advance(options: { now: number; limit?: number }): Promise<AdvanceReport>
439
+ advance(options: { now: number; limit?: number; clock?: () => number }): Promise<AdvanceReport>
413
440
  ```
414
441
  Materialize → match → fan out → claim → execute → settle. Idempotent and
415
442
  safe to run concurrently. `limit` (default 100) bounds facts, fan-outs and
416
443
  claims per pass. A chain advances one hop per call, so the driver drains to quiescence and
417
444
  then sleeps until `nextDue`.
418
445
 
446
+ The tasks of one claim run one after another, and their leases start at
447
+ `now`, so a task late in a slow pass can start after its lease has run out,
448
+ when another instance may have claimed it again. `clock` is the host's clock:
449
+ given one, each task's lease starts again, from `clock()`, just before its
450
+ effect (never to end before the claim's, should the clock read earlier), and the effect runs only if the task is still this claim's. A task
451
+ another instance took back is left to it. That is one more write per task.
452
+ The driver passes its own `now`; without `clock`, nothing is renewed. The
453
+ guarantee assumes the instances' clocks agree to within `leaseMs − timeoutMs`,
454
+ as the lease already does.
455
+
419
456
  ```typescript
420
457
  type AdvanceReport = {
421
458
  now: number;
@@ -443,8 +480,9 @@ What is loaded now, as parsed.
443
480
  ```typescript
444
481
  fire(reflexId, { now, input?, by? }): Promise<Fact | undefined>
445
482
  ```
446
- Sugar over `ingest`: mints a `manual` fact aimed at one reflex, with `input` as
447
- its `payload` and `by` (default `'operator'`) recorded. Works on a
483
+ Sugar over `ingest`: mints a `manual` fact aimed at one reflex, under that
484
+ reflex's own `as`, with `input` as its `payload` and `by` (default `'operator'`)
485
+ recorded. Works on a
448
486
  **disarmed** reflex — arming gates triggers, not people. Throws
449
487
  `unknown_reflex` when the reflex is not loaded.
450
488
 
@@ -518,8 +556,7 @@ States: a task moves `pending → claimed → done | retrying | failed`; a run m
518
556
  `pending → fanned → settled`, or lands on `skipped` (overlap, catch-up, a
519
557
  refused fan-out, or a reflex no longer loaded — always with a `note`).
520
558
 
521
- `limit` means **the most recent N**, in every store. The two stores used to
522
- answer opposite ends of the same list under the same filter.
559
+ `limit` means **the most recent N**, in every store.
523
560
 
524
561
  **There is no attempt table.** Correctness needs the count and the last error,
525
562
  and both are on the task; per-attempt history is the host's log, which is where
@@ -532,9 +569,9 @@ is the only honest default when the rows are billing history:
532
569
  await tide.sweep(now, { facts: THIRTY_DAYS, runs: NINETY_DAYS });
533
570
  ```
534
571
 
535
- Removing a run removes its tasks with it. Keeping the tasks would destroy the
536
- `UNIQUE(runId, unit)` row that *is* the "this unit already ran" record, and a
537
- restore would then re-charge the invoice.
572
+ `facts` removes the facts delivered before its horizon, `runs` the runs that settled or were skipped
573
+ before its horizon and their tasks with them, and `tasks` the tasks settled
574
+ before its horizon, whatever their run.
538
575
 
539
576
  ---
540
577
 
@@ -548,7 +585,7 @@ logs at whatever grain it wants.
548
585
  | `run.created` | `run` | a run opened |
549
586
  | `run.settled` | `run` | its last task settled, or it fanned out to no tasks — once per run, not again after a `retry` |
550
587
  | `run.skipped` | `reflexId`, `reason` | overlap, or a fan-out tide refused |
551
- | `run.deferred` | `reflexId`, `runId`, `reason` | a fan-out failed in a host seam; retried next `advance` |
588
+ | `run.deferred` | `reflexId`, `runId`, `reason` | a fan-out failed in a host seam; retried after the reflex's retry wait |
552
589
  | `task.done` / `task.failed` | `task` | an attempt recorded a terminal outcome |
553
590
  | `task.retrying` | `task`, `nextAt` | an attempt threw or timed out with retries left |
554
591
  | `task.reclaimed` | `task` | a lapsed lease was taken back |
@@ -629,7 +666,11 @@ of one operation and diverged three ways.
629
666
  second loses the race. `onePer: { column, held, only }` lets at most one row
630
667
  per value of `column` be held at a time, counting rows that match `held`
631
668
  from an earlier claim; it applies to the values listed in `only`, and every
632
- other value claims freely.
669
+ other value claims freely. A value in `only` with nothing to claim takes no
670
+ room from the others. A store should take the values in `only` first, one row
671
+ each, and give what they leave of `limit` to the other rows, as both of
672
+ tide's stores do: taken strictly in `order`, a busy reflex outside `only` can
673
+ fill every claim before a serial one's row is reached.
633
674
  - **`cas`** is the fence: a timed-out attempt finishing late finds its token
634
675
  superseded and is discarded. Setting a field to `undefined` clears it.
635
676
  - **`transact`** is required. Fan-out committing with its run's transition, and
@@ -690,7 +731,9 @@ A `TideStore` over four tables: `tide_fact`, `tide_run`, `tide_work`,
690
731
  `tide_reflex_state` (`TIDE_TABLES`). `appendIfAbsent` is `ON CONFLICT DO
691
732
  NOTHING` on the key `UNIQUE_BY` names; `claim` is one `UPDATE … FOR UPDATE SKIP
692
733
  LOCKED`; the state columns carry CHECK constraints; deleting a run cascades to
693
- its work.
734
+ its work. The ids it mints for `fact`, `run` and `task` rows are UUIDs (rows
735
+ written by an earlier version keep theirs: an id is text, and nothing reads its
736
+ shape).
694
737
 
695
738
  - **`pool`** is a `TidePool`: `{ query(text, values?), transaction?(fn) }`. It
696
739
  is a type of the store's own, and structural: vex's `PgPool`, a PGlite behind
@@ -710,6 +753,11 @@ its work.
710
753
  - **A row is read by a schema.** What comes back from the database is parsed,
711
754
  one schema for each table: a row that does not fit throws where it is read,
712
755
  naming the table and the field.
756
+ - **A string in a JSON column.** A payload, an input or an output that is a
757
+ string reads back as itself when it is not JSON text (`'hello'`). On a
758
+ driver that parses jsonb itself (`pg`, PGlite) one that is JSON text reads
759
+ back parsed: `'123'` as `123`, `'{"a":1}'` as `{ a: 1 }`. A host that needs
760
+ such a string back exactly puts it inside an object.
713
761
  - **A serial group is claimed by one instance at a time.** Asking whether a
714
762
  group is held and claiming in it run in one transaction, behind an advisory
715
763
  lock on the group (`pg_try_advisory_xact_lock`). An instance that does not
@@ -751,8 +799,9 @@ A `TideDriver` is `{ ingest, fire, wake, stop }`. Hand a host's intake the
751
799
  driver, not the bare engine, so a fact wakes it instead of waiting for
752
800
  somebody's beat. `stop()` resolves once nothing the driver started still
753
801
  touches the store: await it before closing the database. `now` replaces the
754
- clock (`Date.now`); `janitorMs` defaults to 5 minutes; absent `retention`,
755
- nothing is swept. What it logs, it logs as `[tide:driver]`.
802
+ clock (`Date.now`), and is what the driver passes to `advance` as both `now`
803
+ and `clock`; `janitorMs` defaults to 5 minutes; absent `retention`, nothing is
804
+ swept. What it logs, it logs as `[tide:driver]`.
756
805
 
757
806
  ---
758
807
 
@@ -807,7 +856,9 @@ often does not. It is told to write every date it drafts or asks about with
807
856
  its weekday ("Fri 2026-11-06"), and a date its reasoning writes beside the wrong
808
857
  weekday is sent back in the same run with the weekday it is, as is a date that
809
858
  does not exist. How it words a date is its own: a draft is never sent back for
810
- that, so a date it writes some other way is not checked.
859
+ that, so a date it writes some other way is not checked. The draft itself is: a
860
+ one-shot clock whose date does not exist (`2026-02-30`, which would fire on
861
+ 2 March) is sent back too, whatever the reasoning says.
811
862
 
812
863
  ```typescript
813
864
  const agent = createReflexAgent({ effects, triggers: ['clock', 'timer'] });
@@ -839,13 +890,13 @@ if (result.ok && isDraft(result.output.data)) {
839
890
  | Code | Raised when |
840
891
  |---|---|
841
892
  | `invalid_reflex` | a reflex failed `ReflexSchema` — including `when` on a non-fact trigger and `each` with no `unitKey` |
842
- | `invalid_fact` | a fact failed `FactInputSchema`, or a handler emitted one that did, or emitted a kind other than `write` / `signal` |
893
+ | `invalid_fact` | a fact failed `FactInputSchema`, or `ingest` was given a `run` fact, or a handler emitted one that did not parse, or emitted a kind other than `write` / `signal` |
843
894
  | `duplicate_reflex` | two reflexes share an id |
844
895
  | `unknown_reflex` | `fire`/`preview` named a reflex that is not loaded, or `load` found a reflex watching the run of one that is not there |
845
896
  | `unguarded_cycle` | `load` found a loop on which no reflex has a `select` or a `when` |
846
897
  | `unknown_effect` | `load` found a reflex naming an effect that is not registered |
847
898
  | `no_transform` | in `TideErrorCode`; not raised — `transform` is a required config field |
848
- | `duplicate_unit` | a selection's `unitKey` was not unique, or `maxFanOut` was exceeded |
899
+ | `duplicate_unit` | a selection's `unitKey` was not unique, or `maxFanOut` was exceeded. Never thrown to a caller: the run is skipped with the message as its `note`, and `preview` answers it as `reason` |
849
900
  | `store` | a selection exists but no `select` seam is wired |
850
901
 
851
902
  `load` checks the whole graph in one pass. When it refuses, `details.errors`
@@ -862,7 +913,16 @@ A `TideError` is tide's own refusal — a duplicate unit key, a missing `select`
862
913
  seam — which means the reflex is wrong and will be wrong again next `advance`, so the
863
914
  run is `skipped` with a note. Anything else came out of a host seam: a
864
915
  selection, a transform, a database. That is a bad minute, not a bad reflex, so
865
- the run stays `pending` and is retried — a row past its due time that a query
866
- can see. Every throw used to skip, and because runs are idempotent on
867
- `(reflexId, cause)`, one database hiccup destroyed that night's billing run
868
- permanently.
916
+ the run stays `pending` and is tried again after a wait — a row past its due
917
+ time that a query can see. The wait is the reflex's own `policy.retry`: after
918
+ the n-th deferral it is `baseMs` with `backoff: 'fixed'`, and
919
+ `baseMs · 2^(min(n, max) − 1)` with `'exponential'` — with the defaults 60 s,
920
+ 120 s, 240 s, then 240 s for good. `max` does not end the run, and nothing caps
921
+ the wait but the largest whole number of milliseconds (about 285 000 years): a
922
+ large `max` makes a long wait, `max: 20` with the default `baseMs` 364 days.
923
+ While a run waits, the pending runs behind it fan out. Each engine keeps its own
924
+ waits, in memory: after a restart each deferred run is tried once at once, then
925
+ waits again, and two instances each pace it by their own count. A run another
926
+ instance fans out or skips is forgotten on the next pass. Skipping it instead would
927
+ lose it for good: runs are idempotent on `(reflexId, cause)`, so the occurrence
928
+ cannot open a second run.
package/README.md CHANGED
@@ -90,7 +90,9 @@ await tide.retry(taskId, now); // reopen a failed task
90
90
  await tide.preview('billing.dunning', { now }); // show me, change nothing
91
91
  ```
92
92
 
93
- **There is no `arm`/`disarm`.** Enablement is a property of the reflex the host hands over, so pausing one is: write your own row, `load` again. One source of truth, it survives a restart, and it leaves something to audit. There used to be a pair of methods that mutated an in-memory map; they were a second copy of a fact the host already owned, and they disagreed with it the moment either moved.
93
+ **Pausing a reflex is an edit of its row.** Enablement is a property of the reflex the host hands over: set `enabled: false` on your own row and `load` again. It survives a restart, and it leaves something to audit.
94
+
95
+ **A restart passes over the clock occurrences it missed**, unless the first load the process makes says `load(reflexes, { at, resume: true })`: then each reflex's `catchUp` decides what the downtime runs.
94
96
 
95
97
  ## Storage
96
98
 
@@ -130,7 +132,7 @@ A model can WRITE a reflex; it never runs one. `createReflexAgent({ effects, tri
130
132
 
131
133
  The draft's shape is built from that choice (`draftSchemaOf`, from tide's own schemas, each with its description) — it is what the model is shown and what it is held to. A draft never carries who it runs as, its policy or whether it is enabled: those are the host's, and `anchorDraft` completes them. Its `id` is only a short name the model makes up, and never asks for — the host may give the stored reflex its own id when it is saved; and a `run` trigger names another reflex's id, so a host that offers it must tell the model which reflexes exist.
132
134
 
133
- It answers with ONE of three things (`answerSchemaOf`): a reflex draft; a `{ question }` back, when the request can be read as different automations and nothing in the conversation decides which; or a `{ refused }`, when no offered effect does what was asked. A question ends the run like any answer — nothing waits. When the person answers it, or corrects a draft they have not saved, the host runs the agent again over the conversation: `reflexConversation({ now, tz, earlier, latest })` turns the earlier requests and the agent's answers to them — as it gave them, reasoning first — and the latest words into the turns of a chat. A draft naming an effect that is not offered, or an input that effect's schema refuses, goes back to the model to correct in the same run (`effectProblem`). So does a date that is not the weekday the agent says it is: it is told today, the coming days and two months, written from `now`, to look dates up there rather than count them. A date written beside the wrong weekday, or one that does not exist, is all that is sent back: how the agent words a date is its own. The host shows it, and when somebody saves it, anchors it (`anchorDraft`) and decides who it runs as (`as`); from then on it runs with no model at all. Cortex is an optional peer, used only by this subpath.
135
+ It answers with ONE of three things (`answerSchemaOf`): a reflex draft; a `{ question }` back, when the request can be read as different automations and nothing in the conversation decides which; or a `{ refused }`, when no offered effect does what was asked. A question ends the run like any answer — nothing waits. When the person answers it, or corrects a draft they have not saved, the host runs the agent again over the conversation: `reflexConversation({ now, tz, earlier, latest })` turns the earlier requests and the agent's answers to them — as it gave them, reasoning first — and the latest words into the turns of a chat. A draft naming an effect that is not offered, or an input that effect's schema refuses, goes back to the model to correct in the same run (`effectProblem`). So does a date that is not the weekday the agent says it is: it is told today, the coming days and two months, written from `now`, to look dates up there rather than count them. A date written beside the wrong weekday, or one that does not exist, is all that is sent back: how the agent words a date is its own. A draft whose one-shot clock names a date that does not exist (`2026-02-30`) is sent back as well. The host shows it, and when somebody saves it, anchors it (`anchorDraft`) and decides who it runs as (`as`); from then on it runs with no model at all. Cortex is an optional peer, used only by this subpath.
134
136
 
135
137
  A draft's trigger may be a **timer** — `{ "timer": { "minutes": 5 } }`, "this long from now". A timer is sugar and is never stored: `anchorDraft(draft, { at, tz })` fixes it to a one-shot clock at the moment of saving plus its length, to the second (rounded up — never short), so time spent reading the draft is not taken off it, and a restart re-loads the same instant.
136
138
 
package/dist/agent.cjs CHANGED
@@ -59,6 +59,7 @@ var TriggerSchema = zod.z.union([
59
59
  RunTriggerSchema,
60
60
  ManualTriggerSchema
61
61
  ]);
62
+ var isRecurring = (clock) => "every" in clock;
62
63
  var RetrySchema = zod.z.object({
63
64
  max: zod.z.number().int().min(0).default(3).describe("Attempts after the first before the task parks `failed`."),
64
65
  backoff: zod.z.enum(["fixed", "exponential"]).default("exponential"),
@@ -181,6 +182,7 @@ var whenItIs = (now) => {
181
182
  `CALENDAR \u2014 ${monthLine(today.y, today.m)}; ${monthLine(next.y, next.m)}`
182
183
  ].join("\n");
183
184
  };
185
+ var clockDateProblems = (at) => at === void 0 || dayOf(at) !== void 0 ? [] : [`The clock's date ${at.slice(0, 10)} is not a date. Look the date up in COMING DAYS or CALENDAR.`];
184
186
  var PAIRED = /\b(mon|tue|wed|thu|fri|sat|sun)(?:day|sday|s|nesday|rsday|rs|urday)?\.?,?\s+(\d{4}-\d{2}-\d{2})(?!\d)/gi;
185
187
  var dateProblems = (reasoning) => {
186
188
  const found = [...(reasoning ?? "").matchAll(PAIRED)].map((match) => ({
@@ -259,6 +261,7 @@ var effectProblem = (effects, reflex) => {
259
261
  const issues = parsed.error.issues.map((issue) => `${issue.path.join(".") || "input"}: ${issue.message}`).join("; ");
260
262
  return `The input for "${effect.name}" does not fit its schema \u2014 ${issues}.`;
261
263
  };
264
+ var oneShotAt = (answer) => isDraft(answer) && "clock" in answer.on && !isRecurring(answer.on.clock) ? answer.on.clock.at : void 0;
262
265
  var createReflexAgent = (config) => cortex.defineAgent({
263
266
  id: "tide.reflex",
264
267
  description: "Answers what somebody wants automated with one tide reflex draft, a question back, or a refusal.",
@@ -268,7 +271,7 @@ var createReflexAgent = (config) => cortex.defineAgent({
268
271
  schema: answerSchemaOf(config),
269
272
  validate: (envelope) => {
270
273
  const effect = isDraft(envelope.data) ? effectProblem(config.effects, envelope.data) : void 0;
271
- const problems = [...effect === void 0 ? [] : [effect], ...dateProblems(envelope.reasoning)];
274
+ const problems = [...effect === void 0 ? [] : [effect], ...clockDateProblems(oneShotAt(envelope.data)), ...dateProblems(envelope.reasoning)];
272
275
  return problems.length === 0 ? { ok: true } : { retry: problems.join("\n") };
273
276
  }
274
277
  }