@niscorp/tide 0.1.0 → 0.1.1

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 ADDED
@@ -0,0 +1,7 @@
1
+ # @niscorp/tide
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 45d6731: `load` refuses under the code of what it found: `unknown_effect` for a reflex naming an unregistered effect, `unknown_reflex` for one watching the run of a reflex that is not there, `unguarded_cycle` for an unguarded cycle. Every refusal was reported as `unguarded_cycle`. `details.refusals` lists each reason with its code (`details.errors` is unchanged), and `GraphReport` carries the same list.
package/DESIGN.md CHANGED
@@ -245,7 +245,7 @@ Three kinds (and two more fact flavours). Structured on purpose — a reflex is
245
245
  ```
246
246
 
247
247
  Any reflex — whatever its trigger — may additionally be fired by hand through
248
- `fire(reflexId, input?)`, **including a disarmed one**: arming gates *triggers*, not
248
+ `fire(reflexId, { now, input?, by? })`, **including a disarmed one**: arming gates *triggers*, not
249
249
  people, and testing before arming is half of what `fire` is for; the ledger records
250
250
  `manual:<who>` either way. A `manual` trigger just means *only* by hand. And `fire`
251
251
  is sugar over `ingest`: it mints a `manual` fact aimed at one reflex — `at` supplied
@@ -635,10 +635,13 @@ on purpose: a drip campaign is a reflex whose delayed fact fires itself; "retry
635
635
  decline in 3 days" loops through `notBefore`; a drain loop subscribes to its own run.
636
636
  All converge because every loop passes through a **guard**: a selection that re-checks
637
637
  reality, a `when`, or a `notBefore` delay. Static analysis cannot tell a convergent
638
- cycle from a divergent one, so it does not pretend to:
638
+ cycle from a divergent one, so it does not pretend to — and it sees only what a reflex
639
+ declares: `notBefore` is a property of an emitted fact, not of a reflex, so load
640
+ cannot count it:
639
641
 
640
- - An **unguarded** cycle — every hop unconditional, no selection, no `when`, no
641
- `notBefore` anywhere on the loop — is refused at load: it diverges by construction.
642
+ - An **unguarded** cycle — every hop unconditional, no selection and no `when`
643
+ anywhere on the loop — is refused at load: it diverges by construction. A loop
644
+ paced only by `notBefore` is refused with it; give one hop a `when` or a selection.
642
645
  - A **guarded** cycle is legal and reported as a finding, so the author sees the loop
643
646
  they built.
644
647
  - The runtime backstop is nearly free because causality already exists: a fact whose
@@ -730,7 +733,8 @@ Plus the driver-facing edges, contracts rather than injections: **`ingest(fact)`
730
733
  in, **`advance({ now, limit })`** to run one committed increment, and
731
734
  **`nextDue(now)`** so the driver knows when next to wake.
732
735
 
733
- Dependencies: **`zod`**. Nothing else — the same bar charter clears.
736
+ Dependencies: **`zod`**. Nothing else — the same bar charter clears. (The
737
+ `/agent` entry imports `@niscorp/cortex`, an optional peer; the engine never does.)
734
738
 
735
739
  ### The store contract
736
740
 
@@ -850,13 +854,13 @@ theirs to keep. `ctx.emit` is how a chain continues without a write choke point.
850
854
  ```
851
855
  src/
852
856
  index.ts Public API barrel — createTide, schemas, the store contract
853
- testing.ts STORE_CONTRACT — the executable definition of a store
857
+ testing.ts STORE_CONTRACT — the executable definition of a store (the ./testing entry)
854
858
  tide.ts createTide: load, ingest, advance, nextDue, fire, retry, preview, ledger, sweep
855
859
  types.ts ledger rows, seam types, TideStore, UNIQUE_BY, reports
856
860
  errors.ts TideError (code + details)
857
861
 
858
862
  schemas/
859
- reflex.schema.ts ReflexSchema — trigger, select, effect, policy, enabled
863
+ reflex.schema.ts ReflexSchema — trigger, select, effect, policy, enabled; the draft schemas and the timer
860
864
  trigger.schema.ts clock | fact | manual, with narrowing helpers
861
865
  fact.schema.ts FactInputSchema — the public intake contract, union enforced
862
866
  policy.schema.ts retry, backoff, overlap, order, catchUp, lateMs
@@ -867,6 +871,8 @@ src/
867
871
  due.ts nextDue — the instant the driver should wake for
868
872
  runtime.ts EngineDeps, the `$` environment, isTruthy, versionOf
869
873
  occurrence.ts calendar math, local-field keys, clamping, DST edges
874
+ anchor.ts anchorDraft — a saved draft's timer becomes a one-shot clock
875
+ facts.ts admitFact / announceFact — the one door into the fact table
870
876
  materialize.ts clock → runs (catch-up, watermark)
871
877
  match.ts fact × reflex, `when`, and openRun — the one place a run is born
872
878
  fanout.ts selection → transactional unit-task commit; refuse vs defer
@@ -877,6 +883,10 @@ src/
877
883
  store/
878
884
  memory.ts createMemoryStore — the reference implementation + snapshot()
879
885
 
886
+ agent/
887
+ reflex-agent.ts createReflexAgent — the ./agent entry; the only file that imports cortex
888
+ index.ts
889
+
880
890
  test/
881
891
  occurrence.test.ts DST both directions, clamping, key stability
882
892
  engine.test.ts the execution semantics, end to end on a fake clock
@@ -884,6 +894,9 @@ test/
884
894
  load.test.ts the load gate: validation, cycles, versioning
885
895
  preview.test.ts dry run writes nothing and shows everything
886
896
  store.test.ts STORE_CONTRACT × every store
897
+ anchor.test.ts a draft's timer, anchored when it is saved
898
+ agent.test.ts the reflex agent — its answer schemas, effect check and conversation turns
899
+ support.ts shared fixtures
887
900
  ```
888
901
 
889
902
  `materialize.ts` is split out of `advance.ts` because the clock is where the engine
package/DOCS.md CHANGED
@@ -7,16 +7,23 @@ Every symbol the package exports, and what it promises. See [DESIGN.md](./DESIGN
7
7
  - [createTide](#createtide)
8
8
  - [The reflex](#the-reflex)
9
9
  - [Triggers](#triggers)
10
+ - [Drafts](#drafts)
10
11
  - [Policy](#policy)
11
12
  - [Templates and `$`](#templates-and-)
12
13
  - [The fact](#the-fact)
13
14
  - [Verbs](#verbs)
14
15
  - [The ledger](#the-ledger)
16
+ - [Events](#events)
15
17
  - [The seams](#the-seams)
16
18
  - [The store contract](#the-store-contract)
17
19
  - [Occurrence math](#occurrence-math)
20
+ - [The reflex agent](#the-reflex-agent)
18
21
  - [Errors](#errors)
19
22
 
23
+ Three entry points: `@niscorp/tide` (everything below unless it says otherwise),
24
+ `@niscorp/tide/agent` and `@niscorp/tide/testing`. `zod` is the one required
25
+ peer; `@niscorp/cortex` is an optional peer that only `/agent` imports.
26
+
20
27
  ---
21
28
 
22
29
  ## createTide
@@ -32,7 +39,9 @@ type TideConfig = {
32
39
  select?: SelectFn; // required only if a reflex has a selection
33
40
  effects?: EffectRegistry | ((as: string | undefined) => EffectRegistry);
34
41
  actor?: (as: string | undefined) => unknown; // default: the `as` string itself
35
- maxChainDepth?: number; // default 24
42
+ maxChainDepth?: number; // default 24 — a fact deeper than this is parked
43
+ maxChainFacts?: number; // default 10 000 — facts one chain may mint beneath its root; the rest are parked
44
+ storeUnwatchedWrites?: boolean; // default true — false drops a write fact no loaded reflex could watch
36
45
  maxFanOut?: number; // default 10 000
37
46
  leaseMs?: number; // default 300 000 — how long a claim is good for
38
47
  onEvent?: (event: TideEvent) => void;
@@ -49,6 +58,12 @@ its `dedupeKey`, as `fact.deduped`. All three paths go through one door in the
49
58
  engine, and a fact written inside a transaction is announced only once that
50
59
  transaction commits, so an event always describes a row that exists.
51
60
 
61
+ `storeUnwatchedWrites: false` is for a host whose ledger is not its audit log.
62
+ `ingest` then returns `undefined`, stores nothing and announces nothing for a
63
+ `write` fact whose entity (and op) no loaded reflex's trigger names. It asks
64
+ only that — it ignores `enabled`, arming and `as` — and it drops nothing while
65
+ no reflexes are loaded. Signal and manual facts are always stored.
66
+
52
67
  `leaseMs` is the recovery story for a process that dies between the effect and
53
68
  the record. A task still `claimed` past its lease is claimable again; the
54
69
  fencing token is what makes that safe.
@@ -65,7 +80,7 @@ type Reflex = {
65
80
  as?: string; // opaque identity; the host resolves it
66
81
  params?: Record<string, unknown>; // authored knobs, visible as $.params
67
82
  select?: {
68
- query: unknown; // opaque — handed to the `select` seam verbatim
83
+ query: unknown; // opaque — a template: evaluated by `transform`, the result handed to the `select` seam
69
84
  mode: 'each' | 'batch'; // default 'each'
70
85
  unitKey?: string; // required for 'each' — the idempotency grain
71
86
  };
@@ -76,12 +91,21 @@ type Reflex = {
76
91
  };
77
92
  ```
78
93
 
79
- `ReflexSchema` parses it; `ReflexInput` is the input type (defaults not yet applied).
94
+ `ReflexSchema` parses it; `ReflexInput` is the input type (defaults not yet
95
+ applied — `policy`, `enabled` and `select.mode` may be omitted). The parts are
96
+ exported too: `SelectionSchema`, `EffectRefSchema`, `TriggerSchema` and its
97
+ members (`ClockTriggerSchema`, `ClockRecurringSchema`, `ClockOnceSchema`,
98
+ `WriteTriggerSchema`, `SignalTriggerSchema`, `RunTriggerSchema`,
99
+ `ManualTriggerSchema`), `ClockUnitSchema`, `OpSchema`, `WEEKDAYS`,
100
+ `PolicySchema`, `RetrySchema`, `FactInputSchema` and `FactKindSchema`, with the
101
+ types `Selection`, `EffectRef`, `Trigger`, `Clock`, `ClockRecurring`,
102
+ `ClockOnce`, `Op`, `Weekday`, `Policy`, `Retry`, `FactInput` and `FactKind`.
80
103
 
81
104
  **Load refuses**, in one pass: a reflex that does not parse, a duplicate id, an
82
105
  unregistered effect, `when` on a non-fact trigger, `each` mode with no
83
106
  `unitKey`, a run subscription to a reflex that is not
84
- loaded, and an **unguarded cycle**.
107
+ loaded, and an **unguarded cycle** — a loop on which no reflex has a `select`
108
+ or a `when`.
85
109
 
86
110
  **`enabled` is the host's.** Tide reads it off the reflex it is handed and
87
111
  holds no copy. To pause an automation, write your own row and `load` again.
@@ -141,6 +165,40 @@ what was already pushed, one interval late — see `DESIGN.md`.
141
165
 
142
166
  ---
143
167
 
168
+ ## Drafts
169
+
170
+ A draft is a reflex as it is written, before it is saved: `id`, `intent`, `on`
171
+ and `effect` — nothing that is the host's (`as`, `policy`, `enabled`). It is the
172
+ shape the [reflex agent](#the-reflex-agent) answers with.
173
+
174
+ ```typescript
175
+ draftSchemaOf(choice?: DraftChoice): z.ZodType<ReflexDraft>
176
+ type DraftChoice = {
177
+ triggers?: readonly DraftTrigger[]; // 'clock' | 'timer' | 'write' | 'signal' | 'run' | 'manual' — default: all six
178
+ fields?: readonly DraftField[]; // 'params' | 'select' | 'when' — default: none
179
+ };
180
+ ReflexDraftSchema // draftSchemaOf() — every trigger kind, no extra fields
181
+ DRAFT_TRIGGERS // trigger kind → its schema
182
+ TimerSchema, TimerTriggerSchema // { hours?, minutes?, seconds? } — non-negative integers, > 0 in total
183
+ ```
184
+
185
+ `draftSchemaOf` throws a plain `Error` on an empty `triggers` list. The draft
186
+ schemas keep the reflex's own rules: `when` on a non-fact trigger and `each`
187
+ with no `unitKey` are refused.
188
+
189
+ ```typescript
190
+ anchorDraft(draft: ReflexDraft, anchor: { at: number; tz: string }): Reflex
191
+ timerMs(timer: Timer): number
192
+ ```
193
+
194
+ `anchorDraft` turns a draft into a stored reflex at the moment it is saved. A
195
+ `timer` becomes a one-shot clock at `anchor.at` plus its length, rounded **up**
196
+ to the whole second, as a local date-time in `anchor.tz`; any other trigger
197
+ passes through. The result is parsed by `ReflexSchema`, so defaults are applied
198
+ and a bad draft throws. The host adds `as` afterwards.
199
+
200
+ ---
201
+
144
202
  ## Policy
145
203
 
146
204
  ```typescript
@@ -263,7 +321,9 @@ including turning one off.
263
321
  ingest(fact: FactInput, options?: { as?: string; cause?: string; depth?: number }): Promise<Fact | undefined>
264
322
  ```
265
323
  One write. Undefined means a `dedupeKey` collision — a refusal, not an error,
266
- announced as `fact.deduped` so a repeat is never mistaken for silence.
324
+ announced as `fact.deduped` so a repeat is never mistaken for silence — or,
325
+ under `storeUnwatchedWrites: false`, a write nothing watches, dropped silently.
326
+ A fact that does not parse throws `invalid_fact`.
267
327
  Matching happens in `advance`, against whatever is loaded when the fact comes
268
328
  due, which is what lets a delayed fact meet the reflexes of the day it fires.
269
329
 
@@ -296,17 +356,44 @@ safe to run concurrently. `limit` (default 100) bounds facts, fan-outs and
296
356
  claims per pass. A chain advances one hop per call, so the driver drains to quiescence and
297
357
  then sleeps until `nextDue`.
298
358
 
359
+ ```typescript
360
+ type AdvanceReport = {
361
+ now: number;
362
+ materialized: number; skippedOccurrences: number;
363
+ factsMatched: number; runsCreated: number; tasksCreated: number;
364
+ executed: number; succeeded: number; failed: number; retrying: number; reclaimed: number;
365
+ runsSettled: number; parked: number;
366
+ };
367
+ ```
368
+
369
+ ```typescript
370
+ nextDue(now: number): Promise<number | undefined>
371
+ ```
372
+ The next instant at which `advance` can make progress: an undelivered fact's
373
+ `notBefore ?? at`, a pending run's `dueAt`, a waiting task's backoff, a claimed
374
+ task's lease lapse, a loaded clock's next occurrence. `undefined` means nothing
375
+ is scheduled — sleep until an `ingest`. The timer is the driver's; tide still
376
+ reads no clock.
377
+
378
+ ```typescript
379
+ reflexes(): readonly Reflex[]
380
+ ```
381
+ What is loaded now, as parsed.
382
+
299
383
  ```typescript
300
384
  fire(reflexId, { now, input?, by? }): Promise<Fact | undefined>
301
385
  ```
302
- Sugar over `ingest`: mints a `manual` fact aimed at one reflex. Works on a
303
- **disarmed** reflex — arming gates triggers, not people.
386
+ Sugar over `ingest`: mints a `manual` fact aimed at one reflex, with `input` as
387
+ its `payload` and `by` (default `'operator'`) recorded. Works on a
388
+ **disarmed** reflex — arming gates triggers, not people. Throws
389
+ `unknown_reflex` when the reflex is not loaded.
304
390
 
305
391
  ```typescript
306
392
  retry(taskId, now): Promise<boolean>
307
393
  ```
308
394
  Reopens a `failed` task **and rewinds its run** from `settled` back to `fanned`,
309
- in one transaction, so the next `advance` actually claims it. The run keeps
395
+ in one transaction, so the next `advance` actually claims it. `false` when the
396
+ task does not exist or is not `failed`. The run keeps
310
397
  `drained`, so re-settling does not announce a second time: the digest that
311
398
  already went out saying twelve failed is not sent again.
312
399
 
@@ -319,7 +406,7 @@ rows by name, each unit's resolved input, and whatever the handler's `preview`
319
406
  hook renders.
320
407
 
321
408
  ```typescript
322
- graph(): GraphReport // edges, cycles, blind, errors, warnings
409
+ graph(): GraphReport // { edges: { from, to, via }[], cycles, blind, errors, warnings } over what is loaded
323
410
  sweep(now, retention): Promise<number> // { facts?, runs?, tasks? } horizons in ms
324
411
  ```
325
412
 
@@ -335,21 +422,23 @@ tide.ledger.runs(filter?) // { reflexId?, limit? } — newest first
335
422
  tide.ledger.run(id)
336
423
  tide.ledger.tasks(filter?) // { runId?, reflexId?, state?, limit? }
337
424
  tide.ledger.task(id)
338
- tide.ledger.facts(filter?)
425
+ tide.ledger.facts(filter?) // { reflexId?, limit? } — newest first; `reflexId` keeps run and manual facts naming that reflex
339
426
  tide.ledger.fact(id)
340
- tide.ledger.causeChain(factId) // walks `cause` upward
341
- tide.ledger.releaseParked(factId) // let a chain-ceilinged fact through, once
427
+ tide.ledger.causeChain(factId) // walks `cause` upward — the fact first, then its ancestors
428
+ tide.ledger.releaseParked(factId) // let a parked fact through, once; false if it is not parked
342
429
  ```
343
430
 
344
- - **fact** — everything that arrived, with its depth, delivery and any park.
431
+ - **fact** — everything that arrived: the `FactInput` plus `id`, the `as` it
432
+ was minted under, `depth`, `deliveredAt`, any `parked` reason and `released`
433
+ override, the `root` of its chain and (on a root) its `descendants` count.
345
434
  - **run** — one activation: cause, version hash, the identity it ran `as`, what
346
435
  the selection returned, the counts, the outcome.
347
436
  - **task** — one unit of effect work: unit key, pinned `env`, attempt count,
348
437
  lease, last error, `output`.
349
438
 
350
439
  States: a task moves `pending → claimed → done | retrying | failed`; a run moves
351
- `pending → fanned → settled`, or lands on `skipped` (overlap, catch-up, or a
352
- malformed reflex, always with a `note`).
440
+ `pending → fanned → settled`, or lands on `skipped` (overlap, catch-up, a
441
+ refused fan-out, or a reflex no longer loaded — always with a `note`).
353
442
 
354
443
  `limit` means **the most recent N**, in every store. The two stores used to
355
444
  answer opposite ends of the same list under the same filter.
@@ -371,6 +460,27 @@ restore would then re-charge the invoice.
371
460
 
372
461
  ---
373
462
 
463
+ ## Events
464
+
465
+ `onEvent` receives a `TideEvent`. Events are not rows — they are what a host
466
+ logs at whatever grain it wants.
467
+
468
+ | `type` | Carries | When |
469
+ |---|---|---|
470
+ | `run.created` | `run` | a run opened |
471
+ | `run.settled` | `run` | its last task settled, or it fanned out to no tasks — once per run, not again after a `retry` |
472
+ | `run.skipped` | `reflexId`, `reason` | overlap, or a fan-out tide refused |
473
+ | `run.deferred` | `reflexId`, `runId`, `reason` | a fan-out failed in a host seam; retried next `advance` |
474
+ | `task.done` / `task.failed` | `task` | an attempt recorded a terminal outcome |
475
+ | `task.retrying` | `task`, `nextAt` | an attempt threw or timed out with retries left |
476
+ | `task.reclaimed` | `task` | a lapsed lease was taken back |
477
+ | `fact.ingested` | `fact` | a fact was stored — ingested, emitted, or a settled run's |
478
+ | `fact.deduped` | `fact` | a fact was refused on its `dedupeKey` |
479
+ | `fact.parked` | `fact`, `reason` | the matcher parked it at `maxChainDepth`. A fact parked on arrival by `maxChainFacts` is announced as `fact.ingested`, with `parked` set |
480
+ | `fact.unmatched` | `fact`, `reflexId`, `reason` | a `when` said no, or threw |
481
+
482
+ ---
483
+
374
484
  ## The seams
375
485
 
376
486
  | Seam | Contract |
@@ -385,11 +495,17 @@ restore would then re-charge the invoice.
385
495
  type TideCtx = {
386
496
  reflexId: string; runId: string; taskId: string;
387
497
  taskKey: string; // the downstream idempotency key — pass it to the provider
388
- attempt: number; now: number; actor: unknown;
389
- emit: (fact) => void; // buffered; commits with a SUCCESSFUL attempt only
498
+ attempt: number;
499
+ depth: number; // how deep in a cause chain this task sits — a bridge forwards it to `ingest`
500
+ now: number; actor: unknown;
501
+ emit: (fact: Omit<FactInput, 'cause'>) => void; // buffered; commits with a SUCCESSFUL attempt only
390
502
  };
391
503
  ```
392
504
 
505
+ `select` receives `SelectCtx` — `{ reflexId, now, actor, env }`, where `env` is
506
+ `$`. An effect's optional `preview(input, ctx)` receives `PreviewCtx` —
507
+ `{ reflexId, unit, now, actor }`.
508
+
393
509
  **The calling convention is the retry classification.** Return = done, however
394
510
  unhappy the outcome (a card decline is a domain outcome: record it as a row and
395
511
  let another reflex branch on it). Throw = transient, retried on bounded backoff.
@@ -434,6 +550,16 @@ of one operation and diverged three ways.
434
550
  - **`transact`** is required. Fan-out committing with its run's transition, and
435
551
  an attempt recording with the facts it emitted, are transactions rather than
436
552
  conventions.
553
+ - **`query`** and **`remove`** take `{ table, where?, order?, limit? }` and
554
+ `{ table, where? }`. A `where` value is a literal (equality) or a
555
+ `Comparison` — `eq`, `ne`, `lt`, `lte`, `gt`, `gte`, `in`, `notIn`, `isNull`,
556
+ listed in the exported `COMPARISON_OPS`. There is no OR. Removing a run
557
+ removes its tasks.
558
+
559
+ `PRIMARY_KEY` is exported beside `UNIQUE_BY`: the column `cas` addresses a row
560
+ by — `id` for `fact`, `run` and `task`, `reflexId` for `state`. The spec types
561
+ (`ClaimSpec`, `QuerySpec`, `RemoveSpec`, `Where`, `Comparison`, `Order`,
562
+ `Mutation`, `UniqueKey`, `TableName`, `TideTables`) are exported with them.
437
563
 
438
564
  ```typescript
439
565
  import { createMemoryStore } from '@niscorp/tide';
@@ -444,9 +570,10 @@ import { STORE_CONTRACT } from '@niscorp/tide/testing';
444
570
  run against. It also exposes `snapshot()` for assertions — deliberately outside
445
571
  `TideStore`, so the engine cannot reach around its own contract.
446
572
 
447
- `STORE_CONTRACT` is the executable definition of everything above: a list of
448
- `{ name, run(store) }` checks that throw, with no test framework, so any runner
449
- can drive them.
573
+ `STORE_CONTRACT` is the executable definition of everything above: a
574
+ `readonly StoreCheck[]` — `{ name: string; run: (store: TideStore) => Promise<void> }`
575
+ — of checks that throw, with no test framework, so any runner can drive them.
576
+ Each check wants a fresh, empty store.
450
577
 
451
578
  ```typescript
452
579
  for (const check of STORE_CONTRACT) it(check.name, () => check.run(makeStore()));
@@ -474,6 +601,54 @@ daysInMonth(year, month): number
474
601
  versionOf(reflex): string // the content hash, excluding `enabled`
475
602
  ```
476
603
 
604
+ `occurrenceKey` takes a recurring clock. `anchorDraft` and `timerMs` are under
605
+ [Drafts](#drafts).
606
+
607
+ ---
608
+
609
+ ## The reflex agent
610
+
611
+ `@niscorp/tide/agent` — needs `@niscorp/cortex`, the optional peer. Given what
612
+ somebody wants automated and the effects the host offers, it answers with one
613
+ of three things: a reflex draft, a question back, or a refusal. It schedules
614
+ nothing; the host shows the answer, and saves a draft with `anchorDraft` and
615
+ `load`.
616
+
617
+ ```typescript
618
+ createReflexAgent(config: { effects: readonly OfferedEffect[] } & DraftChoice): AgentDefinition<ReflexAnswer>
619
+
620
+ type OfferedEffect = { name: string; description: string; input: ZodType };
621
+ type ReflexAgentInput = { intent: string; now: string; tz: string }; // now: local "YYYY-MM-DDTHH:MM" in tz
622
+ type ReflexAnswer = ReflexDraft | ReflexQuestion | ReflexRefusal;
623
+ type ReflexQuestion = { question: string };
624
+ type ReflexRefusal = { refused: string };
625
+ ```
626
+
627
+ `triggers` and `fields` narrow what a draft may use, as in `draftSchemaOf`. A
628
+ draft naming an effect that is not offered, or an input that effect's schema
629
+ refuses, is sent back to the model to correct within the same run.
630
+
631
+ ```typescript
632
+ const agent = createReflexAgent({ effects, triggers: ['clock', 'timer'] });
633
+ const result = await agent.run({ intent, now, tz }, { llm }).result;
634
+ if (result.ok && isDraft(result.output.data)) {
635
+ // …shown to the person; when they save it:
636
+ await tide.load([{ ...anchorDraft(result.output.data, { at: Date.now(), tz }), as: owner }], { at: Date.now() });
637
+ }
638
+ ```
639
+
640
+ - `isDraft(answer)` — narrows a `ReflexAnswer` to a draft.
641
+ - `answerSchemaOf(choice?)` — the answer schema for what the caller offers;
642
+ `ReflexAnswerSchema` is `answerSchemaOf()`.
643
+ - `ReflexAgentInputSchema`, `ReflexQuestionSchema`, `ReflexRefusalSchema` — the
644
+ input and the two non-draft answers.
645
+ - `effectProblem(effects, draft): string | undefined` — what is wrong with a
646
+ draft's effect, as a sentence, or nothing. The check the agent runs.
647
+ - `reflexConversation({ now, tz, earlier, latest }): Message[]` — the
648
+ conversation so far as chat turns: each earlier `{ request, answer, reasoning? }`
649
+ and the person's `latest` words. Pass it to `run` in place of a single input
650
+ when a question is answered or a draft corrected.
651
+
477
652
  ---
478
653
 
479
654
  ## Errors
@@ -482,15 +657,20 @@ versionOf(reflex): string // the content hash, excluding `enabled`
482
657
 
483
658
  | Code | Raised when |
484
659
  |---|---|
485
- | `invalid_reflex` | a reflex failed `ReflexSchema` |
486
- | `invalid_fact` | a fact failed `FactInputSchema`, or a handler emitted one that did |
660
+ | `invalid_reflex` | a reflex failed `ReflexSchema` — including `when` on a non-fact trigger and `each` with no `unitKey` |
661
+ | `invalid_fact` | a fact failed `FactInputSchema`, or a handler emitted one that did, or emitted a kind other than `write` / `signal` |
487
662
  | `duplicate_reflex` | two reflexes share an id |
488
- | `unknown_reflex` | `fire`/`preview` named a reflex that is not loaded |
489
- | `unknown_effect` | a reflex names an unregistered effect |
490
- | `unguarded_cycle` | load found a loop with no guard anywhere on it |
663
+ | `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 |
664
+ | `unguarded_cycle` | `load` found a loop on which no reflex has a `select` or a `when` |
665
+ | `unknown_effect` | `load` found a reflex naming an effect that is not registered |
666
+ | `no_transform` | in `TideErrorCode`; not raised — `transform` is a required config field |
491
667
  | `duplicate_unit` | a selection's `unitKey` was not unique, or `maxFanOut` was exceeded |
492
668
  | `store` | a selection exists but no `select` seam is wired |
493
669
 
670
+ `load` checks the whole graph in one pass. When it refuses, `details.errors`
671
+ lists every reason and `details.refusals` gives each with its own code; the
672
+ error's `code` is the first one's.
673
+
494
674
  Runtime failures are **not** exceptions: a handler that throws becomes a
495
675
  recorded attempt, a `when` that throws becomes a recorded non-match, and an `advance`
496
676
  does not crash because one reflex is broken.
package/README.md CHANGED
@@ -10,7 +10,7 @@ Every nisc package answers one question: vex answers *what*, nova *how it looks*
10
10
  pnpm add @niscorp/tide zod
11
11
  ```
12
12
 
13
- `zod` is the only peer dependency. Storage, selection, transformation, effects and identity are seams the host fills.
13
+ `zod` is the only required peer; `@niscorp/cortex` is an optional one, used only by `@niscorp/tide/agent`. Storage, selection, transformation, effects and identity are seams the host fills.
14
14
 
15
15
  ## Quick example
16
16
 
@@ -143,4 +143,4 @@ Pre-1.0. The grammar and the store contract are the parts to hold still; everyth
143
143
 
144
144
  ## License
145
145
 
146
- MIT
146
+ Apache-2.0
package/dist/index.cjs CHANGED
@@ -247,7 +247,7 @@ var versionOf = (reflex) => {
247
247
  var isGuarded = (reflex) => reflex.select !== void 0 || reflex.when !== void 0;
248
248
  var buildGraph = (reflexes, effects) => {
249
249
  const edges = [];
250
- const errors = [];
250
+ const refusals = [];
251
251
  const warnings = [];
252
252
  const blind = [];
253
253
  const byId = new Map(reflexes.map((reflex) => [reflex.id, reflex]));
@@ -263,13 +263,13 @@ var buildGraph = (reflexes, effects) => {
263
263
  const existing = runWatchers.get(fact.run) ?? [];
264
264
  runWatchers.set(fact.run, [...existing, reflex.id]);
265
265
  if (fact.run === reflex.id) warnings.push(`${reflex.id} subscribes to its own run \u2014 a drain loop; make sure it narrows`);
266
- if (!byId.has(fact.run)) errors.push(`${reflex.id} watches the run of unknown reflex "${fact.run}"`);
266
+ if (!byId.has(fact.run)) refusals.push({ code: "unknown_reflex", message: `${reflex.id} watches the run of unknown reflex "${fact.run}"` });
267
267
  }
268
268
  }
269
269
  for (const reflex of reflexes) {
270
270
  const handler = effects[reflex.effect.name];
271
271
  if (handler === void 0) {
272
- errors.push(`${reflex.id} names effect "${reflex.effect.name}", which is not registered`);
272
+ refusals.push({ code: "unknown_effect", message: `${reflex.id} names effect "${reflex.effect.name}", which is not registered` });
273
273
  continue;
274
274
  }
275
275
  if (handler.writes === void 0) {
@@ -290,10 +290,11 @@ var buildGraph = (reflexes, effects) => {
290
290
  }));
291
291
  for (const cycle of cycles)
292
292
  if (!cycle.guarded)
293
- errors.push(
294
- `unguarded cycle: ${cycle.reflexIds.join(" \u2192 ")} \u2192 ${cycle.reflexIds[0]} \u2014 no selection and no \`when\` anywhere on the loop, so it diverges by construction`
295
- );
296
- return { edges, cycles, blind, errors, warnings };
293
+ refusals.push({
294
+ code: "unguarded_cycle",
295
+ message: `unguarded cycle: ${cycle.reflexIds.join(" \u2192 ")} \u2192 ${cycle.reflexIds[0]} \u2014 no selection and no \`when\` anywhere on the loop, so it diverges by construction`
296
+ });
297
+ return { edges, cycles, blind, errors: refusals.map((refusal) => refusal.message), refusals, warnings };
297
298
  };
298
299
  var findCycles = (reflexes, edges) => {
299
300
  const adjacency = /* @__PURE__ */ new Map();
@@ -1209,9 +1210,10 @@ var createTide = (config) => {
1209
1210
  parsed.push(result.data);
1210
1211
  }
1211
1212
  const graph = buildGraph(parsed, mergedEffects(parsed));
1212
- if (graph.errors.length > 0)
1213
- throw new TideError("unguarded_cycle", `tide refused to load:
1214
- ${graph.errors.join("\n ")}`, { errors: graph.errors });
1213
+ const refused = graph.refusals[0];
1214
+ if (refused !== void 0)
1215
+ throw new TideError(refused.code, `tide refused to load:
1216
+ ${graph.errors.join("\n ")}`, { errors: graph.errors, refusals: graph.refusals });
1215
1217
  const previously = new Set(loaded.keys());
1216
1218
  const next = /* @__PURE__ */ new Map();
1217
1219
  for (const reflex of parsed) {