@niscorp/tide 0.1.5 → 0.1.7
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 +45 -0
- package/DESIGN.md +43 -17
- package/DOCS.md +114 -9
- package/README.md +14 -2
- package/dist/agent.cjs +3 -9
- package/dist/agent.cjs.map +1 -1
- package/dist/agent.js +1 -3
- package/dist/agent.js.map +1 -1
- package/dist/{chunk-UEG3UZDG.js → chunk-4TXWZFRE.js} +5 -13
- package/dist/chunk-4TXWZFRE.js.map +1 -0
- package/dist/chunk-7KHOAJNL.js +19 -0
- package/dist/chunk-7KHOAJNL.js.map +1 -0
- package/dist/index.cjs +107 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -1
- package/dist/index.d.ts +19 -1
- package/dist/index.js +107 -71
- package/dist/index.js.map +1 -1
- package/dist/postgres.cjs +590 -0
- package/dist/postgres.cjs.map +1 -0
- package/dist/postgres.d.cts +26 -0
- package/dist/postgres.d.ts +26 -0
- package/dist/postgres.js +472 -0
- package/dist/postgres.js.map +1 -0
- package/dist/testing.cjs +0 -6
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js +0 -6
- package/dist/testing.js.map +1 -1
- package/package.json +20 -3
- package/dist/chunk-UEG3UZDG.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,50 @@
|
|
|
1
1
|
# @niscorp/tide
|
|
2
2
|
|
|
3
|
+
## 0.1.7
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 9b7ccbe: DOCS.md states nine facts about the API that were written only in source comments.
|
|
8
|
+
|
|
9
|
+
They are: what `maxFanOut` counts and that a run over it is skipped; what a fact's `depth`, `deliveredAt` and `root` hold; what a task's `unit` and `claimedUntil` hold; what `appendIfAbsent` returns, that the store mints a missing `id`, and when a `UNIQUE_BY` key with `when` applies; and what `onePer` limits in a claim.
|
|
10
|
+
|
|
11
|
+
One statement is corrected. DESIGN.md said a run's cause can be a run id or `manual:<who>`. A run's `cause` is `occurrence:<key>` or `fact:<id>`; who fired a reflex by hand is the manual fact's `by`. DOCS.md now lists the forms of a run's and a fact's `cause`.
|
|
12
|
+
|
|
13
|
+
No behaviour changed.
|
|
14
|
+
|
|
15
|
+
**What to change:** nothing.
|
|
16
|
+
|
|
17
|
+
## 0.1.6
|
|
18
|
+
|
|
19
|
+
### Patch Changes
|
|
20
|
+
|
|
21
|
+
- 7fb8322: Tide's Postgres store and its driver ship from tide. They were in `@niscorp/moss`.
|
|
22
|
+
|
|
23
|
+
**A new entry point, `@niscorp/tide/postgres`: the store.**
|
|
24
|
+
- `createTideStore(pool, options?)` answers a `TideStore` plus `ready: Promise<void>`, over four tables it migrates itself through a strata ledger. With it come `TIDE_SEQUENCE` (the tables, as a strata sequence, for an app that migrates them in its own run), `TIDE_TABLES`, `TIDE_DDL`, and the types `TideStoreOptions`, `TidePool` and `TidePoolQuery`.
|
|
25
|
+
- The pool is a type of the store's own, `TidePool`: `query(text, values?)`, and `transaction(fn)`. Vex's `PgPool`, a PGlite behind a shim and a `pg` pool that checks a client out for each transaction are each one. Tide imports no driver and no host.
|
|
26
|
+
- `@niscorp/strata` is a new peer, and it is OPTIONAL: only this entry point imports it. An app that uses `@niscorp/tide/postgres` installs strata; an app on the memory store or a store of its own does not.
|
|
27
|
+
- The sequence is the one every database that kept tide's tables under moss has run: its id is still `nisc.moss.tide`, and its migrations, their order and their steps are unchanged. A database migrated by an earlier release finds nothing pending.
|
|
28
|
+
- A row the store reads back is read by a schema, one for each table. A row that does not fit (a state the engine has no name for, a number where text belongs) throws where it is read, naming the table and the field. It used to be handed to the engine as it was.
|
|
29
|
+
- What a `where` compares a field with (`{ lte: 5 }`, `{ in: [...] }`) is read by a schema too. One that does not fit (`in` that is not a list, `isNull` that is not a boolean) throws, naming the field. The types of `Where` already refuse such a call, so nothing written against them changes.
|
|
30
|
+
|
|
31
|
+
**New in the main entry: the driver.**
|
|
32
|
+
- `createTideDriver({ tide, now?, janitorMs?, retention? })` answers a `TideDriver`: `ingest` and `fire` that wake the engine, `wake()`, and `stop()`. It advances to quiescence on every ingest, sleeps until the instant `nextDue` names, and sweeps on a slow beat. The types `TideDriver` and `TideDriverConfig` come with it.
|
|
33
|
+
- The engine still reads no clock and sets no timer. The driver is what does, for a host that does not want to write those twenty lines.
|
|
34
|
+
- **What the driver logs begins `[tide:driver]`.** It began `[moss:tide-driver]` while the driver was moss's. There are four such lines, all to `console.error`: a drain that exceeded its 10,000 steps, a next-due read that failed, a wake that threw, and a sweep that failed. A deployment that searches its logs for the old prefix, or alerts on it, searches for the new one.
|
|
35
|
+
|
|
36
|
+
**Two instances cannot both claim in one serial group.**
|
|
37
|
+
- A reflex with `order: 'serial'` runs one task at a time: the store claims in its group only when no task of it is held. The Postgres store asked whether the group was held and then claimed, as two statements. With two processes on one database, both could ask before either claimed, and each took a task: two tasks of a serial reflex ran at once.
|
|
38
|
+
- The two statements now run in one transaction, behind an advisory lock on the group (`pg_try_advisory_xact_lock`) that ends with the transaction. An instance that does not get the lock leaves the group to the one that has it; nothing waits.
|
|
39
|
+
- Shown on PostgreSQL 18.4 with two pools claiming at once (300 rounds, and 150 rounds of four claims each): exactly one held every round, and two held in 299 of 300 with the lock taken out. No test in the repository holds this: PGlite has one connection, so two claimers never meet there.
|
|
40
|
+
- `createTideStore` over a pool with no `transaction` now refuses a serial claim with the sentence `transact` already refused with. Such a pool could not run tide before: fan-out is a transaction.
|
|
41
|
+
|
|
42
|
+
**A wait longer than a timer can hold no longer makes the driver a loop.**
|
|
43
|
+
- The driver sleeps until the instant `nextDue` names, with one timer. Node keeps a timer's delay in 32 bits: one over 2^31 − 1 ms (24.8 days) is not refused, it is set to 1 ms, with a `TimeoutOverflowWarning`. A reflex whose next occurrence was further off than that had the driver wake every millisecond, advance, find nothing and ask again. Every wait is cut to 2^31 − 1 ms now: the driver wakes then, finds nothing, and waits out the rest.
|
|
44
|
+
- The same for a `janitorMs` set that long, which beat every millisecond.
|
|
45
|
+
|
|
46
|
+
**What to change:** nothing, for an app that did not take these from moss. One that did imports them from here: see the moss changeset.
|
|
47
|
+
|
|
3
48
|
## 0.1.5
|
|
4
49
|
|
|
5
50
|
### Patch Changes
|
package/DESIGN.md
CHANGED
|
@@ -77,7 +77,9 @@ of those properties. Tide exists so that piece never has to be written.
|
|
|
77
77
|
the instant `nextDue(now)` names — a clock occurrence, a retry backoff, a lease
|
|
78
78
|
lapse, a delayed fact. Tide tells the driver when it wants waking; the driver owns
|
|
79
79
|
the timer. A slow janitor beat recovers what a crashed process left behind — it is
|
|
80
|
-
how work is FOUND, never how work moves.
|
|
80
|
+
how work is FOUND, never how work moves. `createTideDriver` is that driver,
|
|
81
|
+
shipped beside the engine for a host that does not write its own: the one piece
|
|
82
|
+
of the package that reads a clock to decide when the engine runs. A dev check is its own driver, handing
|
|
81
83
|
`advance` a fake `now` and asserting on rows.
|
|
82
84
|
|
|
83
85
|
7. **One effect per reflex, and effects are opaque named calls.** The effect
|
|
@@ -246,8 +248,8 @@ Three kinds (and two more fact flavours). Structured on purpose — a reflex is
|
|
|
246
248
|
|
|
247
249
|
Any reflex — whatever its trigger — may additionally be fired by hand through
|
|
248
250
|
`fire(reflexId, { now, input?, by? })`, **including a disarmed one**: arming gates *triggers*, not
|
|
249
|
-
people, and testing before arming is half of what `fire` is for; the
|
|
250
|
-
|
|
251
|
+
people, and testing before arming is half of what `fire` is for; the manual fact
|
|
252
|
+
records who fired in its `by` either way. A `manual` trigger just means *only* by hand. And `fire`
|
|
251
253
|
is sugar over `ingest`: it mints a `manual` fact aimed at one reflex — `at` supplied
|
|
252
254
|
by the caller, like every fact — so even the human verb enters through the one intake
|
|
253
255
|
and reads no clock.
|
|
@@ -391,8 +393,8 @@ a guarantee nothing else can:
|
|
|
391
393
|
|
|
392
394
|
- **`fact`** — everything that arrived: kind, payload, `dedupeKey`, depth, delivery,
|
|
393
395
|
any park. The intake log *is* the audit trail of change.
|
|
394
|
-
- **`run`** — one activation of one reflex: the cause (occurrence
|
|
395
|
-
|
|
396
|
+
- **`run`** — one activation of one reflex: the cause (`occurrence:<key>` or
|
|
397
|
+
`fact:<id>`), the version hash, the identity it ran `as`, what the selection
|
|
396
398
|
returned, the counts, the outcome.
|
|
397
399
|
- **`task`** — one unit of effect work: unit key, pinned `env`, state, attempt count,
|
|
398
400
|
last error, and the handler's returned **output** — stored, which is what makes
|
|
@@ -739,7 +741,7 @@ the argument that tide is a *nisc* library and not a scheduler with JSON config:
|
|
|
739
741
|
|
|
740
742
|
| Seam | Contract | The host injects | Precedent |
|
|
741
743
|
|---|---|---|---|
|
|
742
|
-
| `store` | `TideStore` — six capabilities over four tables (below) | `createMemoryStore()
|
|
744
|
+
| `store` | `TideStore` — six capabilities over four tables (below) | `createMemoryStore()`, or `createTideStore(pool)` from `@niscorp/tide/postgres` for persistence; or a store of the host's own | vex's `CacheBackend` — structural, driver-free |
|
|
743
745
|
| `transform` | `(config, source) => value` | Prism's `evaluate`, or anything | **nova's exact socket** — nova doesn't know Prism; neither does tide |
|
|
744
746
|
| `select` | `(query, ctx) => AsyncIterable<row>` — the query blob is opaque | vex replay under the actor's policy; or raw SQL; or an array | vex's `generateDsl` / `mapToShape` |
|
|
745
747
|
| `effects` | `name → { run(input, ctx), writes?, preview? }` | vex mutation replays, fns, cortex agents; or plain functions | moss's `functions` seam |
|
|
@@ -750,7 +752,8 @@ in, **`advance({ now, limit })`** to run one committed increment, and
|
|
|
750
752
|
**`nextDue(now)`** so the driver knows when next to wake.
|
|
751
753
|
|
|
752
754
|
Dependencies: **`zod`**. Nothing else — the same bar charter clears. (The
|
|
753
|
-
`/agent` entry imports `@niscorp/cortex`,
|
|
755
|
+
`/agent` entry imports `@niscorp/cortex`, and the `/postgres` entry
|
|
756
|
+
`@niscorp/strata`: optional peers both, and the engine imports neither.)
|
|
754
757
|
|
|
755
758
|
### The store contract
|
|
756
759
|
|
|
@@ -785,8 +788,8 @@ implements.
|
|
|
785
788
|
|
|
786
789
|
`STORE_CONTRACT`, exported from `@niscorp/tide/testing`, is the executable definition
|
|
787
790
|
of everything above: a list of `{ name, run(store) }` checks that throw, with no test
|
|
788
|
-
framework, so any runner can drive them. The memory store runs it;
|
|
789
|
-
runs the same list against a real database.
|
|
791
|
+
framework, so any runner can drive them. The memory store runs it; the Postgres
|
|
792
|
+
store runs the same list against a real database (`test/postgres-store.test.ts`).
|
|
790
793
|
|
|
791
794
|
**⟲ This exists because of the store that was deleted.** `store/postgres.ts` was 700
|
|
792
795
|
lines, had never been instantiated anywhere in this repo, and claimed in its own header
|
|
@@ -798,17 +801,23 @@ the retention horizon; three transactional methods that skipped the ready-guard
|
|
|
798
801
|
raised `undefined_table` *inside* a transaction. Every one was invisible. The lesson is
|
|
799
802
|
not "write more tests" — it is that a contract nobody can execute is a comment.
|
|
800
803
|
|
|
804
|
+
The store at that path today is not that one. It was written in moss against the
|
|
805
|
+
contract, held to `STORE_CONTRACT` and to the engine's own scenarios on a real
|
|
806
|
+
database, and moved here with those tests when it was plain that it is tide's storage
|
|
807
|
+
and not a host's.
|
|
808
|
+
|
|
801
809
|
---
|
|
802
810
|
|
|
803
811
|
## Hosts
|
|
804
812
|
|
|
805
813
|
### Moss — the reference host
|
|
806
814
|
|
|
807
|
-
Moss fills every seam,
|
|
815
|
+
Moss fills every seam but the store, which is tide's own:
|
|
808
816
|
|
|
809
817
|
| Tide seam | Moss fills it with |
|
|
810
818
|
|---|---|
|
|
811
|
-
| `store` | **`createTideStore(pool)`** — four tables beside `vex_cache`, `ON CONFLICT DO NOTHING` for `appendIfAbsent`, `FOR UPDATE SKIP LOCKED` for `claim`, CHECK constraints on every state column, and a foreign key that cascades work with its run |
|
|
819
|
+
| `store` | **`createTideStore(pool)`** from `@niscorp/tide/postgres`, on the pool the app's runtime holds — four tables beside `vex_cache`, `ON CONFLICT DO NOTHING` for `appendIfAbsent`, `FOR UPDATE SKIP LOCKED` for `claim`, CHECK constraints on every state column, and a foreign key that cascades work with its run |
|
|
820
|
+
| facts in | `createTideFacts` (`@niscorp/moss/tide`), a feature of moss: every write vex commits is minted as a `write` fact, stamped with the identity the write's own scope names |
|
|
812
821
|
| `select` | vex replay **through the actor's own wire** — selection inherits replay-only, scoped, cached, inspectable; the tenant filter is in the SQL, engine-injected, unforgeable |
|
|
813
822
|
| `effects` | every seeded vex **mutation** auto-registered under its fingerprint (with `writes` *derived* from `mutationEffect`) + the app's `effects(actor)` |
|
|
814
823
|
| `transform` | prism — the same wiring the shell's transform socket already gets |
|
|
@@ -854,7 +863,7 @@ tide.load(reflexes, { at: Date.now() });
|
|
|
854
863
|
app.post('/webhook/stripe', (req) => tide.ingest(toFact(req))); // validate at the boundary first
|
|
855
864
|
|
|
856
865
|
// The driver: wake on ingest, drain to quiescence, sleep until nextDue.
|
|
857
|
-
// (
|
|
866
|
+
// (`createTideDriver` is these lines, written once, with the sleep and a janitor.)
|
|
858
867
|
const drain = async () => { for (;;) { const r = await tide.advance({ now: Date.now() }); if (isQuiet(r)) break; } };
|
|
859
868
|
```
|
|
860
869
|
|
|
@@ -869,7 +878,8 @@ theirs to keep. `ctx.emit` is how a chain continues without a write choke point.
|
|
|
869
878
|
|
|
870
879
|
```
|
|
871
880
|
src/
|
|
872
|
-
index.ts Public API barrel — createTide, schemas, the store contract
|
|
881
|
+
index.ts Public API barrel — createTide, schemas, the store contract, the driver
|
|
882
|
+
driver.ts createTideDriver — wake on ingest, sleep until nextDue, a janitor
|
|
873
883
|
testing.ts STORE_CONTRACT — the executable definition of a store (the ./testing entry)
|
|
874
884
|
tide.ts createTide: load, ingest, advance, nextDue, fire, retry, preview, ledger, sweep
|
|
875
885
|
types.ts ledger rows, seam types, TideStore, UNIQUE_BY, reports
|
|
@@ -898,6 +908,14 @@ src/
|
|
|
898
908
|
|
|
899
909
|
store/
|
|
900
910
|
memory.ts createMemoryStore — the reference implementation + snapshot()
|
|
911
|
+
postgres/ the Postgres store — the ./postgres entry; the only directory that imports strata
|
|
912
|
+
index.ts the door: createTideStore, TIDE_SEQUENCE, TIDE_TABLES, TIDE_DDL, TidePool
|
|
913
|
+
pool.ts the pool the store runs on, as much of one as it uses
|
|
914
|
+
tables.ts the four tables, and the strata sequence that makes them
|
|
915
|
+
rows.ts a row and an entity, both directions, read by a schema
|
|
916
|
+
compile.ts a where, an order and a set, compiled to SQL
|
|
917
|
+
claim.ts the claim: one statement, and one instance at a time in a serial group
|
|
918
|
+
store.ts createTideStore: the six capabilities over a pool
|
|
901
919
|
|
|
902
920
|
agent/
|
|
903
921
|
reflex-agent.ts createReflexAgent — the ./agent entry; the only file that imports cortex
|
|
@@ -909,7 +927,11 @@ test/
|
|
|
909
927
|
durability.test.ts one test per defect that reached the built engine
|
|
910
928
|
load.test.ts the load gate: validation, cycles, versioning
|
|
911
929
|
preview.test.ts dry run writes nothing and shows everything
|
|
912
|
-
store.test.ts STORE_CONTRACT ×
|
|
930
|
+
store.test.ts STORE_CONTRACT × the memory store
|
|
931
|
+
postgres-store.test.ts STORE_CONTRACT × the Postgres store, in two pool shapes; a serial group and two instances
|
|
932
|
+
postgres-engine.test.ts the engine's scenarios on a real database
|
|
933
|
+
baselines.test.ts the checksum of each migration of TIDE_SEQUENCE, pinned
|
|
934
|
+
driver.test.ts the driver: stopping, and a wait longer than a timer holds
|
|
913
935
|
anchor.test.ts a draft's timer, anchored when it is saved
|
|
914
936
|
agent.test.ts the reflex agent — its answer schemas, effect check and conversation turns
|
|
915
937
|
support.ts shared fixtures
|
|
@@ -920,8 +942,12 @@ test/
|
|
|
920
942
|
orchestrator. There is no `verbs.ts`: `fire` is four lines of sugar over `ingest`,
|
|
921
943
|
and `retry` belongs beside the executor whose invariants it rewinds.
|
|
922
944
|
|
|
923
|
-
|
|
924
|
-
|
|
945
|
+
`store/postgres/` is here, and **tide still imports no host**. Persistence is where
|
|
946
|
+
that rule earns its keep, and the store keeps it: the pool it runs on is a type it
|
|
947
|
+
writes out itself (`TidePool`), the one package it imports is strata, for the ledger
|
|
948
|
+
its tables are migrated through, and it sits on an entry point of its own so that
|
|
949
|
+
nothing the engine's entry reaches imports even that. What stays in moss is what only
|
|
950
|
+
a host can do: turning its own writes into facts.
|
|
925
951
|
|
|
926
952
|
---
|
|
927
953
|
|
|
@@ -1040,7 +1066,7 @@ The wishlist, answered — including its own open questions:
|
|
|
1040
1066
|
| Per-tenant config, instant disarm, versioning across runs | reflexes are tenant rows; disarming is the host's row write + `load` (§ decision 11); content-hash versions (§ decision 14) |
|
|
1041
1067
|
| Host-agnostic wake-up; serverless and local both | `advance({ now })` + `nextDue(now)`: the driver wakes on ingest and sleeps until the next due instant; its janitor beat is recovery, not pacing |
|
|
1042
1068
|
| Deterministic headless checks | memory store + fake clock; no timers exist to wait on |
|
|
1043
|
-
| Durable across restarts | `createTideStore(pool)
|
|
1069
|
+
| Durable across restarts | `createTideStore(pool)`, `@niscorp/tide/postgres`; the memory store remains the reference and the check harness |
|
|
1044
1070
|
| Wishlist: dependency between automations | run facts — `on: { fact: { run: 'A' } }` with `when` on the stats |
|
|
1045
1071
|
| **Open: one library or two?** | one, standalone — "react to a change" is a fact reflex; same machine |
|
|
1046
1072
|
| **Open: does the identity belong here?** | no — moss's `ActorContext`, consumed through an opaque seam |
|
package/DOCS.md
CHANGED
|
@@ -16,13 +16,16 @@ Every symbol the package exports, and what it promises. See [DESIGN.md](./DESIGN
|
|
|
16
16
|
- [Events](#events)
|
|
17
17
|
- [The seams](#the-seams)
|
|
18
18
|
- [The store contract](#the-store-contract)
|
|
19
|
+
- [The Postgres store](#the-postgres-store)
|
|
20
|
+
- [The driver](#the-driver)
|
|
19
21
|
- [Occurrence math](#occurrence-math)
|
|
20
22
|
- [The reflex agent](#the-reflex-agent)
|
|
21
23
|
- [Errors](#errors)
|
|
22
24
|
|
|
23
|
-
|
|
24
|
-
`@niscorp/tide/agent` and `@niscorp/tide/
|
|
25
|
-
|
|
25
|
+
Four entry points: `@niscorp/tide` (everything below unless it says otherwise),
|
|
26
|
+
`@niscorp/tide/agent`, `@niscorp/tide/testing` and `@niscorp/tide/postgres`.
|
|
27
|
+
`zod` is the one required peer. Two peers are optional, each imported by one
|
|
28
|
+
entry only: `@niscorp/cortex` by `/agent`, `@niscorp/strata` by `/postgres`.
|
|
26
29
|
|
|
27
30
|
---
|
|
28
31
|
|
|
@@ -42,7 +45,7 @@ type TideConfig = {
|
|
|
42
45
|
maxChainDepth?: number; // default 24 — a fact deeper than this is parked
|
|
43
46
|
maxChainFacts?: number; // default 10 000 — facts one chain may mint beneath its root; the rest are parked
|
|
44
47
|
storeUnwatchedWrites?: boolean; // default true — false drops a write fact no loaded reflex could watch
|
|
45
|
-
maxFanOut?: number; // default 10 000
|
|
48
|
+
maxFanOut?: number; // default 10 000 — rows one selection may return; a run whose selection returns more is skipped
|
|
46
49
|
leaseMs?: number; // default 300 000 — how long a claim is good for
|
|
47
50
|
onEvent?: (event: TideEvent) => void;
|
|
48
51
|
};
|
|
@@ -454,10 +457,21 @@ tide.ledger.releaseParked(factId) // let a parked fact through, once; false if
|
|
|
454
457
|
- **fact** — everything that arrived: the `FactInput` plus `id`, the `as` it
|
|
455
458
|
was minted under, `depth`, `deliveredAt`, any `parked` reason and `released`
|
|
456
459
|
override, the `root` of its chain and (on a root) its `descendants` count.
|
|
460
|
+
`depth` counts the hops from the start of a chain: a fact a handler emits or
|
|
461
|
+
a settled run mints is one deeper than the task or run it came from, and
|
|
462
|
+
`ingest` stores the `depth` it is handed. `deliveredAt` is the `now` of the
|
|
463
|
+
`advance` that offered the fact to every loaded reflex, set whether or not
|
|
464
|
+
one matched. `root` is the id of the fact that started the chain, and that
|
|
465
|
+
fact itself has none.
|
|
457
466
|
- **run** — one activation: cause, version hash, the identity it ran `as`, what
|
|
458
|
-
the selection returned, the counts, the outcome.
|
|
467
|
+
the selection returned, the counts, the outcome. A run's `cause` is
|
|
468
|
+
`occurrence:<key>` or `fact:<id>`; a fact's is `task:<id>` when a handler
|
|
469
|
+
emitted it and `run:<id>` when a run's settlement minted it.
|
|
459
470
|
- **task** — one unit of effect work: unit key, pinned `env`, attempt count,
|
|
460
|
-
lease, last error, `output`.
|
|
471
|
+
lease, last error, `output`. `unit` is the row's `unitKey` value as a string
|
|
472
|
+
in `each` mode, and `''` for a `batch` run and for a run with no selection.
|
|
473
|
+
`claimedUntil` is when the lease lapses, and `0` while the task is not
|
|
474
|
+
`claimed`.
|
|
461
475
|
|
|
462
476
|
States: a task moves `pending → claimed → done | retrying | failed`; a run moves
|
|
463
477
|
`pending → fanned → settled`, or lands on `skipped` (overlap, catch-up, a
|
|
@@ -563,11 +577,18 @@ of one operation and diverged three ways.
|
|
|
563
577
|
- **`appendIfAbsent`** is idempotent on the table's unique key, declared once in
|
|
564
578
|
the exported `UNIQUE_BY` constant. Those four constraints *are* the engine's
|
|
565
579
|
exactly-once promises; a store that does not enforce all four is not a tide store.
|
|
580
|
+
It returns the stored row, or `undefined` on a collision: a refusal, not an
|
|
581
|
+
error. The store mints the `id` of a `fact`, `run` or `task` row that carries
|
|
582
|
+
none. A key with a `when` column applies only to rows that have that column
|
|
583
|
+
set, so a fact with no `dedupeKey` is always appended.
|
|
566
584
|
- **`claim`** selects and mutates in one step. `set` accepts `{ inc: n }` for a
|
|
567
585
|
counter, because `attempt` has to rise at claim time or a handler that
|
|
568
586
|
reliably kills the process retries forever. `onePer` is `order: 'serial'`,
|
|
569
587
|
and it lives inside the claim because a caller that looks first and claims
|
|
570
|
-
second loses the race.
|
|
588
|
+
second loses the race. `onePer: { column, held, only }` lets at most one row
|
|
589
|
+
per value of `column` be held at a time, counting rows that match `held`
|
|
590
|
+
from an earlier claim; it applies to the values listed in `only`, and every
|
|
591
|
+
other value claims freely.
|
|
571
592
|
- **`cas`** is the fence: a timed-out attempt finishing late finds its token
|
|
572
593
|
superseded and is discarded. Setting a field to `undefined` clears it.
|
|
573
594
|
- **`transact`** is required. Fan-out committing with its run's transition, and
|
|
@@ -605,8 +626,92 @@ for (const check of STORE_CONTRACT) it(check.name, () => check.run(makeStore()))
|
|
|
605
626
|
It is exported rather than kept in `test/` because the contract is not tide's
|
|
606
627
|
private business. The last SQL store in this package said in its own header that
|
|
607
628
|
it was "held to the same tests" and had none; it diverged in eleven ways and
|
|
608
|
-
every one of them was invisible.
|
|
609
|
-
|
|
629
|
+
every one of them was invisible. Tide's own Postgres store (below) runs this
|
|
630
|
+
same list against a real database, in two pool shapes.
|
|
631
|
+
|
|
632
|
+
---
|
|
633
|
+
|
|
634
|
+
## The Postgres store
|
|
635
|
+
|
|
636
|
+
```typescript
|
|
637
|
+
import { createTideStore, TIDE_SEQUENCE, TIDE_TABLES, TIDE_DDL } from '@niscorp/tide/postgres';
|
|
638
|
+
import type { TidePool, TidePoolQuery, TideStoreOptions } from '@niscorp/tide/postgres';
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
An entry point of its own, so that the engine's entry imports nothing but zod.
|
|
642
|
+
It imports `@niscorp/strata`, an optional peer: install it to use this entry.
|
|
643
|
+
|
|
644
|
+
```typescript
|
|
645
|
+
createTideStore(pool: TidePool, options?: TideStoreOptions): TideStore & { ready: Promise<void> }
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
A `TideStore` over four tables: `tide_fact`, `tide_run`, `tide_work`,
|
|
649
|
+
`tide_reflex_state` (`TIDE_TABLES`). `appendIfAbsent` is `ON CONFLICT DO
|
|
650
|
+
NOTHING` on the key `UNIQUE_BY` names; `claim` is one `UPDATE … FOR UPDATE SKIP
|
|
651
|
+
LOCKED`; the state columns carry CHECK constraints; deleting a run cascades to
|
|
652
|
+
its work.
|
|
653
|
+
|
|
654
|
+
- **`pool`** is a `TidePool`: `{ query(text, values?), transaction?(fn) }`. It
|
|
655
|
+
is a type of the store's own, and structural: vex's `PgPool`, a PGlite behind
|
|
656
|
+
a shim, a `pg` pool that checks a client out for each transaction. `query`
|
|
657
|
+
and `transaction` are called on the object that has them. A pool with no
|
|
658
|
+
`transaction` cannot run tide: fan-out, attempt recording and a serial claim
|
|
659
|
+
are transactions, and each refuses with a sentence.
|
|
660
|
+
- **`ready`** resolves when the tables are there. Every method awaits it. The
|
|
661
|
+
store migrates them itself, through a strata ledger, unless
|
|
662
|
+
`options.migrate` is `false`: then whoever owns the database's migrations has
|
|
663
|
+
run `TIDE_SEQUENCE` in a run of its own (under moss, `runtime.tables`).
|
|
664
|
+
- **`TIDE_SEQUENCE`** is the tables as a strata sequence. Its id is
|
|
665
|
+
`nisc.moss.tide`: the store was in `@niscorp/moss` when the sequence was
|
|
666
|
+
named, and every ledger that has run it holds it under that name.
|
|
667
|
+
`TIDE_DDL` is the text of its first migration. Both are history: the tables
|
|
668
|
+
change by appending a migration, never by editing one.
|
|
669
|
+
- **A row is read by a schema.** What comes back from the database is parsed,
|
|
670
|
+
one schema for each table: a row that does not fit throws where it is read,
|
|
671
|
+
naming the table and the field.
|
|
672
|
+
- **A serial group is claimed by one instance at a time.** Asking whether a
|
|
673
|
+
group is held and claiming in it run in one transaction, behind an advisory
|
|
674
|
+
lock on the group (`pg_try_advisory_xact_lock`). An instance that does not
|
|
675
|
+
get the lock leaves the group to the one that has it.
|
|
676
|
+
|
|
677
|
+
The engine's own writes go through the pool, not through a host's write path:
|
|
678
|
+
an engine claiming its own task has no principal to run a policy for. The
|
|
679
|
+
ledger READS are the host's, as ordinary queries over these tables.
|
|
680
|
+
|
|
681
|
+
---
|
|
682
|
+
|
|
683
|
+
## The driver
|
|
684
|
+
|
|
685
|
+
```typescript
|
|
686
|
+
import { createTideDriver } from '@niscorp/tide';
|
|
687
|
+
import type { TideDriver, TideDriverConfig } from '@niscorp/tide';
|
|
688
|
+
|
|
689
|
+
createTideDriver({ tide, now?, janitorMs?, retention? }): TideDriver
|
|
690
|
+
```
|
|
691
|
+
|
|
692
|
+
The engine reads no clock and paces nothing; this is the thing that does, for
|
|
693
|
+
a host that does not write its own.
|
|
694
|
+
|
|
695
|
+
- **Wake** — `ingest` and `fire` advance the engine immediately, to
|
|
696
|
+
quiescence: a chain advances one committed hop per step, so the driver
|
|
697
|
+
loops until a step reports nothing moved. `wake()` returns the promise of
|
|
698
|
+
that drain, so a "run it now" button can await a settled world.
|
|
699
|
+
- **Sleep** — after quiescence, `tide.nextDue(now)` names the next instant
|
|
700
|
+
worth waking for and one timer sleeps until then, preempted by any ingest.
|
|
701
|
+
No beat, no polling for work. A wait longer than a timer can hold (2^31 − 1
|
|
702
|
+
ms, 24.8 days) is cut to that: the driver wakes, finds nothing, and waits
|
|
703
|
+
out the rest.
|
|
704
|
+
- **Janitor** — a slow fallback wake plus the retention sweep. It finds
|
|
705
|
+
nothing when nothing is broken; it exists because a durable multi-worker
|
|
706
|
+
design needs the scan that notices work committed by a process that died
|
|
707
|
+
before its own wake ran. It is how work is *recovered*, never how it moves.
|
|
708
|
+
|
|
709
|
+
A `TideDriver` is `{ ingest, fire, wake, stop }`. Hand a host's intake the
|
|
710
|
+
driver, not the bare engine, so a fact wakes it instead of waiting for
|
|
711
|
+
somebody's beat. `stop()` resolves once nothing the driver started still
|
|
712
|
+
touches the store: await it before closing the database. `now` replaces the
|
|
713
|
+
clock (`Date.now`); `janitorMs` defaults to 5 minutes; absent `retention`,
|
|
714
|
+
nothing is swept. What it logs, it logs as `[tide:driver]`.
|
|
610
715
|
|
|
611
716
|
---
|
|
612
717
|
|
package/README.md
CHANGED
|
@@ -48,7 +48,8 @@ await tide.load([
|
|
|
48
48
|
|
|
49
49
|
// The HOST owns waking. Tide reads no clock — it advances one committed step
|
|
50
50
|
// at a time and says when it next wants waking, and a driver does the rest:
|
|
51
|
-
// drain on every ingest, then sleep until that instant.
|
|
51
|
+
// drain on every ingest, then sleep until that instant. `createTideDriver`
|
|
52
|
+
// is that driver, written once; these are the lines it is made of.
|
|
52
53
|
const drain = async () => { for (;;) { const r = await tide.advance({ now: Date.now() }); if (quiet(r)) break; } };
|
|
53
54
|
await drain();
|
|
54
55
|
const at = await tide.nextDue(Date.now()); // undefined = nothing scheduled
|
|
@@ -104,6 +105,17 @@ Four tables, and only two of them grow with events:
|
|
|
104
105
|
|
|
105
106
|
The port is six capabilities, not twenty-seven nouns: `transact`, `appendIfAbsent`, `claim`, `cas`, `query`, `remove`. `createMemoryStore()` is the reference implementation. `STORE_CONTRACT`, exported from `@niscorp/tide/testing`, is the same set of checks both it and any other store must pass — importable so a host's store is held to one definition rather than to two readings of a comment.
|
|
106
107
|
|
|
108
|
+
**Durable: `@niscorp/tide/postgres`.** `createTideStore(pool)` is the same contract over Postgres, held to the same checks against a real database. It takes a pool described by a type of its own (`query`, `transaction`), so it imports no driver and no host, and it migrates its four tables through a [strata](../strata/README.md) ledger (`TIDE_SEQUENCE`). Strata is an optional peer, needed by this entry only.
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
import { createTide, createTideDriver } from '@niscorp/tide';
|
|
112
|
+
import { createTideStore } from '@niscorp/tide/postgres';
|
|
113
|
+
|
|
114
|
+
const tide = createTide({ store: createTideStore(pool), transform, effects });
|
|
115
|
+
const driver = createTideDriver({ tide }); // wakes on ingest, sleeps until nextDue
|
|
116
|
+
await driver.ingest({ kind: 'signal', name: 'stripe', at: Date.now() });
|
|
117
|
+
```
|
|
118
|
+
|
|
107
119
|
## The reflex agent — `@niscorp/tide/agent`
|
|
108
120
|
|
|
109
121
|
A model can WRITE a reflex; it never runs one. `createReflexAgent({ effects, triggers, fields })` is a cortex agent handed what somebody wants automated, the local `now` and timezone, and what the host offers:
|
|
@@ -132,7 +144,7 @@ if (result.ok && isDraft(result.output.data)) {
|
|
|
132
144
|
|
|
133
145
|
## Hosts
|
|
134
146
|
|
|
135
|
-
Tide imports no host. Under **moss** the seams are filled with vex (selection under the actor's scope policy, mutations auto-registered as effects), prism (transform), cortex agents (effects)
|
|
147
|
+
Tide imports no host. Under **moss** the seams are filled with vex (selection under the actor's scope policy, mutations auto-registered as effects), prism (transform), cortex agents (effects) and moss's `ActorContext` (identity); persistence is tide's own `createTideStore(pool)` on the pool the app's runtime holds, and every committed write reaches tide as a fact through moss's `createTideFacts` feature (`@niscorp/moss/tide`). In plain Node the seams are filled with raw SQL and plain functions. Nothing above the seam can tell the difference.
|
|
136
148
|
|
|
137
149
|
## Documentation
|
|
138
150
|
|
package/dist/agent.cjs
CHANGED
|
@@ -55,15 +55,11 @@ var RetrySchema = zod.z.object({
|
|
|
55
55
|
var PolicySchema = zod.z.object({
|
|
56
56
|
retry: RetrySchema.optional(),
|
|
57
57
|
timeoutMs: zod.z.number().int().positive().default(3e4),
|
|
58
|
-
// May a firing start while the previous one is unsettled? The long
|
|
59
|
-
// billing run still going at the next tick must not double-start.
|
|
60
58
|
overlap: zod.z.enum(["skip", "allow"]).default("skip"),
|
|
61
59
|
catchUp: zod.z.enum(["run", "skip", "latest"]).default("run"),
|
|
62
|
-
//
|
|
63
|
-
//
|
|
64
|
-
// `
|
|
65
|
-
// repeats of one another, so under 'skip' the oldest runs and the rest
|
|
66
|
-
// are recorded as overlap skips.
|
|
60
|
+
// Read by `catchUp: 'skip'` only. What `catchUp` opens still passes
|
|
61
|
+
// `overlap`: occurrences missed together are repeats of one another, so
|
|
62
|
+
// under `overlap: 'skip'` the oldest runs and the rest are skipped.
|
|
67
63
|
lateMs: zod.z.number().int().positive().default(36e5),
|
|
68
64
|
order: zod.z.enum(["any", "serial"]).default("any")
|
|
69
65
|
}).strict();
|
|
@@ -187,8 +183,6 @@ var createReflexAgent = (config) => cortex.defineAgent({
|
|
|
187
183
|
context: [() => describeEffects(config.effects)],
|
|
188
184
|
output: {
|
|
189
185
|
schema: answerSchemaOf(config),
|
|
190
|
-
// Corrected in the run, tools and context still warm. Only a draft
|
|
191
|
-
// names an effect; a question or a refusal has nothing to check here.
|
|
192
186
|
validate: (envelope) => {
|
|
193
187
|
if (!isDraft(envelope.data)) return { ok: true };
|
|
194
188
|
const problem = effectProblem(config.effects, envelope.data);
|
package/dist/agent.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/reflex.schema.ts","../src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AA,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"]}
|
|
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":";;;;;;AAEO,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;AACb,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,CAAI,QAAA,CAAS,EAAE,IAAA,EA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,OAAO,CAAA,eAAA,EAAkB,MAAA,CAAO,IAAI,CAAA,iCAAA,EAA+B,MAAM,CAAA,CAAA,CAAA;AAC3E;AAEO,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,IAC7B,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\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])$/;\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\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\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\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\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // Read by `catchUp: 'skip'` only. What `catchUp` opens still passes\n // `overlap`: occurrences missed together are repeats of one another, so\n // under `overlap: 'skip'` the oldest runs and the rest are skipped.\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\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\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\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\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\nexport type DraftField = 'params' | 'select' | 'when';\n\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\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\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\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","import { 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\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\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\nexport const ReflexAnswerSchema = answerSchemaOf();\n\nexport const isDraft = (answer: ReflexAnswer): answer is ReflexDraft => 'effect' in answer;\n\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// Converted by the schema's own zod: a caller's schema may come from another copy.\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\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\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 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"]}
|