@niscorp/tide 0.1.6 → 0.1.8
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 +29 -0
- package/DESIGN.md +7 -6
- package/DOCS.md +38 -10
- package/README.md +5 -1
- package/dist/agent.cjs +12 -14
- package/dist/agent.cjs.map +1 -1
- package/dist/agent.d.cts +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +2 -4
- package/dist/agent.js.map +1 -1
- package/dist/{chunk-4CUQXWVY.js → chunk-7KHOAJNL.js} +3 -4
- package/dist/chunk-7KHOAJNL.js.map +1 -0
- package/dist/{chunk-UEG3UZDG.js → chunk-ZEEJLISU.js} +13 -17
- package/dist/chunk-ZEEJLISU.js.map +1 -0
- package/dist/index.cjs +21 -69
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +29 -5
- package/dist/index.d.ts +29 -5
- package/dist/index.js +13 -56
- package/dist/index.js.map +1 -1
- package/dist/migrations/index.cjs +156 -0
- package/dist/migrations/index.cjs.map +1 -0
- package/dist/migrations/index.d.cts +198 -0
- package/dist/migrations/index.d.ts +198 -0
- package/dist/migrations/index.js +21 -0
- package/dist/migrations/index.js.map +1 -0
- package/dist/postgres.cjs +12 -10
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.js +6 -3
- package/dist/postgres.js.map +1 -1
- package/dist/{reflex.schema-DeiyN5eN.d.cts → reflex.schema-DW1znJfS.d.cts} +29 -5
- package/dist/{reflex.schema-DeiyN5eN.d.ts → reflex.schema-DW1znJfS.d.ts} +29 -5
- 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 +15 -5
- package/dist/chunk-4CUQXWVY.js.map +0 -1
- package/dist/chunk-UEG3UZDG.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/fact.schema.ts","../src/schemas/reflex.schema.ts","../src/errors.ts","../src/engine/runtime.ts","../src/engine/graph.ts","../src/engine/occurrence.ts","../src/engine/match.ts","../src/engine/materialize.ts","../src/engine/fanout.ts","../src/engine/facts.ts","../src/engine/execute.ts","../src/engine/advance.ts","../src/engine/due.ts","../src/engine/preview.ts","../src/tide.ts","../src/types.ts","../src/store/memory.ts","../src/driver.ts","../src/engine/anchor.ts"],"names":["z","require","time","pad2"],"mappings":";;;;;AAYO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AAEb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC;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,E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,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,GAAG,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,IAAI,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,MAAM,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,MAAM,CAAC,CAAA,CAAA;AACtG,CAAA;AAEO,IAAM,WAAA,GAAc,CAAC,KAAA,EAAoB,MAAA,KAA+C;AAC7F,EAAA,IAAI,EAAE,OAAA,IAAW,KAAA,CAAM,KAAK,OAAO,YAAA,CAAa,MAAM,KAAK,CAAA;AAG3D,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,IAAA,CAAA,CAAM,MAAA,CAAO,EAAA,GAAK,OAAA,CAAQ,KAAA,CAAM,EAAA,CAAG,KAAK,CAAA,IAAK,GAAI,CAAA,GAAI,GAAA;AACxE,EAAA,OAAO,YAAA,CAAa,MAAM,EAAE,GAAG,OAAO,EAAA,EAAI,EAAE,OAAO,EAAE,EAAA,EAAI,cAAc,KAAA,EAAO,MAAA,CAAO,EAAE,CAAA,EAAG,EAAA,EAAI,OAAO,EAAA,EAAG,IAAK,CAAA;AAC/G","file":"index.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 { OpSchema } from './trigger.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Fact — the public intake contract.\n//\n// Tide's whole ingestion surface. Anything that can produce this\n// shape can drive tide; nothing else about the producer is tide's\n// business. A host that sees its own writes pushes them — the vex\n// bridge is that host. Either way, what arrives is this.\n// ═══════════════════════════════════════════════════════════════\n\nexport const FactKindSchema = z.enum(['write', 'signal', 'manual', 'run']);\n\nexport const FactInputSchema = z\n .object({\n kind: FactKindSchema,\n\n // write facts\n entity: z.string().optional().describe('Which table or entity was written.'),\n op: OpSchema.optional().describe('Ops are distinct stimuli — \"only on create\" is op: \"insert\".'),\n row: z.record(z.string(), z.unknown()).optional().describe('The row, as the write returned it.'),\n\n // signal facts\n name: z.string().optional().describe('Which named intake this arrived on.'),\n payload: z.unknown().optional().describe('The event body — validated at the HOST boundary before it gets here.'),\n\n // run facts (minted by tide when a run settles — the fan-in mechanism)\n reflex: z.string().optional(),\n runId: z.string().optional(),\n occurrence: z.string().optional().describe('The calendar key, when the clock was the cause.'),\n stats: z\n .object({ total: z.number().int(), done: z.number().int(), failed: z.number().int() })\n .strict()\n .optional(),\n\n // manual facts (minted by `fire`)\n target: z.string().optional().describe('The one reflex a manual fact is aimed at.'),\n by: z.string().optional().describe('Who fired it — recorded on the firing as manual:<who>.'),\n\n at: z.number().int().describe('Supplied by the caller. Tide reads no clocks.'),\n notBefore: z.number().int().optional().describe('A delayed fact — timers as data, visible and queryable.'),\n dedupeKey: z.string().optional().describe('Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error.'),\n cause: z.string().optional().describe('Set by tide when an effect emits — the causality chain.'),\n })\n .strict()\n // THE UNION IS ENFORCED, because an unenforced one is worse than none.\n //\n // `{ kind: 'write' }` with no entity used to parse, store, match nothing,\n // get marked delivered, and vanish — the producer had no way to learn its\n // fact was never going to wake anything. Each kind names the fields that\n // make it addressable, and a fact that cannot be addressed is refused at\n // the intake rather than swallowed by the matcher.\n .superRefine((fact, ctx) => {\n const require = (field: keyof typeof fact, why: string) => {\n if (fact[field] === undefined)\n ctx.addIssue({ code: 'custom', message: `a ${fact.kind} fact needs \\`${String(field)}\\` — ${why}`, path: [field] });\n };\n const refuse = (field: keyof typeof fact) => {\n if (fact[field] !== undefined)\n ctx.addIssue({ code: 'custom', message: `\\`${String(field)}\\` is not part of a ${fact.kind} fact`, path: [field] });\n };\n\n if (fact.kind === 'write') {\n require('entity', 'it is what a write trigger matches on');\n refuse('name');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'signal') {\n require('name', 'it is which named intake this arrived on');\n refuse('entity');\n refuse('op');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'manual') {\n require('target', 'a manual fact is aimed at exactly one reflex');\n refuse('entity');\n refuse('name');\n refuse('runId');\n }\n if (fact.kind === 'run') {\n require('reflex', 'it is whose run settled');\n require('runId', 'it is which run settled');\n refuse('entity');\n refuse('name');\n refuse('target');\n }\n });\n\nexport type FactInput = z.infer<typeof FactInputSchema>;\nexport type FactKind = z.infer<typeof FactKindSchema>;\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Reflex — the artifact.\n//\n// A trigger, an optional selection, exactly one effect, a policy.\n// A straight arc from stimulus to response with no deliberation\n// between: there is no step language here, and a multi-step flow\n// is a CHAIN of reflexes joined by committed rows.\n//\n// `select.query` and every template are `unknown` ON PURPOSE. The\n// moment tide validates a query it owns a query language; the\n// moment it evaluates an expression it owns an evaluator. Both\n// exist in the stack already, behind seams. Tide stores, diffs and\n// hashes these blobs, and hands them over verbatim.\n// ═══════════════════════════════════════════════════════════════\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\n// ═══════════════════════════════════════════════════════════════\n// Draft — a reflex as it is WRITTEN, before it is saved.\n//\n// What a model writes: a name, an intent, a trigger and an effect — and\n// nothing that is the host's (who it runs as, its policy, whether it is\n// enabled). Which triggers, and whether the extra fields a data-driven\n// automation needs, are the CALLER'S choice (`draftSchemaOf`): a draft may\n// only use what its host can run, the way it may only name the effects its\n// host offers. That schema is what the model is shown, and what it is held\n// to; what is stored is still the full ReflexSchema, completed when the\n// draft is saved (`anchorDraft`).\n//\n// One trigger exists only here: the TIMER — \"this long from now\". A timer\n// is sugar, never stored. `now` is only known when somebody saves the\n// draft, so the host anchors it then, and what is stored and run is an\n// ordinary one-shot clock — which survives a restart, because it names an\n// instant rather than a distance from one.\n// ═══════════════════════════════════════════════════════════════\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\n// The trigger kinds a draft can be offered, by name.\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\n// The fields beyond name, intent, trigger and effect a draft can be offered —\n// for automations that select rows or test a fact before they act.\nexport type DraftField = 'params' | 'select' | 'when';\n\n// What the caller offers a draft: its trigger kinds (every kind, if it names\n// none) and its extra fields (none, if it names none).\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name for this automation.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\n// The widest draft: every trigger, every extra field — the TYPE every\n// narrower draft is, and what `anchorDraft` completes.\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\n// The draft schema for what the caller offers — tide's own pieces, each with\n// the description it already has: the widest draft, cut to the chosen fields,\n// its trigger narrowed to the chosen kinds. Nothing is restated here.\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\n// The default draft: every trigger kind, no extra fields.\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n","export type TideErrorCode =\n | 'invalid_reflex'\n | 'invalid_fact'\n | 'duplicate_reflex'\n | 'unknown_reflex'\n | 'unknown_effect'\n | 'unguarded_cycle'\n | 'duplicate_unit'\n | 'no_transform'\n | 'store';\n\nexport class TideError extends Error {\n readonly code: TideErrorCode;\n readonly details?: unknown;\n\n constructor(code: TideErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = 'TideError';\n this.code = code;\n this.details = details;\n }\n}\n\nexport const isTideError = (value: unknown): value is TideError => value instanceof TideError;\n","import type { Reflex } from '../schemas';\nimport type { EffectRegistry, Row, SelectFn, TideEvent, TideStore, TransformFn } from '../types';\n\nexport type LoadedReflex = {\n reflex: Reflex;\n version: string;\n // Matching starts here. A reflex never retro-fires: the fact history from\n // before it existed is reachable only by deliberate backfill, never by\n // accident — a new \"notify on signup\" reflex must not greet every member\n // since launch.\n armedAt: number;\n};\n\nexport type EngineDeps = {\n store: TideStore;\n transform: TransformFn;\n select?: SelectFn;\n effectsFor: (as: string | undefined) => EffectRegistry;\n actorFor: (as: string | undefined) => unknown;\n maxChainDepth: number;\n maxChainFacts: number;\n maxFanOut: number;\n // How long a claim is good for. Expiry is the reclaim; there is no reaper.\n leaseMs: number;\n emit: (event: TideEvent) => void;\n reflexes: () => readonly LoadedReflex[];\n find: (id: string) => LoadedReflex | undefined;\n // This engine's claim tokens (execute.ts). Unique within the engine only;\n // the fence pairs the token with the task's attempt, which is what tells\n // two engines' claims apart.\n nextToken: () => string;\n};\n\n// ── the environment templates evaluate against ──────────────────\n//\n// Small and closed on purpose: what a template can see is enumerable,\n// so what a reflex can depend on is auditable.\n\nexport type EnvParts = {\n params?: Row;\n occurrence?: { key: string; at: number; tz?: string };\n fact?: Row;\n facts?: readonly Row[];\n row?: Row;\n rows?: readonly Row[];\n now: number;\n};\n\nexport const buildEnv = (parts: EnvParts): Row => {\n const env: Row = { params: parts.params ?? {}, now: parts.now };\n if (parts.occurrence !== undefined) env.occurrence = parts.occurrence;\n if (parts.fact !== undefined) env.fact = parts.fact;\n if (parts.facts !== undefined) env.facts = parts.facts;\n if (parts.row !== undefined) env.row = parts.row;\n if (parts.rows !== undefined) env.rows = parts.rows;\n return env;\n};\n\nexport const withNow = (env: Row, now: number): Row => ({ ...env, now });\n\n// A template that throws is the author's problem, not the engine's: it is\n// reported where it happened (a delivery note, a task error, a preview\n// line) and never crashes a tick.\nexport const evaluateTemplate = (transform: TransformFn, config: unknown, env: Row): unknown =>\n config === undefined ? undefined : transform(config, env);\n\nexport const isTruthy = (value: unknown): boolean => {\n if (value === undefined || value === null || value === false) return false;\n if (value === 0 || value === '') return false;\n if (Array.isArray(value)) return value.length > 0;\n return true;\n};\n\n// ── version — a content hash of the definition ──────────────────\n//\n// `enabled` is a switch on the row, not part of the definition: flipping\n// it is not an edit. `params` ARE part of it — changing graceDays from 3\n// to 7 is a behavioural change the ledger must be able to explain.\n\nconst canonical = (value: unknown): string => {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n const entries = Object.entries(value)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : 1));\n return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${canonical(entryValue)}`).join(',')}}`;\n};\n\nexport const versionOf = (reflex: Reflex): string => {\n const { enabled: _enabled, ...definition } = reflex;\n const text = canonical(definition);\n // FNV-1a, two lanes. An identity token for the ledger, not a security\n // hash — but wide enough that an edit is never mistaken for its ancestor.\n let hashA = 0x811c9dc5;\n let hashB = 0x01000193;\n for (let index = 0; index < text.length; index += 1) {\n const code = text.charCodeAt(index);\n hashA = Math.imul(hashA ^ code, 0x01000193) >>> 0;\n hashB = Math.imul(hashB ^ ((code << 3) | index % 7), 0x85ebca6b) >>> 0;\n }\n return `v_${hashA.toString(16).padStart(8, '0')}${hashB.toString(16).padStart(8, '0')}`;\n};\n","import { factOf } from '../schemas';\nimport type { Reflex } from '../schemas';\nimport type { EffectRegistry } from '../types';\n\n// ═══════════════════════════════════════════════════════════════\n// The flow graph — derived, never drawn\n//\n// Reflexes WATCH entities (their triggers name them); effects\n// WRITE entities. An edge is a write meeting a watch. The graph is\n// therefore STATIC DATA computed from the artifacts — under moss,\n// `writes` is DERIVED from the vex mutation behind each effect —\n// which is what makes it impossible for the flowchart to drift\n// from the flow.\n//\n// Cycles are CLASSIFIED, not banned. Tide's own best patterns are\n// cycles on purpose — a drip campaign is a reflex whose delayed\n// fact fires itself; a drain loop subscribes to its own firing —\n// and they converge because every loop passes a GUARD. Static\n// analysis cannot tell a convergent cycle from a divergent one,\n// so it does not pretend to: only a wholly unguarded loop, which\n// diverges by construction, is refused.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Edge = { from: string; to: string; via: string };\n\nexport type GraphReport = {\n edges: readonly Edge[];\n cycles: readonly { reflexIds: readonly string[]; guarded: boolean }[];\n // Effects with no declared (or derived) `writes` — the checker cannot\n // see through them. Under moss, where `writes` derives from the vex\n // mutation, a blind edge means something BYPASSED vex, which is exactly\n // when a loud word is wanted.\n blind: readonly { reflexId: string; effect: string }[];\n errors: readonly string[];\n // The same refusals as `errors`, each with the code it is refused under.\n refusals: readonly { code: 'unknown_reflex' | 'unknown_effect' | 'unguarded_cycle'; message: string }[];\n warnings: readonly string[];\n};\n\n// A guard is what makes a loop convergent: a selection that re-checks\n// reality, or a predicate that can say no. `notBefore` also guards, but it\n// is a runtime property of an emitted fact and cannot be seen from here —\n// which is why an unguarded cycle is reported as an error the author can\n// argue with, not a silent refusal.\nconst isGuarded = (reflex: Reflex): boolean => reflex.select !== undefined || reflex.when !== undefined;\n\nexport const buildGraph = (reflexes: readonly Reflex[], effects: EffectRegistry): GraphReport => {\n const edges: Edge[] = [];\n const refusals: { code: 'unknown_reflex' | 'unknown_effect' | 'unguarded_cycle'; message: string }[] = [];\n const warnings: string[] = [];\n const blind: { reflexId: string; effect: string }[] = [];\n\n const byId = new Map(reflexes.map((reflex) => [reflex.id, reflex]));\n\n const watchers = new Map<string, string[]>();\n const runWatchers = new Map<string, string[]>();\n for (const reflex of reflexes) {\n const fact = factOf(reflex.on);\n if (fact?.entity !== undefined) {\n const existing = watchers.get(fact.entity) ?? [];\n watchers.set(fact.entity, [...existing, reflex.id]);\n }\n if (fact?.run !== undefined) {\n const existing = runWatchers.get(fact.run) ?? [];\n runWatchers.set(fact.run, [...existing, reflex.id]);\n if (fact.run === reflex.id) warnings.push(`${reflex.id} subscribes to its own run — a drain loop; make sure it narrows`);\n if (!byId.has(fact.run)) refusals.push({ code: 'unknown_reflex', message: `${reflex.id} watches the run of unknown reflex \"${fact.run}\"` });\n }\n }\n\n for (const reflex of reflexes) {\n const handler = effects[reflex.effect.name];\n if (handler === undefined) {\n refusals.push({ code: 'unknown_effect', message: `${reflex.id} names effect \"${reflex.effect.name}\", which is not registered` });\n continue;\n }\n if (handler.writes === undefined) {\n blind.push({ reflexId: reflex.id, effect: reflex.effect.name });\n continue;\n }\n for (const entity of handler.writes)\n for (const target of watchers.get(entity) ?? []) edges.push({ from: reflex.id, to: target, via: entity });\n }\n\n for (const [source, targets] of runWatchers)\n for (const target of targets) if (byId.has(source)) edges.push({ from: source, to: target, via: `run:${source}` });\n\n const cycles = findCycles(reflexes, edges).map((reflexIds) => ({\n reflexIds,\n guarded: reflexIds.some((id) => {\n const reflex = byId.get(id);\n return reflex !== undefined && isGuarded(reflex);\n }),\n }));\n\n for (const cycle of cycles)\n if (!cycle.guarded)\n refusals.push({\n code: 'unguarded_cycle',\n message: `unguarded cycle: ${cycle.reflexIds.join(' → ')} → ${cycle.reflexIds[0]} — no selection and no \\`when\\` anywhere on the loop, so it diverges by construction`,\n });\n\n return { edges, cycles, blind, errors: refusals.map((refusal) => refusal.message), refusals, warnings };\n};\n\n// Tarjan's SCC. Components of size > 1 are cycles; a size-1 component is\n// one only when it edges to itself.\nconst findCycles = (reflexes: readonly Reflex[], edges: readonly Edge[]): string[][] => {\n const adjacency = new Map<string, string[]>();\n for (const reflex of reflexes) adjacency.set(reflex.id, []);\n for (const edge of edges) {\n const existing = adjacency.get(edge.from);\n if (existing !== undefined) existing.push(edge.to);\n }\n\n const index = new Map<string, number>();\n const low = new Map<string, number>();\n const onStack = new Set<string>();\n const stack: string[] = [];\n const components: string[][] = [];\n let counter = 0;\n\n const strongConnect = (node: string): void => {\n index.set(node, counter);\n low.set(node, counter);\n counter += 1;\n stack.push(node);\n onStack.add(node);\n\n for (const next of adjacency.get(node) ?? []) {\n const nextIndex = index.get(next);\n if (nextIndex === undefined) {\n strongConnect(next);\n const nextLow = low.get(next);\n const nodeLow = low.get(node);\n if (nextLow !== undefined && nodeLow !== undefined) low.set(node, Math.min(nodeLow, nextLow));\n } else if (onStack.has(next)) {\n const nodeLow = low.get(node);\n if (nodeLow !== undefined) low.set(node, Math.min(nodeLow, nextIndex));\n }\n }\n\n if (low.get(node) === index.get(node)) {\n const component: string[] = [];\n let popped = stack.pop();\n while (popped !== undefined) {\n onStack.delete(popped);\n component.push(popped);\n if (popped === node) break;\n popped = stack.pop();\n }\n components.push(component.reverse());\n }\n };\n\n for (const reflex of reflexes) if (!index.has(reflex.id)) strongConnect(reflex.id);\n\n const selfLooping = new Set(edges.filter((edge) => edge.from === edge.to).map((edge) => edge.from));\n return components.filter((component) => {\n if (component.length > 1) return true;\n const only = component[0];\n return only !== undefined && selfLooping.has(only);\n });\n};\n","import { WEEKDAYS, isRecurring } from '../schemas';\nimport type { Clock, ClockRecurring } from '../schemas';\n\n// ═══════════════════════════════════════════════════════════════\n// Occurrences — local calendar fields, never instants\n//\n// A DST boundary can move the INSTANT a key fires at; it cannot\n// mint a second key or lose one. `2026-03` exists exactly once\n// whatever the clock does, so the double-fire and the silent skip\n// are structurally impossible rather than carefully avoided — and\n// catch-up is decidable, because the missed keys are enumerable.\n//\n// Zero dependencies: timezone resolution rides the platform's own\n// IANA data through Intl.\n// ═══════════════════════════════════════════════════════════════\n\nexport type LocalParts = { year: number; month: number; day: number; hour: number; minute: number; second: number };\nexport type LocalDay = { year: number; month: number; day: number };\nexport type Occurrence = { key: string; at: number };\n\nconst HALF_DAY_MS = 43_200_000;\nconst DAY_MS = 86_400_000;\n// Ten years of local days. A bound, not a policy: catch-up covers outages\n// and deliberate backfill is its own (deferred) verb.\nconst MAX_DAYS_SCANNED = 3_700;\n\nconst FORMATTERS = new Map<string, Intl.DateTimeFormat>();\n\nconst formatterFor = (tz: string): Intl.DateTimeFormat => {\n const cached = FORMATTERS.get(tz);\n if (cached !== undefined) return cached;\n const built = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n });\n FORMATTERS.set(tz, built);\n return built;\n};\n\nexport const zonedParts = (instant: number, tz: string): LocalParts => {\n const parts = formatterFor(tz).formatToParts(new Date(instant));\n const read = (type: Intl.DateTimeFormatPartTypes): number => {\n const found = parts.find((part) => part.type === type);\n return found === undefined ? 0 : Number(found.value);\n };\n return {\n year: read('year'),\n month: read('month'),\n day: read('day'),\n hour: read('hour'),\n minute: read('minute'),\n second: read('second'),\n };\n};\n\nconst offsetAt = (instant: number, tz: string): number => {\n const parts = zonedParts(instant, tz);\n const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);\n return asIfUtc - Math.floor(instant / 1000) * 1000;\n};\n\nconst rendersAs = (instant: number, tz: string, day: LocalDay, hour: number, minute: number): boolean => {\n const parts = zonedParts(instant, tz);\n return (\n parts.year === day.year &&\n parts.month === day.month &&\n parts.day === day.day &&\n parts.hour === hour &&\n parts.minute === minute\n );\n};\n\n// A local wall-clock time → the instant it names.\n//\n// The two edges are DECIDED, not discovered. Probing the offset half a day\n// either side is what surfaces both candidates across a transition; probing\n// at the guess alone finds only one, and silently returns the wrong side of\n// a fall-back. Ambiguous (fall back) → the FIRST occurrence. Erased (spring\n// forward) → shifted forward past the gap. Both match Temporal's\n// `disambiguation: 'compatible'`, so behaviour here is not tide's invention.\nexport const zonedToUtc = (day: LocalDay, hour: number, minute: number, tz: string): number => {\n const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);\n const before = offsetAt(guess - HALF_DAY_MS, tz);\n const after = offsetAt(guess + HALF_DAY_MS, tz);\n const candidates = before === after ? [guess - before] : [guess - before, guess - after];\n const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));\n return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);\n};\n\nexport const daysInMonth = (year: number, month: number): number => new Date(Date.UTC(year, month, 0)).getUTCDate();\n\nconst weekdayOf = (day: LocalDay): string => {\n const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();\n // getUTCDay is Sunday-first; WEEKDAYS is Monday-first.\n return WEEKDAYS[(index + 6) % 7] ?? 'mon';\n};\n\nconst splitInts = (value: string, separator: string): number[] =>\n value.split(separator).map((part) => Number(part));\n\nconst at2 = (values: readonly number[], index: number): number => values[index] ?? 0;\n\nconst nextDay = (day: LocalDay): LocalDay => {\n const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);\n return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };\n};\n\nconst ordinalOf = (day: LocalDay): number => day.year * 10_000 + day.month * 100 + day.day;\n\nconst pad2 = (value: number): string => String(value).padStart(2, '0');\n\n// Day-31 clamps to month end: February bills on the 28th, because\n// \"skip February\" is never what a billing rule means. A yearly Feb-29\n// clamps the same way, for the same reason.\nconst isDueOn = (clock: ClockRecurring, day: LocalDay): boolean => {\n if (clock.every === 'day') return true;\n if (clock.every === 'week') return weekdayOf(day) === clock.on;\n if (clock.every === 'month')\n return typeof clock.on === 'number' && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));\n if (typeof clock.on !== 'string') return false;\n const parts = splitInts(clock.on, '-');\n const month = at2(parts, 0);\n const dayOfMonth = at2(parts, 1);\n return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));\n};\n\nexport const occurrenceKey = (clock: ClockRecurring, day: LocalDay): string => {\n if (clock.every === 'year') return String(day.year);\n if (clock.every === 'month') return `${day.year}-${pad2(day.month)}`;\n return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;\n};\n\n// Every occurrence in (after, through]. Half-open at the start so a\n// materialization watermark can advance without re-minting its own edge.\nexport const occurrencesBetween = (clock: Clock, after: number, through: number, cap: number): Occurrence[] => {\n if (through <= after || cap <= 0) return [];\n\n if (!isRecurring(clock)) {\n const [date = '', time = ''] = clock.at.split('T');\n const ymd = splitInts(date, '-');\n const hms = splitInts(time, ':');\n // The second is added to the resolved minute: an offset changes on a\n // minute boundary, never inside one, so the minute decides the edge.\n const at =\n zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) +\n at2(hms, 2) * 1000;\n return at > after && at <= through ? [{ key: clock.at, at }] : [];\n }\n\n const time = splitInts(clock.at, ':');\n const hour = at2(time, 0);\n const minute = at2(time, 1);\n const start = zonedParts(after, clock.tz);\n const end = zonedParts(through, clock.tz);\n const endOrdinal = ordinalOf(end);\n\n const found: Occurrence[] = [];\n let cursor: LocalDay = { year: start.year, month: start.month, day: start.day };\n let scanned = 0;\n\n while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {\n scanned += 1;\n if (isDueOn(clock, cursor)) {\n const at = zonedToUtc(cursor, hour, minute, clock.tz);\n if (at > after && at <= through) {\n found.push({ key: occurrenceKey(clock, cursor), at });\n if (found.length >= cap) break;\n }\n }\n cursor = nextDay(cursor);\n }\n\n return found;\n};\n","import { factOf, isManual } from '../schemas';\nimport type { Fact, Row, Run } from '../types';\nimport { buildEnv, evaluateTemplate, isTruthy } from './runtime';\nimport type { EngineDeps, LoadedReflex } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// Match — facts × reflexes\n//\n// Matching is per (fact, reflex): one fact can wake five. A `when`\n// that throws is a recorded non-match, never a crashed advance and\n// never a silent one — the two failure modes a naive matcher\n// chooses between.\n//\n// There is no delivery table. \"Which reflexes did this fact wake\"\n// is `WHERE cause = 'fact:<id>'`, a column rather than a join\n// table; and the non-matches, which outnumber the matches and grow\n// with the number of loaded reflexes rather than with the work,\n// are an EVENT the host can log at whatever grain it wants.\n// ═══════════════════════════════════════════════════════════════\n\nexport type OpenRunInput = {\n cause: string;\n depth: number;\n dueAt: number;\n now: number;\n occurrence?: string;\n factIds?: readonly string[];\n note?: string;\n state?: 'pending' | 'skipped';\n // Whether this cause is a REPEAT of work that may already be running.\n // `overlap: 'skip'` reads it, and nothing else does. See openRun.\n repeat?: boolean;\n};\n\n// The one place a run is born. Overlap lives here because \"may this start\n// while the last is unsettled\" is a question about the reflex, not about\n// what woke it.\nexport const openRun = async (deps: EngineDeps, loaded: LoadedReflex, input: OpenRunInput): Promise<Run | undefined> => {\n const { reflex, version } = loaded;\n\n const base = {\n reflexId: reflex.id,\n version,\n // Written down so the ledger is scopeable by an ordinary host rule\n // rather than by parsing reflex ids. Opaque to tide.\n as: reflex.as,\n cause: input.cause,\n occurrence: input.occurrence,\n factIds: input.factIds,\n depth: input.depth,\n total: 0,\n done: 0,\n failed: 0,\n dueAt: input.dueAt,\n createdAt: input.now,\n };\n\n // OVERLAP GOVERNS REPEATS, NOT DISTINCT EVENTS.\n //\n // \"May this start while the last is unsettled\" is a sensible question about\n // an occurrence — next month's billing run arriving while this month's is\n // still going is the same work coming round again, and skipping it is the\n // whole point. It is the WRONG question about a payment: two payments are two\n // pieces of work, and the second is not a repeat of the first.\n //\n // The default is `'skip'`, so with no distinction every fact-triggered reflex\n // silently dropped its second fact per tick. Three members joining in one\n // minute produced one welcome email and two skipped runs — recorded, so not\n // invisible, but gone. Lyra's watched automations were all in that state.\n //\n // A `manual` fact IS a repeat — a human pressing \"run now\" twice — so it\n // still guards. The tool for \"do not run my handlers concurrently\" is\n // `order: 'serial'`, which QUEUES; overlap discards, and discarding an\n // external event that exists exactly once is data loss.\n if (input.repeat !== false && input.state !== 'skipped' && reflex.policy.overlap === 'skip') {\n const [unsettled] = await deps.store.query({\n table: 'run',\n where: { reflexId: reflex.id, state: { in: ['pending', 'fanned'] } },\n limit: 1,\n });\n if (unsettled !== undefined) {\n await deps.store.appendIfAbsent('run', {\n ...base,\n state: 'skipped',\n settledAt: input.now,\n // Nothing waits on it and nothing announces it: a run that never\n // started has no settlement to report.\n drained: true,\n note: `overlap: the previous run (${unsettled.id}) is still unsettled`,\n });\n deps.emit({ type: 'run.skipped', reflexId: reflex.id, reason: 'overlap' });\n return undefined;\n }\n }\n\n const skipped = input.state === 'skipped';\n const run = await deps.store.appendIfAbsent('run', {\n ...base,\n state: input.state ?? 'pending',\n settledAt: skipped ? input.now : undefined,\n drained: skipped ? true : undefined,\n note: input.note,\n });\n\n if (run !== undefined && run.state === 'pending') deps.emit({ type: 'run.created', run });\n return run;\n};\n\nconst factAsRow = (fact: Fact): Row => ({ ...fact });\n\nexport const reflexMatchesFact = (loaded: LoadedReflex, fact: Fact): boolean => {\n const { reflex } = loaded;\n\n // Checked FIRST, before enablement and arming: arming gates triggers, not\n // people. Testing before arming is half of what `fire` is for.\n if (fact.kind === 'manual') return fact.target === reflex.id;\n\n // A FACT MINTED UNDER ONE IDENTITY CANNOT WAKE A REFLEX RUNNING UNDER\n // ANOTHER. This is the tenant boundary inside the engine, and it is needed\n // because tide is the one place a row travels WITHOUT being read.\n //\n // Every database access already goes through the host: a selection and an\n // effect's write both run as the reflex's own principal, under a compiled\n // scope policy, and neither can see another tenant's rows. That held.\n // What leaked was the row tide was already carrying as a payload — in a\n // minted write fact, in a handler's `emit`, in a settled run's stats. The\n // matcher paired those payloads with reflexes by ENTITY alone, so one\n // tenant's row was handed to another tenant's effect and written under\n // their identity. No query was involved, so no policy was consulted, and\n // nothing downstream could have caught it: the row that landed was\n // legitimately the recipient's.\n //\n // The string is opaque — tide never learns what a principal is. STRICT\n // equality is the entire rule, and strict is the point: an earlier version\n // exempted facts with no identity, on the reasoning that the host knows what\n // it ingested. That is a hole with a rationalisation on top. A Stripe\n // webhook ingested for one tenant woke every tenant's `signal: 'stripe'`\n // reflex, and the payload went with it.\n //\n // So a fact with no identity wakes only reflexes with no identity. A host\n // that uses `as` declares it at the intake — `ingest(fact, { as })` — and a\n // host that does not use identities at all is unaffected, because undefined\n // equals undefined. An event that genuinely concerns every tenant is\n // ingested once per tenant, by the only party that can know which those are.\n //\n // Manual facts are exempt above and do not need this: `target` names exactly\n // one reflex, which is narrower than an identity.\n if (fact.as !== reflex.as) return false;\n\n if (!reflex.enabled) return false;\n // Never retro-fire: a fact older than the arming belongs to a world in\n // which this reflex did not exist.\n if (fact.at < loaded.armedAt) return false;\n\n if (isManual(reflex.on)) return false;\n\n const watched = factOf(reflex.on);\n if (watched === undefined) return false;\n\n if (fact.kind === 'write')\n return watched.entity !== undefined && watched.entity === fact.entity && (watched.op === undefined || watched.op === fact.op);\n if (fact.kind === 'signal') return watched.signal !== undefined && watched.signal === fact.name;\n if (fact.kind === 'run') return watched.run !== undefined && watched.run === fact.reflex;\n return false;\n};\n\nexport type MatchReport = { factsMatched: number; runsCreated: number; parked: number };\n\nexport const matchFacts = async (deps: EngineDeps, now: number, limit: number): Promise<MatchReport> => {\n const report: MatchReport = { factsMatched: 0, runsCreated: 0, parked: 0 };\n\n // NOTHING LOADED IS NOT \"OFFERED TO EVERYONE\".\n //\n // A fact is complete once it has been offered to every loaded reflex, and\n // with none loaded that condition was vacuously true: a tick racing `load()`\n // marked the whole backlog delivered, and the never-retro-fire rule then put\n // it permanently out of reach. Facts wait instead; retention bounds the wait.\n if (deps.reflexes().length === 0) return report;\n\n // Due, undelivered, unparked — ordered by when they became due, so a\n // backlog drains oldest-first.\n const due = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true } },\n order: [{ by: 'at' }],\n limit: limit * 4,\n });\n\n for (const fact of due.filter((candidate) => (candidate.notBefore ?? candidate.at) <= now).slice(0, limit)) {\n // The runtime backstop behind the load-time cycle rules. Nearly free,\n // because causality is already recorded: a divergent loop hits a loud\n // ceiling instead of melting the ledger.\n //\n // `released` is a human's override and has to survive the check that\n // parked it. Clearing `parked` alone re-parked the fact on the very next\n // tick — the depth had not changed and never would.\n if (fact.depth > deps.maxChainDepth && fact.released !== true) {\n const reason = `chain depth ${fact.depth} exceeds maxChainDepth ${deps.maxChainDepth}`;\n await deps.store.cas('fact', fact.id, {}, { parked: reason });\n deps.emit({ type: 'fact.parked', fact, reason });\n report.parked += 1;\n continue;\n }\n\n let woke = false;\n\n for (const loaded of deps.reflexes()) {\n if (!reflexMatchesFact(loaded, fact)) continue;\n\n const env = buildEnv({ params: loaded.reflex.params, fact: factAsRow(fact), now });\n\n if (loaded.reflex.when !== undefined) {\n try {\n if (!isTruthy(evaluateTemplate(deps.transform, loaded.reflex.when, env))) {\n deps.emit({ type: 'fact.unmatched', fact, reflexId: loaded.reflex.id, reason: '`when` did not match' });\n continue;\n }\n } catch (error) {\n deps.emit({\n type: 'fact.unmatched',\n fact,\n reflexId: loaded.reflex.id,\n reason: `when: ${error instanceof Error ? error.message : String(error)}`,\n });\n continue;\n }\n }\n\n woke = true;\n\n const run = await openRun(deps, loaded, {\n cause: `fact:${fact.id}`,\n depth: fact.depth,\n dueAt: now,\n now,\n occurrence: fact.occurrence,\n factIds: [fact.id],\n // A write, a signal or another reflex's settlement happened once and\n // will not happen again; a human pressing the button twice will.\n repeat: fact.kind === 'manual',\n });\n if (run !== undefined) report.runsCreated += 1;\n }\n\n await deps.store.cas('fact', fact.id, {}, { deliveredAt: now });\n if (woke) report.factsMatched += 1;\n }\n\n return report;\n};\n","import { clockOf } from '../schemas';\nimport type { ReflexState } from '../types';\nimport type { EngineDeps, LoadedReflex } from './runtime';\nimport { occurrencesBetween } from './occurrence';\nimport { openRun } from './match';\n\n// ═══════════════════════════════════════════════════════════════\n// Materialize — the clock\n//\n// Occurrences are materialized AHEAD, which is what makes silence\n// visible: a run that should have happened and didn't is a pending\n// row past its due time — a query, not a vanished event.\n//\n// One row read and written per reflex. The watermark used to be\n// an unbounded key/value table with a growing set of string keys;\n// \"where has this reflex got to\" is a property of the reflex, and\n// there are as many of those as there are reflexes.\n// ═══════════════════════════════════════════════════════════════\n\nconst MAX_OCCURRENCES_PER_TICK = 500;\n\nexport const stateOf = async (deps: EngineDeps, reflexId: string): Promise<ReflexState | undefined> =>\n (await deps.store.query({ table: 'state', where: { reflexId }, limit: 1 }))[0];\n\n// Upsert on a table whose primary key IS the reflex id. The append can lose\n// to another instance creating the row first, which is a refusal rather than\n// an error — so the patch is re-applied to the row that won.\nconst patchState = async (deps: EngineDeps, reflexId: string, patch: Partial<ReflexState>): Promise<void> => {\n if (await deps.store.cas('state', reflexId, {}, patch)) return;\n const created = await deps.store.appendIfAbsent('state', { reflexId, armedAt: 0, ...patch });\n if (created === undefined) await deps.store.cas('state', reflexId, {}, patch);\n};\n\nexport type MaterializeReport = { materialized: number; skippedOccurrences: number; runsCreated: number };\n\nexport const materializeClocks = async (deps: EngineDeps, now: number): Promise<MaterializeReport> => {\n const report: MaterializeReport = { materialized: 0, skippedOccurrences: 0, runsCreated: 0 };\n\n for (const loaded of deps.reflexes()) {\n const clock = clockOf(loaded.reflex.on);\n if (clock === undefined) continue;\n\n const state = await stateOf(deps, loaded.reflex.id);\n // A clock reflex with no arming time ESTABLISHES its baseline on the\n // first advance and mints nothing: materializing from the epoch would\n // backfill decades of occurrences nobody asked for. A host that wants\n // history passes `at` to load(), or waits for the deferred backfill verb.\n const through = state?.materializedThrough ?? (loaded.armedAt > 0 ? loaded.armedAt : now);\n\n // A DISARMED REFLEX STILL MOVES ITS WATERMARK.\n //\n // Skipping it outright froze the line where the disarm happened, so a\n // reflex paused for eight days minted eight occurrences the moment it\n // came back — and, before the switch became the host's own column, eight\n // real effects with it. Nothing is materialized while it is off; the\n // clock simply keeps moving, which is what \"paused\" means to everybody\n // who is not a computer.\n if (!loaded.reflex.enabled || now <= through) {\n if (state?.materializedThrough === undefined || now > through)\n await patchState(deps, loaded.reflex.id, { materializedThrough: loaded.reflex.enabled ? through : now });\n continue;\n }\n\n const occurrences = occurrencesBetween(clock, through, now, MAX_OCCURRENCES_PER_TICK);\n const newest = occurrences.length === 0 ? undefined : occurrences[occurrences.length - 1];\n const { catchUp, lateMs } = loaded.reflex.policy;\n\n for (const occurrence of occurrences) {\n // Catch-up is AUTHORED, not guessed. Each decision leaves a run row\n // saying which happened — a skipped run is a recorded decision, never\n // an absence somebody has to infer.\n const isNewest = occurrence === newest;\n const late = now - occurrence.at > lateMs;\n const skip = catchUp === 'latest' ? !isNewest : catchUp === 'skip' ? late : false;\n\n const run = await openRun(deps, loaded, {\n cause: `occurrence:${occurrence.key}`,\n depth: 0,\n dueAt: occurrence.at,\n now,\n occurrence: occurrence.key,\n state: skip ? 'skipped' : 'pending',\n note: skip ? `catchUp: ${catchUp} — occurrence ${occurrence.key} was ${Math.round((now - occurrence.at) / 1000)}s late` : undefined,\n });\n\n if (skip) report.skippedOccurrences += 1;\n else if (run !== undefined) {\n report.materialized += 1;\n report.runsCreated += 1;\n }\n }\n\n // THE WATERMARK FOLLOWS THE WORK, NOT THE CLOCK.\n //\n // It used to jump to `now` unconditionally. A reflex that came back after\n // a long outage produced more occurrences than the per-tick cap, and\n // everything past the cap was dropped while the watermark sailed past it:\n // unreachable forever, with no row anywhere saying they had existed. When\n // the cap bites, the next tick resumes from the last key actually\n // materialized — `occurrencesBetween` is half-open at the start, so the\n // edge is not re-minted.\n const capped = occurrences.length >= MAX_OCCURRENCES_PER_TICK && newest !== undefined;\n await patchState(deps, loaded.reflex.id, { materializedThrough: capped ? newest.at : now });\n }\n\n return report;\n};\n","import { TideError, isTideError } from '../errors';\nimport type { Fact, Row, Run, Task } from '../types';\nimport { buildEnv, evaluateTemplate } from './runtime';\nimport type { EngineDeps, LoadedReflex } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// Fan out — a run becomes unit tasks\n//\n// Transactional, and that is the whole point. A fan-out that\n// crashed at row 200 of 500 and RESUMED would re-select against\n// moved data: a member who paid in the gap keeps a task minted\n// from the stale pass. Committing the tasks with the run's\n// transition means a crash leaves nothing to resume from, so the\n// re-run selects fresh and mints clean.\n// ═══════════════════════════════════════════════════════════════\n\nexport const collectRows = async (\n source: AsyncIterable<Row> | Iterable<Row> | Promise<Iterable<Row>>,\n cap: number,\n): Promise<readonly Row[]> => {\n const resolved = await source;\n const rows: Row[] = [];\n if (Symbol.asyncIterator in Object(resolved)) {\n for await (const row of resolved as AsyncIterable<Row>) {\n rows.push(row);\n if (rows.length > cap) throw new TideError('duplicate_unit', `selection exceeded maxFanOut (${cap})`);\n }\n return rows;\n }\n for (const row of resolved as Iterable<Row>) {\n rows.push(row);\n if (rows.length > cap) throw new TideError('duplicate_unit', `selection exceeded maxFanOut (${cap})`);\n }\n return rows;\n};\n\ntype Unit = { unit: string; env: Row };\n\nconst unitsFrom = (rows: readonly Row[], unitKey: string | undefined, base: Row, reflexId: string): Unit[] => {\n const seen = new Set<string>();\n return rows.map((row) => {\n const raw = unitKey === undefined ? undefined : row[unitKey];\n const unit = raw === undefined || raw === null ? '' : String(raw);\n // A duplicate unit key means the run's GRAIN is wrong. Letting the\n // unique constraint eat the second row would hide an authoring error;\n // an authoring error is loud or it is invisible.\n if (seen.has(unit))\n throw new TideError('duplicate_unit', `${reflexId}: duplicate unit key \"${unit}\" — the selection's unitKey is not unique`);\n seen.add(unit);\n return { unit, env: { ...base, row } };\n });\n};\n\nconst factRowsOf = async (deps: EngineDeps, run: Run): Promise<readonly Fact[]> => {\n const ids = run.factIds ?? [];\n if (ids.length === 0) return [];\n return deps.store.query({ table: 'fact', where: { id: { in: [...ids] } } });\n};\n\nexport const fanOut = async (deps: EngineDeps, now: number, limit: number): Promise<number> => {\n let created = 0;\n\n const pending = await deps.store.query({\n table: 'run',\n where: { state: 'pending' },\n order: [{ by: 'dueAt' }],\n limit,\n });\n\n for (const run of pending) {\n const loaded = deps.find(run.reflexId);\n if (loaded === undefined) {\n await deps.store.cas('run', run.id, { state: 'pending' }, { state: 'skipped', settledAt: now, drained: true, note: 'reflex is no longer loaded' });\n continue;\n }\n\n try {\n const facts = await factRowsOf(deps, run);\n const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);\n created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n // A TRANSIENT FAILURE MUST NOT CONSUME AN OCCURRENCE.\n //\n // Every throw used to mark the run `skipped`. Runs are idempotent on\n // (reflexId, cause), so the occurrence could never re-materialize —\n // one database hiccup during a selection destroyed that night's\n // billing run permanently, and because `skipped` is not `settled`,\n // anything waiting on it waited forever.\n //\n // The two cases are distinguishable and the distinction is the fix.\n // A TideError is tide's own refusal — a duplicate unit key, a\n // selection with no `select` seam — which means the REFLEX is wrong\n // and will be wrong again next tick. Anything else came out of a host\n // seam: the selection, the transform, the database. That is a bad\n // minute, not a bad reflex.\n //\n // Deferring leaves the run `pending`, which is a row past its due\n // time that a query can see — visible silence, not a vanished event.\n if (isTideError(error)) {\n await deps.store.cas('run', run.id, { state: 'pending' }, { state: 'skipped', settledAt: now, drained: true, note: `fan-out refused: ${reason}` });\n deps.emit({ type: 'run.skipped', reflexId: run.reflexId, reason });\n continue;\n }\n\n await deps.store.cas('run', run.id, { state: 'pending' }, { note: `fan-out deferred: ${reason}` });\n deps.emit({ type: 'run.deferred', reflexId: run.reflexId, runId: run.id, reason });\n }\n }\n\n return created;\n};\n\n// ATOMIC: the tasks and the run's move to `fanned` commit together. A crash\n// mid-fan-out must leave NOTHING to resume from, because resuming would\n// re-select against moved data.\nconst commitFanout = async (\n deps: EngineDeps,\n run: Run,\n tasks: readonly Omit<Task, 'id'>[],\n selected: number,\n now: number,\n): Promise<number> =>\n deps.store.transact(async (tx) => {\n // Guarded on `pending`, so a second instance that fanned this run out\n // first finds nothing to do rather than minting a duplicate set.\n const claimed = await tx.cas('run', run.id, { state: 'pending' }, { state: 'fanned' });\n if (!claimed) return 0;\n\n let written = 0;\n for (const task of tasks) if ((await tx.appendIfAbsent('task', task)) !== undefined) written += 1;\n\n // `total` is what was WRITTEN, not what was offered. Counting the input\n // array meant any refusal by the unique key left `total` permanently\n // unreachable — the run never settled, never drained, and blocked its\n // reflex for good.\n const settledNow = written === 0;\n await tx.cas(\n 'run',\n run.id,\n {},\n {\n selected,\n total: written,\n // A zero-task run settles immediately and still announces itself —\n // \"nothing was due\" is an answer a digest may legitimately want.\n state: settledNow ? 'settled' : 'fanned',\n settledAt: settledNow ? now : undefined,\n },\n );\n return written;\n });\n\nconst taskOf = (unit: Unit, run: Run, loaded: LoadedReflex, now: number): Omit<Task, 'id'> => ({\n runId: run.id,\n reflexId: loaded.reflex.id,\n unit: unit.unit,\n // UNIQUE(runId, unit) — the idempotency grain, written BEFORE the effect\n // runs. There is no path to the effect that skips this row.\n cause: run.cause,\n env: unit.env,\n // Carried, not looked up later: a swept run must not reset the chain\n // ceiling for work that is still in flight.\n depth: run.depth,\n state: 'pending',\n attempt: 0,\n claimedUntil: 0,\n notBefore: run.dueAt > now ? run.dueAt : now,\n createdAt: now,\n});\n\n// What fan-out needs from a run — no more. Preview builds one of these\n// without persisting anything, which is how the dry run walks the SAME code\n// path as the real thing rather than a sympathetic reimplementation of it.\nexport type RunShape = { cause: string; occurrence?: string; dueAt: number };\n\nconst shapeOf = (run: Run): RunShape => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });\n\nexport const unitsForRun = async (\n deps: EngineDeps,\n loaded: LoadedReflex,\n run: RunShape,\n facts: readonly Fact[],\n now: number,\n): Promise<Unit[]> => {\n const { reflex } = loaded;\n\n const base = buildEnv({\n params: reflex.params,\n occurrence: run.occurrence === undefined ? undefined : { key: run.occurrence, at: run.dueAt },\n fact: facts.length === 1 ? { ...facts[0] } : undefined,\n facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : undefined,\n now,\n });\n\n // A write fact CARRIES the row that caused it — minted at the host's\n // write choke point under this reflex's own identity. With no selection\n // declared, that row IS the unit: re-selecting would ask the database a\n // question the fact already answers, and answer it differently if the\n // row has moved. A declared selection is ENRICHMENT — it re-checks\n // reality under the reflex's own principal at fan-out time, which is the\n // guard that makes write-driven chains safe to loop.\n //\n // `preview` passes no fact and `fire`'s manual fact has no row; both fall\n // through to the selection (or the unit-less base), which is what a human\n // rehearsing or forcing a reflex means to ask.\n const carried = facts.map((fact) => fact.row).filter((row): row is Row => row !== undefined);\n if (carried.length > 0 && reflex.select === undefined) return unitsFrom(carried, undefined, base, reflex.id);\n\n if (reflex.select === undefined) return [{ unit: '', env: base }];\n\n if (deps.select === undefined)\n throw new TideError('store', `${reflex.id} has a selection but no \\`select\\` seam is wired`);\n\n const query = evaluateTemplate(deps.transform, reflex.select.query, base);\n const rows = await collectRows(\n deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),\n deps.maxFanOut,\n );\n\n if (reflex.select.mode === 'batch') return [{ unit: '', env: { ...base, rows } }];\n return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);\n};\n\nexport type { Unit };\n","import type { Fact, NewFact, TideEvent, TideStore } from '../types';\n\n// ═══════════════════════════════════════════════════════════════\n// The ONE door into the fact table\n//\n// Facts arrive three ways — the host ingests one, a handler emits\n// one, a settled run reports its stats as one — and they used to\n// be three bare `appendIfAbsent('fact', …)` calls, each of which\n// had to remember to announce what it wrote. One forgot: a chain\n// continued by `ctx.emit` landed in the ledger and never appeared\n// in the event stream, so a watcher saw a run start on a fact\n// nobody announced. And none of them announced a REFUSAL, so an\n// emitted fact that landed and one that collided on its dedupeKey\n// looked identical — silence either way.\n//\n// So admitting and announcing are split, and both live here.\n// `admitFact` writes and says what happened; `announceFact` turns\n// that into the event. They are two functions rather than one\n// because a write inside a transaction must not be announced until\n// the transaction commits — an event describes a row that exists,\n// never one a rollback is about to take back.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Admission = { stored: Fact } | { refused: NewFact };\n\n// THE CHAIN'S ROOT, from what caused this fact: a task or a run, back to the\n// fact that started the run, and from there to that fact's own root. None —\n// a host's fact, or the first facts of a run nothing caused (a clock) — makes\n// this fact a root itself.\nconst rootOf = async (store: TideStore, cause: string | undefined): Promise<string | undefined> => {\n if (cause === undefined) return undefined;\n let runId: string | undefined;\n if (cause.startsWith('task:')) {\n const [task] = await store.query({ table: 'task', where: { id: cause.slice('task:'.length) }, limit: 1 });\n runId = task?.runId;\n } else if (cause.startsWith('run:')) {\n runId = cause.slice('run:'.length);\n }\n if (runId === undefined) return undefined;\n const [run] = await store.query({ table: 'run', where: { id: runId }, limit: 1 });\n const parentId = run?.factIds?.[0];\n if (parentId === undefined) return undefined;\n const [parent] = await store.query({ table: 'fact', where: { id: parentId }, limit: 1 });\n return parent === undefined ? undefined : (parent.root ?? parent.id);\n};\n\n// Every fact minted beneath a root is counted ON the root, atomically, and\n// one past `maxChainFacts` is stored PARKED — breadth's ceiling, as depth's is\n// in the matcher. A root swept from the ledger can no longer be counted; its\n// chain is long past the point this exists for.\nexport const admitFact = async (store: TideStore, fact: NewFact, maxChainFacts: number): Promise<Admission> => {\n const root = await rootOf(store, fact.cause);\n let parked: string | undefined;\n if (root !== undefined && (await store.cas('fact', root, {}, { descendants: { inc: 1 } }))) {\n const [counted] = await store.query({ table: 'fact', where: { id: root }, limit: 1 });\n const minted = counted?.descendants ?? 0;\n if (minted > maxChainFacts) parked = `chain from fact ${root} minted ${minted} facts, past maxChainFacts ${maxChainFacts}`;\n }\n const row = { ...fact, ...(root === undefined ? {} : { root }), ...(parked === undefined ? {} : { parked }) };\n const stored = await store.appendIfAbsent('fact', row);\n return stored === undefined ? { refused: fact } : { stored };\n};\n\nexport const announceFact = (emit: (event: TideEvent) => void, admission: Admission): void => {\n if ('stored' in admission) emit({ type: 'fact.ingested', fact: admission.stored });\n else emit({ type: 'fact.deduped', fact: admission.refused });\n};\n","import { FactInputSchema } from '../schemas';\nimport { TideError } from '../errors';\nimport type { AttemptOutcome, FactInput, NewFact, Task, TideCtx, TideStore } from '../types';\nimport { evaluateTemplate, withNow } from './runtime';\nimport { admitFact, announceFact } from './facts';\nimport type { Admission } from './facts';\nimport type { EngineDeps } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// Execute — the ONE door out of tide\n//\n// Everything that leaves — a write, an email, an agent — passes\n// through this function. That single choke point is what makes\n// preview a verb (stub one function and nothing can leak), the\n// timeout uniform, the task key uniformly available, and the\n// ledger complete. A second path outward would quietly break all\n// four.\n//\n// Retry classification is a CALLING CONVENTION, not metadata:\n// a handler that RETURNS is done (a card decline is a domain\n// outcome, recorded as data and branched on by other reflexes);\n// a handler that THROWS is transient and retried on bounded\n// backoff to a terminal, human-visible state. The decision sits\n// where the knowledge is — only the payment handler can tell a\n// decline from a gateway 500 — and nobody can forget to declare it.\n// ═══════════════════════════════════════════════════════════════\n\nexport type ExecuteReport = { executed: number; succeeded: number; failed: number; retrying: number; reclaimed: number };\n\nconst TIMEOUT = Symbol('tide.timeout');\n\nconst raceTimeout = async (work: Promise<unknown>, timeoutMs: number): Promise<unknown> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMEOUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMEOUT), timeoutMs);\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n};\n\nconst backoffFor = (attempt: number, base: number, kind: 'fixed' | 'exponential'): number =>\n kind === 'fixed' ? base : base * Math.pow(2, Math.max(0, attempt - 1));\n\n// ONE TOKEN PER CLAIM, not per task. The fence's job is to tell THIS claim\n// apart from an earlier one, and every task appears in at most one claim, so\n// a batch-wide token separates exactly the pairs that need separating.\n//\n// A counter rather than a clock or a random: tide reads no clock, and a\n// headless check that replays the same tick twice has to get the same\n// answers. The counter is the engine's (`deps.nextToken`), so two engines —\n// two processes — can mint the same token; the fence pairs it with the task's\n// attempt, which the store bumps on every claim (record, below).\n\n// CLAIMING IS ONE STEP, and it takes back lapsed leases in the same breath.\n//\n// A task still `claimed` past its lease is claimable again — that is the\n// whole recovery story for a process that died between the effect and the\n// record, and it needs no reaper, no heartbeat and no liveness table. The\n// fencing token is what makes it safe: the dead process's attempt, should it\n// somehow finish, finds its token superseded.\nconst claimTasks = async (deps: EngineDeps, now: number, limit: number, token: string): Promise<readonly Task[]> => {\n const serialReflexIds = deps\n .reflexes()\n .filter((loaded) => loaded.reflex.policy.order === 'serial')\n .map((loaded) => loaded.reflex.id);\n\n return deps.store.claim({\n table: 'task',\n where: {\n state: { in: ['pending', 'retrying', 'claimed'] },\n notBefore: { lte: now },\n // Either it was never claimed, or the claim has lapsed. Expressed as\n // one predicate because a second query would be a second decision.\n claimedUntil: { lte: now },\n },\n // `unit` is the tiebreaker, and it is not cosmetic. Every task of one\n // fan-out shares a `notBefore` and a `createdAt`, so with two keys the\n // order was whatever the storage engine felt like — insertion order in a\n // Map, heap order in Postgres. Two stores answering differently is the\n // thing the contract exists to prevent, and a headless check asserting on\n // the order effects ran in deserves the same answer everywhere.\n order: [{ by: 'notBefore' }, { by: 'createdAt' }, { by: 'unit' }],\n limit,\n set: { state: 'claimed', token, claimedUntil: now + deps.leaseMs, attempt: { inc: 1 } },\n // `order: 'serial'` — at most one live claim per reflex, counting what\n // another claim already holds. Inside the claim, because a caller that\n // looks first and claims second loses the race to its own second tick.\n onePer:\n serialReflexIds.length === 0\n ? undefined\n : { column: 'reflexId', held: { state: 'claimed', claimedUntil: { gt: now } }, only: serialReflexIds },\n });\n};\n\nexport const executeTasks = async (deps: EngineDeps, now: number, limit: number): Promise<ExecuteReport> => {\n const report: ExecuteReport = { executed: 0, succeeded: 0, failed: 0, retrying: 0, reclaimed: 0 };\n\n // Counted before the claim takes them back, because a claim returns the\n // row it wrote and the interesting fact is what the row USED to be. A\n // metric, so a race here costs a number rather than a guarantee.\n const lapsed = new Set(\n (\n await deps.store.query({\n table: 'task',\n where: { state: 'claimed', claimedUntil: { lte: now }, notBefore: { lte: now } },\n limit,\n })\n ).map((task) => task.id),\n );\n\n const token = deps.nextToken();\n const claimed = await claimTasks(deps, now, limit, token);\n\n for (const task of claimed) {\n if (lapsed.has(task.id)) {\n report.reclaimed += 1;\n deps.emit({ type: 'task.reclaimed', task });\n }\n\n const loaded = deps.find(task.reflexId);\n if (loaded === undefined) continue;\n\n const { reflex } = loaded;\n const registry = deps.effectsFor(reflex.as);\n const handler = registry[reflex.effect.name];\n const env = withNow(task.env, now);\n\n const buffered: NewFact[] = [];\n const ctx: TideCtx = {\n reflexId: reflex.id,\n runId: task.runId,\n taskId: task.id,\n taskKey: `${reflex.id}:${task.cause}:${task.unit}`,\n attempt: task.attempt,\n depth: task.depth,\n now,\n actor: deps.actorFor(reflex.as),\n // VALIDATED, and narrowed to two kinds.\n //\n // `emit` used to accept anything: a handler could emit `kind: 'manual'`\n // and fire a DISARMED reflex, because manual facts are checked before\n // enablement on purpose — arming gates triggers, not people. A handler\n // is not a person. `run` is tide's own bookkeeping and is minted by the\n // settler, so it is refused for the same reason.\n //\n // A malformed emit THROWS, inside the handler, so the attempt fails\n // visibly. The alternative is a fact that stores, matches nothing and\n // vanishes — a chain that silently stops one hop in.\n //\n // Depth is stamped from the task below — the handler never sets it,\n // because a handler that could choose its own depth could escape the\n // chain ceiling.\n emit: (fact: Omit<FactInput, 'cause'>) => {\n if (fact.kind !== 'write' && fact.kind !== 'signal')\n throw new TideError('invalid_fact', `${reflex.id}: an effect may emit \\`write\\` or \\`signal\\` facts, not \\`${fact.kind}\\``);\n const parsed = FactInputSchema.safeParse({ ...fact, cause: `task:${task.id}` });\n if (!parsed.success)\n throw new TideError('invalid_fact', `${reflex.id}: emitted fact did not parse: ${parsed.error.issues.map((i) => i.message).join('; ')}`, {\n issues: parsed.error.issues,\n });\n buffered.push({ ...parsed.data, depth: 0 });\n },\n };\n\n let outcome: AttemptOutcome = 'ok';\n let output: unknown;\n let error: string | undefined;\n let input: unknown;\n\n try {\n input = evaluateTemplate(deps.transform, reflex.effect.input, env);\n if (handler === undefined) throw new Error(`effect \"${reflex.effect.name}\" is not registered`);\n const result = await raceTimeout(Promise.resolve(handler.run(input, ctx)), reflex.policy.timeoutMs);\n if (result === TIMEOUT) {\n outcome = 'timeout';\n error = `timed out after ${reflex.policy.timeoutMs}ms`;\n } else {\n output = result;\n }\n } catch (thrown) {\n outcome = 'error';\n error = thrown instanceof Error ? thrown.message : String(thrown);\n }\n\n // From the TASK, not read back from the run. A run swept out from under a\n // long-running chain used to answer `undefined`, resetting the ceiling to\n // 0 — defeating the backstop in exactly the swept, long-running case it\n // exists for.\n // Depth AND identity are stamped here, by the engine, from the task and\n // the reflex — never by the handler. A handler that could choose either\n // could escape the chain ceiling or the tenant boundary.\n const emits = buffered.map((fact) => ({ ...fact, depth: task.depth + 1, as: reflex.as }));\n\n const retry = reflex.policy.retry;\n const maxAttempts = (retry?.max ?? 3) + 1;\n const next =\n outcome === 'ok'\n ? ({ state: 'done' } as const)\n : task.attempt >= maxAttempts\n ? ({ state: 'failed' } as const)\n : ({\n state: 'retrying',\n notBefore: now + backoffFor(task.attempt, retry?.baseMs ?? 60_000, retry?.backoff ?? 'exponential'),\n } as const);\n\n const recorded = await record(deps, task, token, {\n state: next.state,\n notBefore: next.state === 'retrying' ? next.notBefore : task.notBefore,\n output,\n error,\n // A throwing attempt discards its buffer: otherwise every retry of an\n // emit-then-throw handler would double-mint facts and fire the chain twice.\n emits: outcome === 'ok' ? emits : [],\n at: now,\n });\n\n // Rejected means the fence held — a timed-out attempt finishing late\n // found its token superseded. Its external side effect is exactly what\n // the task key handed to the provider defends against.\n if (recorded === undefined) continue;\n // Announced only now, after the transaction committed: an event is a\n // report of a row that exists, and a rollback would have taken these back.\n for (const admission of recorded) announceFact(deps.emit, admission);\n\n report.executed += 1;\n const [settled] = await deps.store.query({ table: 'task', where: { id: task.id }, limit: 1 });\n const reported = settled === undefined ? undefined : { ...settled, input };\n if (next.state === 'done') {\n report.succeeded += 1;\n if (reported !== undefined) deps.emit({ type: 'task.done', task: reported });\n } else if (next.state === 'failed') {\n report.failed += 1;\n if (reported !== undefined) deps.emit({ type: 'task.failed', task: reported });\n } else {\n report.retrying += 1;\n if (reported !== undefined) deps.emit({ type: 'task.retrying', task: reported, nextAt: next.notBefore });\n }\n }\n\n return report;\n};\n\ntype Settlement = {\n state: Task['state'];\n notBefore: number;\n output?: unknown;\n error?: string;\n emits: readonly NewFact[];\n at: number;\n};\n\n// The task's landing, the facts it emitted and its run's counters, in ONE\n// transaction. The store used to own this and therefore owned retry\n// semantics with it; it is engine policy, and it now reads as engine policy.\n//\n// Answers what became of each emitted fact, for the caller to announce once\n// the transaction has committed — or `undefined` when the fence refused the\n// attempt and nothing was written at all.\nconst record = async (deps: EngineDeps, task: Task, token: string, settlement: Settlement): Promise<readonly Admission[] | undefined> =>\n deps.store.transact(async (tx: TideStore) => {\n const settles = settlement.state === 'done' || settlement.state === 'failed';\n\n // THE FENCE. `expect` is the token AND the attempt this claim made, so an\n // attempt that timed out and finished late finds itself superseded and is\n // discarded rather than overwriting the live one. The attempt is what\n // makes it hold across engines: every claim bumps it in the store, so no\n // two claims of one task share it, while two engines' tokens can collide.\n const accepted = await tx.cas(\n 'task',\n task.id,\n { token, attempt: task.attempt },\n {\n state: settlement.state,\n token: undefined,\n claimedUntil: 0,\n output: settlement.output,\n error: settlement.error,\n notBefore: settlement.notBefore,\n settledAt: settles ? settlement.at : undefined,\n },\n );\n if (!accepted) return undefined;\n\n // Emits ride the SUCCESSFUL attempt's transaction. A throwing handler\n // discards its buffer, so a retry cannot double-mint a chain.\n const admissions: Admission[] = [];\n for (const emit of settlement.emits) admissions.push(await admitFact(tx, emit, deps.maxChainFacts));\n\n if (settles) {\n // COUNTED FIRST, READ SECOND. Reading the run and then writing the count\n // let two landings each read it before the other's count was in: both\n // found it short of its total, neither settled it, and the run stayed\n // `fanned` with every task done — no run fact, and an `overlap: 'skip'`\n // reflex that never started again. The increment is the store's own\n // arithmetic, so the read after it sees every count that has landed; in\n // SQL it also holds the row until this transaction ends.\n await tx.cas(\n 'run',\n task.runId,\n {},\n { done: { inc: settlement.state === 'done' ? 1 : 0 }, failed: { inc: settlement.state === 'failed' ? 1 : 0 } },\n );\n const [run] = await tx.query({ table: 'run', where: { id: task.runId }, limit: 1 });\n // Settled from `fanned` only, so two landings that both find the run\n // complete settle it once.\n if (run !== undefined && run.done + run.failed >= run.total && run.settledAt === undefined)\n await tx.cas('run', run.id, { state: 'fanned' }, { state: 'settled', settledAt: settlement.at });\n }\n return admissions;\n });\n\n// THE HUMAN RECOVERY VERB, and it must rewind the run.\n//\n// A failed task settled its run, and a claim only reaches tasks that are\n// pending, retrying or lapsed. Reopening the task alone left it claimable in\n// principle and unclaimed in practice — so `retry()`, the only documented\n// exit from `failed`, did nothing at all.\n//\n// The old objection was real: a digest already went out saying twelve failed,\n// and re-settling must not send it again. That is what `drained` answers. The\n// run rewinds; the announcement does not repeat.\n//\n// THE COUNT COMES DOWN WHATEVER STATE THE RUN IS IN. It used to come down only\n// as part of the rewind, which expects a `settled` run — so the second of two\n// retries (the first had already rewound it), or a retry pressed while the\n// run was still going, reopened its task and left `failed` one too high. A\n// run counting a failure it no longer had then reached its total one task\n// early: it settled, and announced itself, with work still out.\nexport const reopenTask = async (deps: EngineDeps, taskId: string, now: number): Promise<boolean> =>\n deps.store.transact(async (tx) => {\n const [task] = await tx.query({ table: 'task', where: { id: taskId }, limit: 1 });\n if (task === undefined || task.state !== 'failed') return false;\n\n const reopened = await tx.cas(\n 'task',\n taskId,\n { state: 'failed' },\n { state: 'pending', notBefore: now, error: undefined, settledAt: undefined, token: undefined, claimedUntil: 0 },\n );\n if (!reopened) return false;\n\n await tx.cas('run', task.runId, {}, { failed: { inc: -1 } });\n await tx.cas('run', task.runId, { state: 'settled' }, { state: 'fanned', settledAt: undefined });\n return true;\n });\n\n// A run settles when its last task does — and tide, being the bookkeeper of\n// its own fan-out, is the only thing that knows. Emitting that knowledge as\n// an ordinary fact is the entire fan-in mechanism: no barrier primitive, no\n// \"am I last?\" logic in a handler.\n//\n// Exactly-once through `drained`, a FLAG ON THE ROW rather than an in-memory\n// queue. A queue cannot survive a restart and cannot be rewound, which is\n// what made the recovery verb and fan-in mutually exclusive.\nexport const settleRuns = async (deps: EngineDeps, now: number): Promise<number> => {\n const settled = await deps.store.claim({\n table: 'run',\n where: { state: 'settled', drained: { ne: true } },\n order: [{ by: 'settledAt' }],\n limit: 200,\n set: { drained: true },\n });\n\n for (const run of settled) {\n deps.emit({ type: 'run.settled', run });\n const admission = await admitFact(deps.store, {\n kind: 'run',\n reflex: run.reflexId,\n runId: run.id,\n occurrence: run.occurrence,\n stats: { total: run.total, done: run.done, failed: run.failed },\n at: now,\n depth: run.depth + 1,\n cause: `run:${run.id}`,\n // A settlement is news about THIS reflex's work — counts of rows it\n // selected. Another tenant's digest has no business waking on it.\n as: run.as,\n }, deps.maxChainFacts);\n announceFact(deps.emit, admission);\n }\n\n return settled.length;\n};\n","import type { AdvanceReport } from '../types';\nimport type { EngineDeps } from './runtime';\nimport { materializeClocks } from './materialize';\nimport { matchFacts } from './match';\nimport { fanOut } from './fanout';\nimport { executeTasks, settleRuns } from './execute';\n\n// ═══════════════════════════════════════════════════════════════\n// Advance — one committed increment of the world\n//\n// Everything happens inside it; nothing happens outside it. Tide's\n// only notion of time is the `now` it is handed, which is what lets\n// a headless check time-travel and assert on rows with no sleeping,\n// and what lets the same engine run under any driver.\n//\n// This is the DRIVER'S verb, not a pacing model. Tide never decides\n// when to advance: a host's driver calls it on ingest (to\n// quiescence — a chain advances one hop per call, so the driver\n// loops until nothing moves), and `nextDue` tells that driver when\n// the next instant worth waking for is. The old world advanced one\n// hop per interval beat, which made every chain crawl at the\n// metronome's speed and made the beat a throughput ceiling.\n//\n// Two instances advancing concurrently are safe by construction:\n// materialization is idempotent on the occurrence key, window\n// closes and task claims are exactly-once through the store, and\n// a non-monotonic `now` (clock skew between hosts) merely delays\n// work — it cannot duplicate it.\n// ═══════════════════════════════════════════════════════════════\n\nexport type AdvanceOptions = { now: number; limit?: number };\n\nconst DEFAULT_LIMIT = 100;\n\nexport const runAdvance = async (deps: EngineDeps, options: AdvanceOptions): Promise<AdvanceReport> => {\n const { now } = options;\n const limit = options.limit ?? DEFAULT_LIMIT;\n\n const clocks = await materializeClocks(deps, now);\n const matched = await matchFacts(deps, now, limit);\n const tasksCreated = await fanOut(deps, now, limit);\n const executed = await executeTasks(deps, now, limit);\n // Settling AFTER execution in the same step means a chain advances one\n // hop per call — which is why the driver drains to quiescence.\n const runsSettled = await settleRuns(deps, now);\n\n return {\n now,\n materialized: clocks.materialized,\n skippedOccurrences: clocks.skippedOccurrences,\n factsMatched: matched.factsMatched,\n runsCreated: clocks.runsCreated + matched.runsCreated,\n tasksCreated,\n executed: executed.executed,\n succeeded: executed.succeeded,\n failed: executed.failed,\n retrying: executed.retrying,\n reclaimed: executed.reclaimed,\n runsSettled,\n parked: matched.parked,\n };\n};\n","import { clockOf } from '../schemas';\nimport { occurrencesBetween } from './occurrence';\nimport { stateOf } from './materialize';\nimport type { EngineDeps } from './runtime';\n\n// ═══════════════════════════════════════════════════════════════\n// nextDue — when is the next instant worth waking for?\n//\n// Tide still reads no clocks. It answers this question from its own\n// rows and hands the answer to the driver, which owns the timer: a\n// scheduler that sleeps until exactly this instant, preempted by any\n// ingest. That inversion is what replaced the interval beat — the\n// old world woke every minute to discover there was nothing to do,\n// and made every chain crawl at the metronome's speed.\n//\n// The invariant that keeps the driver honest: an instant returned\n// here is one where `advance` can MAKE PROGRESS. That is why a\n// fanned run's `dueAt` is NOT considered — its tasks are the live\n// thing (their backoff and leases are), and a fanned run waiting on\n// a retrying task would otherwise report a past instant forever, a\n// busy loop wearing a scheduler's clothes.\n// ═══════════════════════════════════════════════════════════════\n\n// Far enough that any real recurrence (daily, weekly, monthly, a yearly\n// anniversary) has an occurrence inside it; a clock with nothing due in a\n// year genuinely has nothing to say.\nconst CLOCK_HORIZON_MS = 370 * 24 * 60 * 60 * 1000;\n\nexport const nextDue = async (deps: EngineDeps, now: number): Promise<number | undefined> => {\n let due: number | undefined;\n const consider = (at: number | undefined): void => {\n if (at === undefined) return;\n if (due === undefined || at < due) due = at;\n };\n\n // Facts the matcher has not consumed: due at `notBefore ?? at`. Two\n // queries because the grammar has no coalesce — one min over the\n // immediate, one over the delayed.\n const [immediate] = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true }, notBefore: { isNull: true } },\n order: [{ by: 'at' }],\n limit: 1,\n });\n consider(immediate?.at);\n const [delayed] = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true }, notBefore: { isNull: false } },\n order: [{ by: 'notBefore' }],\n limit: 1,\n });\n consider(delayed?.notBefore);\n\n // Pending runs wait for fan-out at their own dueAt. (Fanned runs are\n // deliberately absent — see the header.)\n const [run] = await deps.store.query({ table: 'run', where: { state: 'pending' }, order: [{ by: 'dueAt' }], limit: 1 });\n consider(run?.dueAt);\n\n // Tasks: unclaimed work waits on its backoff; claimed work becomes\n // reclaimable when its lease lapses — the \"found behind the couch\" scan\n // is just this instant arriving.\n const [waiting] = await deps.store.query({\n table: 'task',\n where: { state: { in: ['pending', 'retrying'] } },\n order: [{ by: 'notBefore' }],\n limit: 1,\n });\n consider(waiting?.notBefore);\n const [claimed] = await deps.store.query({ table: 'task', where: { state: 'claimed' }, order: [{ by: 'claimedUntil' }], limit: 1 });\n consider(claimed?.claimedUntil);\n\n for (const loaded of deps.reflexes()) {\n const clock = clockOf(loaded.reflex.on);\n if (clock !== undefined) {\n const state = await stateOf(deps, loaded.reflex.id);\n // No baseline yet: one advance establishes it and mints nothing —\n // due now, so the driver performs that one advance.\n if (state?.materializedThrough === undefined) {\n consider(now);\n continue;\n }\n // A DISABLED clock is due too. Its occurrence materializes nothing,\n // but the advance moves the watermark — \"paused\" means the clock\n // keeps moving, and a driver that never woke for it would hand the\n // reflex its whole pause as a backlog on re-arm.\n consider(occurrencesBetween(clock, state.materializedThrough, state.materializedThrough + CLOCK_HORIZON_MS, 1)[0]?.at);\n }\n }\n\n return due;\n};\n","import { clockOf, isRecurring } from '../schemas';\nimport { TideError } from '../errors';\nimport type { Fact, FactInput, PreviewReport, PreviewUnit } from '../types';\nimport { evaluateTemplate, isTruthy, withNow } from './runtime';\nimport type { EngineDeps } from './runtime';\nimport { occurrencesBetween } from './occurrence';\nimport { unitsForRun } from './fanout';\n\n// ═══════════════════════════════════════════════════════════════\n// Preview — dry run as a verb, not a flag\n//\n// The real pipeline runs: the occurrence is computed, the\n// selection hits real data, every template is evaluated. Exactly\n// one function is stubbed — the effect executor — and because\n// that is the only door out of tide, there is no per-reflex\n// dry-run flag and no `if (dryRun)` for an author to forget. A\n// reflex CANNOT opt out of being previewable.\n//\n// Nothing here writes to the store. Preview is also where template\n// typos surface, which makes it the authoring loop's inner verb.\n// ═══════════════════════════════════════════════════════════════\n\nconst LOOKBACK_MS = 400 * 86_400_000;\nconst LOOKAHEAD_MS = 400 * 86_400_000;\n\nexport type PreviewOptions = { now: number; fact?: FactInput };\n\nexport const previewReflex = async (\n deps: EngineDeps,\n reflexId: string,\n options: PreviewOptions,\n): Promise<PreviewReport> => {\n const loaded = deps.find(reflexId);\n if (loaded === undefined) throw new TideError('unknown_reflex', `no reflex \"${reflexId}\" is loaded`);\n\n const { reflex, version } = loaded;\n const { now } = options;\n\n const clock = clockOf(reflex.on);\n const occurrence = clock === undefined ? undefined : nearestOccurrence(clock, now);\n\n const facts: Fact[] =\n options.fact === undefined ? [] : [{ ...options.fact, id: 'preview-fact', depth: 0 }];\n\n const cause =\n occurrence !== undefined\n ? `occurrence:${occurrence.key}`\n : facts.length > 0\n ? 'fact:preview-fact'\n : `manual:preview`;\n\n const report: PreviewReport = {\n reflexId,\n version,\n fired: true,\n effect: reflex.effect.name,\n cause,\n occurrence: occurrence?.key,\n selected: 0,\n units: [],\n };\n\n // `when` is part of the truth a preview owes its reader: a reflex that\n // would not have matched must say so rather than showing a hypothetical.\n if (reflex.when !== undefined && facts.length > 0) {\n try {\n const env = { params: reflex.params ?? {}, fact: { ...facts[0] }, now };\n // THE ENGINE'S OWN PREDICATE, imported rather than restated. Preview\n // used to reject only false/null/undefined while the matcher also\n // rejects 0, '' and []: a `when` returning an empty list previewed as\n // \"this will fire\" and then didn't — the exact class of surprise preview\n // exists to eliminate.\n if (!isTruthy(evaluateTemplate(deps.transform, reflex.when, env)))\n return { ...report, fired: false, reason: '`when` did not match this fact' };\n } catch (error) {\n return { ...report, fired: false, reason: `when: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n\n let units;\n try {\n units = await unitsForRun(\n deps,\n loaded,\n { cause, occurrence: occurrence?.key, dueAt: occurrence?.at ?? now },\n facts,\n now,\n );\n } catch (error) {\n return { ...report, fired: false, reason: error instanceof Error ? error.message : String(error) };\n }\n\n const registry = deps.effectsFor(reflex.as);\n const handler = registry[reflex.effect.name];\n const actor = deps.actorFor(reflex.as);\n\n const previewed: PreviewUnit[] = units.map((unit) => {\n try {\n const input = evaluateTemplate(deps.transform, reflex.effect.input, withNow(unit.env, now));\n const render = handler?.preview?.(input, { reflexId, unit: unit.unit, now, actor });\n return { unit: unit.unit, env: unit.env, input, render };\n } catch (error) {\n return { unit: unit.unit, env: unit.env, error: error instanceof Error ? error.message : String(error) };\n }\n });\n\n return { ...report, selected: units.length, units: previewed };\n};\n\n// The occurrence a preview should show: the most recent one, or — for a\n// reflex that has not come round yet — the next. Showing nothing because\n// the clock happens to be between beats would be the least useful answer.\nconst nearestOccurrence = (\n clock: NonNullable<ReturnType<typeof clockOf>>,\n now: number,\n): { key: string; at: number } | undefined => {\n const past = occurrencesBetween(clock, now - LOOKBACK_MS, now, 500);\n if (past.length > 0) return past[past.length - 1];\n const future = occurrencesBetween(clock, now, now + LOOKAHEAD_MS, 1);\n if (future.length > 0) return future[0];\n // A one-shot whose moment has passed outside the lookback still deserves\n // a key rather than an empty preview.\n return isRecurring(clock) ? undefined : { key: clock.at, at: now };\n};\n","import { FactInputSchema, ReflexSchema, factOf } from './schemas';\nimport type { Reflex, ReflexInput } from './schemas';\nimport { TideError } from './errors';\nimport type {\n AdvanceReport,\n EffectRegistry,\n Fact,\n FactInput,\n LoadReport,\n PreviewReport,\n Retention,\n Run,\n Task,\n TaskState,\n TideConfig,\n} from './types';\nimport { versionOf } from './engine/runtime';\nimport type { EngineDeps, LoadedReflex } from './engine/runtime';\nimport { buildGraph } from './engine/graph';\nimport type { GraphReport } from './engine/graph';\nimport { runAdvance } from './engine/advance';\nimport type { AdvanceOptions } from './engine/advance';\nimport { nextDue as computeNextDue } from './engine/due';\nimport { previewReflex } from './engine/preview';\nimport type { PreviewOptions } from './engine/preview';\nimport { reopenTask } from './engine/execute';\nimport { stateOf } from './engine/materialize';\nimport { admitFact, announceFact } from './engine/facts';\n\n// ═══════════════════════════════════════════════════════════════\n// createTide — the whole public surface\n//\n// Two edges (ingest in, advance to run — the driver's verb, paired\n// with `nextDue` so the driver knows when to wake), three human\n// verbs (fire, retry, preview), and a ledger anyone can read.\n// Everything else is a seam the host filled.\n//\n// THERE IS NO arm/disarm, and its absence is the design. Tide had\n// a pair, and they mutated an in-memory map: a second copy of a\n// fact the host already owned as a column, lost on restart, and\n// disagreeing with the host's own screen in between. Enablement is\n// a property of the reflex the host hands over. To pause one, write\n// your own row and load again — which is one source of truth, it\n// survives a restart, and it is auditable where a method call is not.\n// ═══════════════════════════════════════════════════════════════\n\nexport type Tide = {\n load: (reflexes: readonly ReflexInput[], options?: { at?: number }) => Promise<LoadReport>;\n reflexes: () => readonly Reflex[];\n graph: () => GraphReport;\n\n // `as` names the identity this fact belongs to, and it is how a host with\n // more than one tenant keeps them apart: a fact is only ever offered to\n // reflexes running under the SAME identity. Omit it and the fact reaches\n // only reflexes that name no identity either — which is every reflex in a\n // single-tenant host, and none in a multi-tenant one. `cause`/`depth` are\n // the bridge's chain thread — see the implementation's doctrine.\n ingest: (fact: FactInput, options?: { as?: string; cause?: string; depth?: number }) => Promise<Fact | undefined>;\n // One committed increment, given `now` — the DRIVER'S verb. A chain\n // advances one hop per call, so a driver drains to quiescence; a check\n // hands it a fake `now` and time-travels. Nothing outside a driver or a\n // check should be calling this.\n advance: (options: AdvanceOptions) => Promise<AdvanceReport>;\n // When the next instant worth waking for is — undefined means \"nothing\n // scheduled: sleep until an ingest\". The timer this feeds belongs to the\n // driver; tide still reads no clocks.\n nextDue: (now: number) => Promise<number | undefined>;\n\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n retry: (taskId: string, now: number) => Promise<boolean>;\n preview: (reflexId: string, options: PreviewOptions) => Promise<PreviewReport>;\n\n ledger: {\n runs: (filter?: { reflexId?: string; limit?: number }) => Promise<readonly Run[]>;\n run: (id: string) => Promise<Run | undefined>;\n tasks: (filter?: { runId?: string; reflexId?: string; state?: TaskState; limit?: number }) => Promise<readonly Task[]>;\n task: (id: string) => Promise<Task | undefined>;\n facts: (filter?: { reflexId?: string; limit?: number }) => Promise<readonly Fact[]>;\n fact: (id: string) => Promise<Fact | undefined>;\n // Walks `cause` upward: \"why did this member get this email\" is a walk\n // up rows, not an archaeology project.\n causeChain: (factId: string) => Promise<readonly Fact[]>;\n releaseParked: (factId: string) => Promise<boolean>;\n };\n\n sweep: (now: number, retention: Retention) => Promise<number>;\n};\n\nconst DEFAULT_MAX_CHAIN_DEPTH = 24;\nconst DEFAULT_MAX_CHAIN_FACTS = 10_000;\nconst DEFAULT_MAX_FAN_OUT = 10_000;\nconst DEFAULT_LEASE_MS = 300_000;\n\nexport const createTide = (config: TideConfig): Tide => {\n const loaded = new Map<string, LoadedReflex>();\n let effectsCache: EffectRegistry | undefined;\n\n const effectsFor = (as: string | undefined): EffectRegistry => {\n if (typeof config.effects === 'function') return config.effects(as);\n if (effectsCache === undefined) effectsCache = config.effects ?? {};\n return effectsCache;\n };\n\n let tokens = 0;\n const deps: EngineDeps = {\n store: config.store,\n transform: config.transform,\n select: config.select,\n effectsFor,\n actorFor: config.actor ?? ((as) => as),\n maxChainDepth: config.maxChainDepth ?? DEFAULT_MAX_CHAIN_DEPTH,\n maxChainFacts: config.maxChainFacts ?? DEFAULT_MAX_CHAIN_FACTS,\n maxFanOut: config.maxFanOut ?? DEFAULT_MAX_FAN_OUT,\n leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,\n emit: config.onEvent ?? (() => undefined),\n reflexes: () => [...loaded.values()],\n find: (id) => loaded.get(id),\n nextToken: () => {\n tokens += 1;\n return `tok_${tokens.toString(36)}`;\n },\n };\n\n // ── load ─────────────────────────────────────────────────────\n\n const load = async (input: readonly ReflexInput[], options?: { at?: number }): Promise<LoadReport> => {\n const parsed: Reflex[] = [];\n const seen = new Set<string>();\n\n for (const candidate of input) {\n const result = ReflexSchema.safeParse(candidate);\n if (!result.success)\n throw new TideError('invalid_reflex', `reflex did not parse: ${result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`, {\n issues: result.error.issues,\n });\n if (seen.has(result.data.id)) throw new TideError('duplicate_reflex', `duplicate reflex id \"${result.data.id}\"`);\n seen.add(result.data.id);\n parsed.push(result.data);\n }\n\n // Every opinion the load gate holds, in one pass: unregistered effects,\n // unguarded cycles, unknown run subscriptions. If it loads, it's\n // coherent — the moss tradition, one layer down.\n const graph = buildGraph(parsed, mergedEffects(parsed));\n // Every refusal is listed; the code is the first one's, so a caller\n // matching on it is told what the load actually tripped over.\n const refused = graph.refusals[0];\n if (refused !== undefined)\n throw new TideError(refused.code, `tide refused to load:\\n ${graph.errors.join('\\n ')}`, { errors: graph.errors, refusals: graph.refusals });\n\n const previously = new Set(loaded.keys());\n\n // Built ASIDE and swapped in one synchronous step. Clearing first and\n // filling across awaits left a window where a concurrent reader — a\n // screen re-reading right after the write that triggered the reload —\n // saw an empty or half-loaded engine and reported every reflex missing.\n const next = new Map<string, LoadedReflex>();\n for (const reflex of parsed) {\n const stored = await stateOf(deps, reflex.id);\n // Arming persists, so a restart does not re-open the past — and a host\n // that passes no `at` gets 0, which matches whatever is already stored.\n const armedAt = stored?.armedAt ?? options?.at ?? 0;\n if (stored === undefined) await config.store.appendIfAbsent('state', { reflexId: reflex.id, armedAt });\n\n // A REFLEX ENTERING THE SET RE-BASELINES ITS CLOCK.\n //\n // Without this, a reflex absent for eight days — deleted and restored,\n // or disabled by the host and left out of the load — comes back with an\n // eight-day-old watermark and materializes every occurrence it missed.\n // Coming back is not the same as never having left, and the difference\n // is eight days of real effects.\n if (!previously.has(reflex.id) && stored?.materializedThrough !== undefined && options?.at !== undefined)\n await config.store.cas('state', reflex.id, {}, { materializedThrough: Math.max(stored.materializedThrough, options.at) });\n\n next.set(reflex.id, { reflex, version: versionOf(reflex), armedAt });\n }\n loaded.clear();\n for (const [id, entry] of next) loaded.set(id, entry);\n\n return { loaded: parsed.length, cycles: graph.cycles, blind: graph.blind, warnings: graph.warnings };\n };\n\n const mergedEffects = (parsed: readonly Reflex[]): EffectRegistry => {\n if (typeof config.effects !== 'function') return config.effects ?? {};\n // A per-actor registry still has to be checkable at load, so the graph\n // sees the union of what every declared identity can reach.\n const union: EffectRegistry = {};\n for (const reflex of parsed) Object.assign(union, config.effects(reflex.as));\n return union;\n };\n\n // ── edges ────────────────────────────────────────────────────\n\n // IS THERE ANYBODY WHO COULD EVER WANT THIS? Only asked when a host has said\n // its ledger is not its audit log (`storeUnwatchedWrites: false`), and only\n // of write facts — a signal or a manual fact is somebody talking to tide on\n // purpose, and a run fact is tide talking to itself.\n //\n // Three deliberate weaknesses, each of them a bug this would otherwise have:\n // it never drops while nothing is loaded (a fact minted in that window still\n // waits, which is the rule matchFacts was fixed to keep); it ignores\n // `enabled`, so arming an automation does not depend on what was thrown away\n // while it was paused; and it ignores `as` and `armedAt`, which are delivery\n // rules rather than facts about whether anyone is listening at all.\n const watchable = (fact: FactInput): boolean => {\n if (config.storeUnwatchedWrites !== false) return true;\n if (fact.kind !== 'write') return true;\n if (loaded.size === 0) return true;\n for (const entry of loaded.values()) {\n const watched = factOf(entry.reflex.on);\n if (watched === undefined) continue;\n if (watched.entity === fact.entity && (watched.op === undefined || watched.op === fact.op)) return true;\n }\n return false;\n };\n\n const ingest = async (fact: FactInput, options?: { as?: string; cause?: string; depth?: number }): Promise<Fact | undefined> => {\n const result = FactInputSchema.safeParse(fact);\n if (!result.success)\n throw new TideError('invalid_fact', `fact did not parse: ${result.error.issues.map((i) => i.message).join('; ')}`, {\n issues: result.error.issues,\n });\n // WHOSE FACT THIS IS — and where it CAME FROM — declared by the host at\n // the door rather than inferred later. SECOND-ARGUMENT fields and not\n // fields on the fact, because the fact shape is what a webhook body\n // parses into: anything on it can be sent by whoever is talking to the\n // host, and an identity — or a provenance, or a chain depth — a caller\n // can choose is not one. These are the host's own word; a `cause` that\n // arrived inside the fact is discarded for the same reason.\n //\n // `cause`/`depth` exist for one producer: a bridge that mints a\n // handler's own writes back in as facts, and must carry the chain the\n // write belongs to or the depth ceiling resets at every trip through\n // the host's database.\n if (!watchable(result.data)) return undefined;\n const admission = await admitFact(config.store, { ...result.data, cause: options?.cause, depth: options?.depth ?? 0, as: options?.as }, deps.maxChainFacts);\n announceFact(deps.emit, admission);\n return 'stored' in admission ? admission.stored : undefined;\n };\n\n const advance = (options: AdvanceOptions): Promise<AdvanceReport> => runAdvance(deps, options);\n\n // ── human verbs ──────────────────────────────────────────────\n\n const fire = async (reflexId: string, options: { now: number; input?: unknown; by?: string }): Promise<Fact | undefined> => {\n if (!loaded.has(reflexId)) throw new TideError('unknown_reflex', `no reflex \"${reflexId}\" is loaded`);\n // Sugar over ingest: even the human verb enters through the one intake,\n // with `at` supplied by the caller like every fact. Tide reads no clock.\n return ingest(\n { kind: 'manual', target: reflexId, payload: options.input, by: options.by ?? 'operator', at: options.now },\n // Carried so the ledger reads consistently. Matching a manual fact does\n // not depend on it — `target` names one reflex, which is narrower.\n { as: loaded.get(reflexId)?.reflex.as },\n );\n };\n\n const preview = (reflexId: string, options: PreviewOptions): Promise<PreviewReport> => previewReflex(deps, reflexId, options);\n\n // ── ledger ───────────────────────────────────────────────────\n //\n // Ordinary queries, and that is the point. These used to be nine methods\n // on the store port that the ENGINE never called — a reporting surface\n // wedged into an execution contract. Under moss they are vex entries over\n // the same two tables; standalone they are these.\n\n const one = async <T extends 'run' | 'task' | 'fact'>(table: T, id: string) =>\n (await config.store.query({ table, where: { id } as never, limit: 1 }))[0];\n\n const causeChain = async (factId: string): Promise<readonly Fact[]> => {\n const chain: Fact[] = [];\n let current = await one('fact', factId);\n while (current !== undefined && chain.length < 64) {\n chain.push(current);\n const cause = current.cause;\n if (cause === undefined) break;\n const parentRunId = cause.startsWith('task:')\n ? (await one('task', cause.slice(5)))?.runId\n : cause.startsWith('run:')\n ? cause.slice(4)\n : undefined;\n if (parentRunId === undefined) break;\n const parentId = (await one('run', parentRunId))?.factIds?.[0];\n current = parentId === undefined ? undefined : await one('fact', parentId);\n }\n return chain;\n };\n\n // Newest first, so a `limit` means \"the most recent N\" everywhere. The two\n // stores used to answer opposite ends of the same list under the same\n // filter, which is the kind of divergence a contract test exists to catch.\n return {\n load,\n reflexes: () => [...loaded.values()].map((entry) => entry.reflex),\n graph: () => buildGraph([...loaded.values()].map((entry) => entry.reflex), mergedEffects([...loaded.values()].map((e) => e.reflex))),\n\n ingest,\n advance,\n nextDue: (now) => computeNextDue(deps, now),\n\n fire,\n retry: (taskId, now) => reopenTask(deps, taskId, now),\n preview,\n\n ledger: {\n runs: (filter) =>\n config.store.query({\n table: 'run',\n where: filter?.reflexId === undefined ? undefined : { reflexId: filter.reflexId },\n order: [{ by: 'createdAt', dir: 'desc' }],\n limit: filter?.limit,\n }),\n run: (id) => one('run', id),\n tasks: (filter) =>\n config.store.query({\n table: 'task',\n where: {\n ...(filter?.runId === undefined ? {} : { runId: filter.runId }),\n ...(filter?.reflexId === undefined ? {} : { reflexId: filter.reflexId }),\n ...(filter?.state === undefined ? {} : { state: filter.state }),\n },\n order: [{ by: 'createdAt', dir: 'desc' }],\n limit: filter?.limit,\n }),\n task: (id) => one('task', id),\n facts: async (filter) => {\n const found = await config.store.query({\n table: 'fact',\n order: [{ by: 'at', dir: 'desc' }],\n limit: filter?.reflexId === undefined ? filter?.limit : undefined,\n });\n const matched = filter?.reflexId === undefined ? found : found.filter((fact) => fact.reflex === filter.reflexId || fact.target === filter.reflexId);\n return filter?.limit === undefined ? matched : matched.slice(0, filter.limit);\n },\n fact: (id) => one('fact', id),\n causeChain,\n // Clears the park AND records that a human overrode the ceiling —\n // clearing the park alone is a ping-pong, because the depth that\n // parked it has not changed and never will.\n releaseParked: async (factId) => {\n const fact = await one('fact', factId);\n if (fact?.parked === undefined) return false;\n return config.store.cas('fact', factId, {}, { parked: undefined, released: true });\n },\n },\n\n // RETENTION, and the one place the ledger shrinks. Runs cascade to their\n // tasks in the store: a run and its members are one fact about the world,\n // and keeping half destroys the UNIQUE(runId, unit) row that IS the \"this\n // unit already ran\" record.\n sweep: async (now, retention) => {\n let removed = 0;\n if (retention.facts !== undefined)\n removed += await config.store.remove({ table: 'fact', where: { deliveredAt: { lt: now - retention.facts } } });\n if (retention.tasks !== undefined)\n removed += await config.store.remove({ table: 'task', where: { settledAt: { lt: now - retention.tasks } } });\n if (retention.runs !== undefined)\n removed += await config.store.remove({ table: 'run', where: { settledAt: { lt: now - retention.runs } } });\n return removed;\n },\n };\n};\n","import type { FactInput, Reflex, ReflexInput } from './schemas';\n\nexport type Row = Record<string, unknown>;\n\n// ═══════════════════════════════════════════════════════════════\n// The ledger — four tables, and only two of them grow with events\n//\n// There were seven: fact, delivery, firing, task, attempt, window,\n// watermark. Six of those were vocabulary. A design noun is not a\n// reason for a table; a GUARANTEE is, and each of these carries one:\n//\n// fact durable before anything interprets it, so `ingest` is one\n// write and matching is retryable in the advance\n// run UNIQUE(reflexId, cause) — THE idempotency, one constraint\n// for every trigger kind; atomic fan-out; fan-in counting\n// task UNIQUE(runId, unit) written BEFORE the effect; the lease;\n// the retry counter\n// state where each reflex has got to. One row per reflex, bounded\n// by how many reflexes exist rather than by what happened\n//\n// What went, and where it went:\n// delivery → the run's `cause`; a non-match is an event, not a row\n// attempt → `attempt` and `error` on the task; per-attempt history\n// is the host's log, and nothing read it here\n// window → deleted with coalesce, which nothing used\n// watermark → the clock through-line and the arming baseline are two\n// fields on `state`, not an unbounded key/value table with\n// a growing set of string keys\n// ═══════════════════════════════════════════════════════════════\n\nexport type Fact = FactInput & {\n id: string;\n // WHOSE FACT THIS IS — the `as` of the reflex that minted it, and absent on\n // anything the host ingested itself.\n //\n // Stamped by the engine, never by a handler, for the same reason `depth` is:\n // a handler that could choose its own identity could choose somebody else's.\n // Tide does not know what the string means. It only knows that a fact minted\n // under one identity must not wake a reflex running under another — which is\n // what stops a row selected for one tenant being handed to another tenant's\n // effect. See `reflexMatchesFact`.\n as?: string;\n // Distance from the root stimulus. An effect's emit inherits its\n // task's depth + 1, which is what lets a divergent loop hit a\n // ceiling instead of melting the ledger.\n depth: number;\n // A fact is done once it has been offered to every LOADED reflex —\n // matching is per (fact, reflex), and one fact can wake five.\n deliveredAt?: number;\n parked?: string;\n // A human looked at a parked fact and said \"run it anyway\". Without\n // this the release is a ping-pong: the matcher re-parks on the next\n // tick, because the depth that parked it has not changed and never\n // will. The override is recorded rather than faked by rewriting depth,\n // which would make the ledger lie about causality.\n released?: boolean;\n // THE CHAIN THIS FACT BELONGS TO — the id of the fact that started it,\n // absent on a root (a fact the host ingested, or the first facts of a run\n // nothing caused). Stamped at the door (engine/facts.ts), never by a handler.\n root?: string;\n // On a root only: how many facts its chain has minted beneath it. Depth\n // caps how LONG a chain runs; this caps how WIDE — a reflex that writes two\n // facts per fact it sees doubles each hop, and under a depth ceiling of 24\n // that is 2^24 runs before anything parks.\n descendants?: number;\n};\n\nexport type RunState = 'pending' | 'fanned' | 'settled' | 'skipped';\n\n// One execution of one reflex. Named `run` rather than `firing` because\n// `firing` was also a trigger kind and a fact kind — one word doing three\n// jobs, and the reason `fact: { firing: … }` read as a puzzle.\nexport type Run = {\n id: string;\n reflexId: string;\n version: string;\n // The host identity this ran under, copied from the reflex. Opaque to\n // tide and written down so the ledger is scopeable by an ordinary\n // host-side rule instead of by parsing reflex ids.\n as?: string;\n // 'occurrence:<key>' | 'fact:<id>' | 'run:<id>' | 'manual:<who>' —\n // provenance, and half of the task's idempotency key.\n cause: string;\n occurrence?: string;\n factIds?: readonly string[];\n state: RunState;\n depth: number;\n selected?: number;\n total: number;\n done: number;\n failed: number;\n dueAt: number;\n createdAt: number;\n settledAt?: number;\n // Whether this run's settlement has already been announced as a fact.\n // Separate from `settledAt` because a reopened task RE-settles its run\n // and must not mint a second fan-in fact: the digest watching it already\n // went out. The flag is what lets the recovery verb rewind safely.\n drained?: boolean;\n note?: string;\n};\n\n// How one attempt ended. There is no attempt TABLE — the count and the last\n// error live on the task, and per-attempt history is the host's log, which\n// is where it was already being read from. The distinction still matters to\n// the executor, so it still has a name.\nexport type AttemptOutcome = 'ok' | 'error' | 'timeout';\n\nexport type TaskState = 'pending' | 'claimed' | 'retrying' | 'done' | 'failed';\n\nexport type Task = {\n id: string;\n runId: string;\n reflexId: string;\n // The unit's grain: a row key in `each`, '' for batch and unit-less runs.\n unit: string;\n cause: string;\n // The pinned environment slice. Frozen at fan-out so a retry evaluates\n // against the same data the selection saw, never against moved data.\n env: Row;\n // Stamped from the run at fan-out, not read back from it at execution\n // time. A run swept out from under a long-running chain used to reset\n // the ceiling to 0 — defeating the backstop in exactly the long-running\n // case it exists for. The task carries what the task needs.\n depth: number;\n state: TaskState;\n attempt: number;\n token?: string;\n // THE LEASE, and expiry IS the reclaim. Without one, a process that died\n // between the effect and the record left the task `claimed` forever: its\n // run never settled, never drained, and an `overlap: 'skip'` reflex was\n // blocked for good. No reaper, no heartbeat — a claim whose lease has\n // lapsed is simply claimable again, which the fencing token makes safe.\n //\n // ZERO, not null, when unclaimed. \"Never claimed or lapsed\" is then one\n // comparison rather than a disjunction, which keeps the claim expressible\n // in a query grammar that has no OR — and a grammar with no OR is a\n // grammar every store can implement.\n claimedUntil: number;\n notBefore: number;\n input?: unknown;\n output?: unknown;\n error?: string;\n createdAt: number;\n settledAt?: number;\n};\n\n// Where a reflex has got to. ONE ROW PER REFLEX — bounded by how many\n// reflexes exist, never by how much has happened, which is what separates\n// it from the ledger proper and is why it survived the collapse.\nexport type ReflexState = {\n reflexId: string;\n // Matching starts here. A reflex never retro-fires: history from before\n // it existed is reachable by deliberate backfill, never by accident.\n armedAt: number;\n // The clock's through-line. Derivable from MAX(cause) over the runs, but\n // only while those runs exist — and retention is allowed to delete them.\n materializedThrough?: number;\n};\n\n// ═══════════════════════════════════════════════════════════════\n// The seams — five injection points\n// ═══════════════════════════════════════════════════════════════\n\n// What an effect handler and the select seam receive. `actor` is opaque:\n// tide never learns what a principal is (under moss it is an ActorContext,\n// charter-resolved and engine-enforced).\nexport type TideCtx = {\n reflexId: string;\n runId: string;\n taskId: string;\n // The downstream idempotency key. A payment capture passes this to the\n // provider, which is what makes a fenced-out zombie attempt harmless.\n taskKey: string;\n attempt: number;\n // How deep in a cause chain this task sits. A handler whose side effects\n // re-enter as facts (a write through the host's own DAL, minted back by\n // the bridge) forwards this with the write, so the chain ceiling survives\n // the trip through the database instead of resetting at every hop.\n depth: number;\n now: number;\n actor: unknown;\n // Continue a chain from inside a handler. Buffered — the fact commits\n // with a SUCCESSFUL attempt, so a retry cannot double-mint it — and\n // narrowed to `write` and `signal`, because a handler that could emit\n // `manual` would reach past the arming switch.\n emit: (fact: Omit<FactInput, 'cause'>) => void;\n};\n\nexport type EffectHandler = {\n run: (input: unknown, ctx: TideCtx) => Promise<unknown> | unknown;\n // What this effect writes. Feeds the flow graph and its cycle refusal —\n // an edge is a write meeting a watch. Under moss it is DERIVED from the\n // vex mutation behind the effect, never declared; a handler with no\n // `writes` is a BLIND edge the load report names.\n writes?: readonly string[];\n // Rendered by `preview` in place of running. Nothing else is needed to\n // make a reflex previewable — the executor is the only door out.\n preview?: (input: unknown, ctx: PreviewCtx) => unknown;\n};\n\nexport type PreviewCtx = { reflexId: string; unit: string; now: number; actor: unknown };\n\nexport type EffectRegistry = Record<string, EffectHandler>;\n\nexport type TransformFn = (config: unknown, source: Row) => unknown;\n\nexport type SelectFn = (query: unknown, ctx: SelectCtx) => AsyncIterable<Row> | Iterable<Row> | Promise<Iterable<Row>>;\n\nexport type SelectCtx = { reflexId: string; now: number; actor: unknown; env: Row };\n\nexport type ActorFn = (as: string | undefined) => unknown;\n\n// ═══════════════════════════════════════════════════════════════\n// Config and reports\n// ═══════════════════════════════════════════════════════════════\n\nexport type Retention = Partial<Record<'facts' | 'runs' | 'tasks', number>>;\n\nexport type TideConfig = {\n store: TideStore;\n transform: TransformFn;\n select?: SelectFn;\n effects?: EffectRegistry | ((as: string | undefined) => EffectRegistry);\n actor?: ActorFn;\n // A fact whose cause chain runs deeper than this is PARKED for review\n // rather than fired — the runtime backstop behind the load-time cycle\n // rules, and nearly free because causality is already recorded.\n maxChainDepth?: number;\n // A chain that has minted more facts than this beneath its root has the\n // rest PARKED — the breadth twin of maxChainDepth. Default 10,000.\n maxChainFacts?: number;\n // KEEP A WRITE FACT NOTHING WATCHES? Default true, which is what the ledger\n // means today: `ledger.facts()` is every write the host committed, and\n // `causeChain` walks it — an audit trail that answers \"why did this person\n // get this\" without anybody having predicted the question.\n //\n // A host that mints a fact per committed ROW pays for that trail on the hot\n // path of every write: an INSERT here, awaited, for a fact no loaded reflex\n // could ever match. A host whose ledger is not its audit log sets this false\n // and pays only for the writes something is actually listening to.\n //\n // NOT retroactive and not clever: it drops nothing while no reflexes are\n // loaded (a fact arriving in that window still waits, exactly as matchFacts\n // has always let it), and it ignores enablement, arming and identity — the\n // question it asks is only \"could any loaded reflex ever watch this entity\n // and op\", which is strictly weaker than the matcher.\n storeUnwatchedWrites?: boolean;\n // How many units one fan-out may mint before the run is refused.\n maxFanOut?: number;\n // How long a claim is good for. A task still `claimed` past this is\n // claimable again — the only recovery a died-mid-effect process needs.\n leaseMs?: number;\n onEvent?: (event: TideEvent) => void;\n};\n\nexport type TideEvent =\n | { type: 'run.created'; run: Run }\n | { type: 'run.settled'; run: Run }\n | { type: 'run.skipped'; reflexId: string; reason: string }\n // A fan-out that will be tried again next tick. Not a skip: a transient\n // selection failure must never consume an occurrence.\n | { type: 'run.deferred'; reflexId: string; runId: string; reason: string }\n | { type: 'task.done'; task: Task }\n | { type: 'task.failed'; task: Task }\n | { type: 'task.retrying'; task: Task; nextAt: number }\n // A lease lapsed and the work was taken back. Rare and worth seeing:\n // it means something died holding a task.\n | { type: 'task.reclaimed'; task: Task }\n | { type: 'fact.ingested'; fact: Fact }\n // A fact refused by its dedupeKey. Not a row — a provider retrying a\n // webhook forever would grow the table without bound, which is what the\n // key exists to stop — but not nothing either: without it, a repeat and\n // a chain that silently stopped read the same.\n | { type: 'fact.deduped'; fact: NewFact }\n | { type: 'fact.parked'; fact: Fact; reason: string }\n // The `when` said no, or threw. Not a row — one per (fact, reflex) pair\n // is a table that grows faster than the work does — but not nothing\n // either, because \"why didn't it fire\" deserves an answer.\n | { type: 'fact.unmatched'; fact: Fact; reflexId: string; reason: string };\n\nexport type AdvanceReport = {\n now: number;\n materialized: number;\n skippedOccurrences: number;\n factsMatched: number;\n runsCreated: number;\n tasksCreated: number;\n executed: number;\n succeeded: number;\n failed: number;\n retrying: number;\n reclaimed: number;\n runsSettled: number;\n parked: number;\n};\n\nexport type LoadReport = {\n loaded: number;\n // Guarded cycles are legal — a drip campaign IS a cycle. They are\n // reported so the author sees the loop they built.\n cycles: readonly { reflexIds: readonly string[]; guarded: boolean }[];\n blind: readonly { reflexId: string; effect: string }[];\n warnings: readonly string[];\n};\n\nexport type PreviewUnit = {\n unit: string;\n env: Row;\n input?: unknown;\n render?: unknown;\n error?: string;\n};\n\nexport type PreviewReport = {\n reflexId: string;\n version: string;\n fired: boolean;\n reason?: string;\n cause?: string;\n occurrence?: string;\n effect: string;\n selected: number;\n units: readonly PreviewUnit[];\n};\n\nexport type NewFact = FactInput & { depth: number; as?: string };\n\n// ═══════════════════════════════════════════════════════════════\n// The store contract — six capabilities, not twenty-seven nouns\n//\n// The old port had a method per noun per verb, so `claimTasks`,\n// `drainSettled` and `claimClosedWindows` were three implementations\n// of ONE operation and diverged three ways. Shaped by what the\n// guarantees need instead:\n//\n// transact several writes land together or not at all\n// appendIfAbsent a row exists once, decided by the table's unique\n// key rather than by a read the caller races\n// claim take work exactly once, under a fence\n// cas move a row only from the state you expected\n// query read\n// remove retention; the only thing that shrinks the ledger\n//\n// Structural and driver-free, the way vex's CacheBackend is. Nothing\n// here knows about retry, arming, coalescing or occurrences — the\n// engine holds every opinion, and the store holds none.\n// ═══════════════════════════════════════════════════════════════\n\nexport type TideTables = {\n fact: Fact;\n run: Run;\n task: Task;\n state: ReflexState;\n};\n\nexport type TableName = keyof TideTables;\n\n// The row identity `cas` and `remove` address a single row by.\nexport const PRIMARY_KEY: { [T in TableName]: keyof TideTables[T] & string } = {\n fact: 'id',\n run: 'id',\n task: 'id',\n state: 'reflexId',\n};\n\nexport type UniqueKey<T extends TableName> = {\n by: readonly (keyof TideTables[T] & string)[];\n // The constraint applies only when this column is present — in Postgres,\n // a partial unique index. A fact with no `dedupeKey` is not claiming to\n // be unique and is always appended.\n when?: keyof TideTables[T] & string;\n};\n\n// WHERE THE IDEMPOTENCY LIVES, written down once so every store agrees.\n// These four constraints are the engine's exactly-once promises; they are\n// not an optimisation and a store that omits one is not a tide store.\nexport const UNIQUE_BY: { [T in TableName]: UniqueKey<T> } = {\n // `entity` is part of the key. Without it two polls over different tables\n // that happened to agree on a cursor value silently ate each other's rows.\n fact: { by: ['kind', 'entity', 'name', 'dedupeKey'], when: 'dedupeKey' },\n run: { by: ['reflexId', 'cause'] },\n task: { by: ['runId', 'unit'] },\n state: { by: ['reflexId'] },\n};\n\nexport type Comparison<V> = {\n eq?: V;\n ne?: V;\n lt?: V;\n lte?: V;\n gt?: V;\n gte?: V;\n in?: readonly V[];\n notIn?: readonly V[];\n isNull?: boolean;\n};\n\nexport const COMPARISON_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'notIn', 'isNull'] as const;\n\nexport type Where<R> = { [K in keyof R]?: R[K] | Comparison<R[K]> };\n\nexport type Order<R> = readonly { by: keyof R & string; dir?: 'asc' | 'desc' }[];\n\nexport type QuerySpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n order?: Order<TideTables[T]>;\n limit?: number;\n};\n\n// A patch, plus the one thing a caller cannot compute without a read it\n// would then race: an increment. `attempt` has to rise AT CLAIM TIME, or a\n// handler that reliably kills the process retries forever.\nexport type Mutation<R> = { [K in keyof R]?: R[K] | { inc: number } };\n\nexport type ClaimSpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n order?: Order<TideTables[T]>;\n limit: number;\n // Applied to every claimed row, atomically with the selection.\n set: Mutation<TideTables[T]>;\n // `order: 'serial'`. At most one row per distinct value of `column` may\n // be held at once, counting rows some earlier claim is already holding —\n // so it lives INSIDE the claim rather than as a filter the caller applies\n // first and loses the race on.\n //\n // `only` names exactly the values this applies to, and it is REQUIRED\n // rather than defaulting to \"everything\": a store implementing \"all\n // groups\" has to enumerate the groups first, and an omitted list that\n // silently means \"all of them\" is the kind of default two implementations\n // read two ways. Everything outside it claims freely. Omit `onePer`\n // entirely when nothing is serial.\n onePer?: { column: keyof TideTables[T] & string; held: Where<TideTables[T]>; only: readonly string[] };\n};\n\nexport type RemoveSpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n};\n\nexport type TideStore = {\n // Several writes land together or not at all. The engine's two atomic\n // moments — fan-out committing with its run's transition, and an attempt\n // recording with the facts it emitted — are transactions, not conventions.\n transact: <T>(fn: (tx: TideStore) => Promise<T>) => Promise<T>;\n\n // Idempotent on the table's unique key. A duplicate materialization, a\n // replayed webhook, or a second instance's tick collides and gets\n // `undefined` — a refusal, not an error. `id` is minted by the store.\n appendIfAbsent: <T extends TableName>(\n table: T,\n row: Omit<TideTables[T], 'id'> & { id?: string },\n ) => Promise<TideTables[T] | undefined>;\n\n // Take rows exactly once. Selection and mutation are one step, which is\n // the whole promise: two instances ticking at the same moment contend\n // rather than duplicate.\n claim: <T extends TableName>(spec: ClaimSpec<T>) => Promise<readonly TideTables[T][]>;\n\n // Move a row only from the state you expected. The fence: a timed-out\n // attempt finishing late finds its token superseded and is discarded\n // rather than overwriting the live one.\n cas: <T extends TableName>(\n table: T,\n id: string,\n expect: Where<TideTables[T]>,\n set: Mutation<TideTables[T]>,\n ) => Promise<boolean>;\n\n query: <T extends TableName>(spec: QuerySpec<T>) => Promise<readonly TideTables[T][]>;\n\n // Retention, and the only thing that shrinks the ledger. Deleting a run\n // cascades to its tasks: the run and its members are one fact about the\n // world, and half of it is worse than neither.\n remove: <T extends TableName>(spec: RemoveSpec<T>) => Promise<number>;\n};\n\nexport type { Reflex, ReflexInput, FactInput };\n","import { COMPARISON_OPS, PRIMARY_KEY, UNIQUE_BY } from '../types';\nimport type {\n ClaimSpec,\n Comparison,\n Fact,\n Mutation,\n Order,\n QuerySpec,\n ReflexState,\n RemoveSpec,\n Row,\n Run,\n TableName,\n Task,\n TideStore,\n TideTables,\n Where,\n} from '../types';\n\n// ═══════════════════════════════════════════════════════════════\n// The memory store\n//\n// The reference implementation of TideStore, and the definition of\n// the contract: four tables, six operations, and no knowledge of\n// what a reflex, a retry or an occurrence is. It went from 414\n// lines to this by losing the twenty-seven nouns — `claimTasks`,\n// `drainSettled` and `claimClosedWindows` were three hand-written\n// implementations of one operation, and they diverged three ways.\n//\n// Its exactly-once promises are free in a single-threaded runtime,\n// which is exactly why every store must be held to the SAME contract\n// tests. A store that lies passes checks that then fail in\n// production — see `test/store.contract.ts`.\n// ═══════════════════════════════════════════════════════════════\n\nexport type MemoryStore = TideStore & {\n // Test/inspection affordance. Never part of TideStore — the engine must\n // not be able to reach around the contract.\n snapshot: () => { facts: readonly Fact[]; runs: readonly Run[]; tasks: readonly Task[]; state: readonly ReflexState[] };\n};\n\nconst ID_PREFIX: Record<TableName, string> = { fact: 'fact', run: 'run', task: 'task', state: 'st' };\n\nconst isComparison = (value: unknown): value is Comparison<unknown> => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key) => (COMPARISON_OPS as readonly string[]).includes(key));\n};\n\nconst compare = (left: unknown, right: unknown): number => {\n if (typeof left === 'number' && typeof right === 'number') return left - right;\n return String(left) < String(right) ? -1 : String(left) > String(right) ? 1 : 0;\n};\n\nconst satisfies = (value: unknown, test: unknown): boolean => {\n if (!isComparison(test)) return value === test;\n const check = test;\n if (check.eq !== undefined && value !== check.eq) return false;\n if (check.ne !== undefined && value === check.ne) return false;\n if (check.lt !== undefined && !(value !== undefined && compare(value, check.lt) < 0)) return false;\n if (check.lte !== undefined && !(value !== undefined && compare(value, check.lte) <= 0)) return false;\n if (check.gt !== undefined && !(value !== undefined && compare(value, check.gt) > 0)) return false;\n if (check.gte !== undefined && !(value !== undefined && compare(value, check.gte) >= 0)) return false;\n if (check.in !== undefined && !check.in.includes(value as never)) return false;\n if (check.notIn !== undefined && check.notIn.includes(value as never)) return false;\n if (check.isNull !== undefined && (value === undefined || value === null) !== check.isNull) return false;\n return true;\n};\n\nconst matches = (row: Row, where: Where<Row> | undefined): boolean => {\n if (where === undefined) return true;\n for (const [column, test] of Object.entries(where)) if (!satisfies(row[column], test)) return false;\n return true;\n};\n\nconst sorted = <R extends Row>(rows: readonly R[], order: Order<Row> | undefined): R[] => {\n if (order === undefined || order.length === 0) return [...rows];\n return [...rows].sort((left, right) => {\n for (const key of order) {\n const result = compare(left[key.by], right[key.by]) * (key.dir === 'desc' ? -1 : 1);\n if (result !== 0) return result;\n }\n return 0;\n });\n};\n\n// The one arithmetic escape. `attempt` has to rise at claim time, and a\n// caller that read it first would race its own increment.\nconst applied = <R extends Row>(row: R, set: Mutation<R>): R => {\n const next: Row = { ...row };\n for (const [column, value] of Object.entries(set)) {\n if (value !== null && typeof value === 'object' && 'inc' in value) {\n next[column] = Number(row[column] ?? 0) + Number((value as { inc: number }).inc);\n continue;\n }\n // `undefined` CLEARS. A settled task has no token and no lease, and\n // \"leave it as it was\" is never what the engine means by writing one.\n if (value === undefined) delete next[column];\n else next[column] = value;\n }\n return next as R;\n};\n\nexport const createMemoryStore = (): MemoryStore => {\n let tables: { [T in TableName]: Map<string, TideTables[T]> } = {\n fact: new Map(),\n run: new Map(),\n task: new Map(),\n state: new Map(),\n };\n\n let sequence = 0;\n\n const rowsOf = <T extends TableName>(table: T): TideTables[T][] => [...tables[table].values()];\n const keyOf = <T extends TableName>(table: T, row: TideTables[T]): string => String(row[PRIMARY_KEY[table]]);\n\n // ── the six ────────────────────────────────────────────────────\n\n const query = async <T extends TableName>(spec: QuerySpec<T>): Promise<readonly TideTables[T][]> => {\n const found = sorted(\n rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined)),\n spec.order as unknown as Order<Row> | undefined,\n ) as TideTables[T][];\n return spec.limit === undefined ? found : found.slice(0, spec.limit);\n };\n\n const appendIfAbsent = async <T extends TableName>(\n table: T,\n input: Omit<TideTables[T], 'id'> & { id?: string },\n ): Promise<TideTables[T] | undefined> => {\n const unique = UNIQUE_BY[table];\n const candidate = input as unknown as Row;\n\n // A row that does not carry the guard column is not claiming to be\n // unique — a fact with no `dedupeKey` is a distinct occurrence of\n // something, not a repeat of it.\n const guarded = unique.when === undefined || candidate[unique.when] !== undefined;\n if (guarded) {\n const collides = rowsOf(table).some((existing) =>\n unique.by.every((column) => (existing as unknown as Row)[column] === candidate[column]),\n );\n if (collides) return undefined;\n }\n\n sequence += 1;\n // A value that was never given is not a key on the row — what `undefined`\n // already means in a `cas` (see `applied`), and what a row read back from\n // a database is. A fact stored with `as: undefined` used to keep the key\n // here and lose it there, so a transform that looks at which keys a fact\n // has saw two different facts, and one that takes plain JSON refused this\n // one.\n const given: Row = Object.fromEntries(Object.entries(candidate).filter(([, value]) => value !== undefined));\n // An id is minted only where the primary key IS `id`. `state` is keyed by\n // the reflex it belongs to, and giving it a second identity would invent\n // a way for one reflex to have two states.\n const row = (PRIMARY_KEY[table] === 'id' ? { ...given, id: given.id ?? `${ID_PREFIX[table]}_${sequence}` } : given) as TideTables[T];\n tables[table].set(keyOf(table, row), row);\n return row;\n };\n\n const claim = async <T extends TableName>(spec: ClaimSpec<T>): Promise<readonly TideTables[T][]> => {\n const candidates = sorted(\n rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined)),\n spec.order as unknown as Order<Row> | undefined,\n ) as TideTables[T][];\n\n // Values whose one slot is already held. Counted HERE, inside the claim,\n // rather than by the caller beforehand — a caller that looks first and\n // claims second loses the race to its own second instance.\n const taken = new Set<string>();\n const restricted = new Set(spec.onePer?.only ?? []);\n if (spec.onePer !== undefined)\n for (const row of rowsOf(spec.table))\n if (matches(row as Row, spec.onePer.held as Where<Row>)) taken.add(String((row as Row)[spec.onePer.column]));\n\n const claimed: TideTables[T][] = [];\n for (const row of candidates) {\n if (claimed.length >= spec.limit) break;\n if (spec.onePer !== undefined) {\n const group = String((row as Row)[spec.onePer.column]);\n if (restricted.has(group)) {\n if (taken.has(group)) continue;\n taken.add(group);\n }\n }\n const next = applied(row as Row, spec.set as Mutation<Row>) as TideTables[T];\n tables[spec.table].set(keyOf(spec.table, next), next);\n claimed.push(next);\n }\n return claimed;\n };\n\n const cas = async <T extends TableName>(\n table: T,\n id: string,\n expect: Where<TideTables[T]>,\n set: Mutation<TideTables[T]>,\n ): Promise<boolean> => {\n const row = tables[table].get(id);\n if (row === undefined || !matches(row as Row, expect as Where<Row>)) return false;\n tables[table].set(id, applied(row as Row, set as Mutation<Row>) as TideTables[T]);\n return true;\n };\n\n const remove = async <T extends TableName>(spec: RemoveSpec<T>): Promise<number> => {\n const doomed = rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined));\n for (const row of doomed) {\n tables[spec.table].delete(keyOf(spec.table, row));\n // A run and its tasks are one fact about the world. Deleting the run\n // and keeping the tasks destroys the UNIQUE(runId, unit) entry that IS\n // the \"this unit already ran\" record — and a restore then re-charges\n // the invoice.\n if (spec.table === 'run')\n for (const task of rowsOf('task')) if (task.runId === (row as unknown as Run).id) tables.task.delete(task.id);\n }\n return doomed.length;\n };\n\n // Copy-on-enter, restore-on-throw. Trivial here and not a formality: the\n // contract test asserts a throwing transaction leaves nothing behind, and\n // a store that cannot promise that breaks fan-out's whole argument.\n const transact = async <T>(fn: (tx: TideStore) => Promise<T>): Promise<T> => {\n const saved = { fact: new Map(tables.fact), run: new Map(tables.run), task: new Map(tables.task), state: new Map(tables.state) };\n try {\n return await fn(store);\n } catch (error) {\n tables = saved;\n throw error;\n }\n };\n\n const store: MemoryStore = {\n transact,\n appendIfAbsent,\n claim,\n cas,\n query,\n remove,\n snapshot: () => ({ facts: rowsOf('fact'), runs: rowsOf('run'), tasks: rowsOf('task'), state: rowsOf('state') }),\n };\n\n return store;\n};\n","import type { Tide } from './tide';\nimport type { AdvanceReport, Fact, Retention } from './types';\n\nexport type TideDriver = {\n ingest: Tide['ingest'];\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n wake: () => Promise<void>;\n stop: () => Promise<void>;\n};\n\nexport type TideDriverConfig = {\n tide: Tide;\n now?: () => number;\n janitorMs?: number;\n // Absent on purpose: how long history matters is the host's call, so nothing is swept.\n retention?: Retention;\n};\n\nconst DEFAULT_JANITOR_MS = 300_000;\nconst MAX_STEPS_PER_DRAIN = 10_000;\n\n// Node does not refuse a delay over 2^31 - 1 ms (24.8 days): it warns and waits 1 ms, which\n// would turn a far-off wake into a loop. Every wait is cut to this; waking early costs one\n// advance that finds nothing, and the timer set after it waits out the rest.\nconst LONGEST_TIMER_MS = 2 ** 31 - 1;\nconst waitable = (ms: number): number => Math.min(ms, LONGEST_TIMER_MS);\n\n// Asked of the value and not of its type, so this file needs no runtime's types: Node's timers\n// have `unref`, and a timer anywhere else is a number that holds nothing open.\nconst letProcessEnd = (timer: unknown): void => {\n if (typeof timer !== 'object' || timer === null || !('unref' in timer)) return;\n const unref: unknown = timer.unref;\n if (typeof unref === 'function') Reflect.apply(unref, timer, []);\n};\n\nconst progressOf = (report: AdvanceReport): number =>\n report.materialized +\n report.skippedOccurrences +\n report.factsMatched +\n report.runsCreated +\n report.tasksCreated +\n report.executed +\n report.reclaimed +\n report.runsSettled +\n report.parked;\n\nexport const createTideDriver = (config: TideDriverConfig): TideDriver => {\n const { tide } = config;\n const now = config.now ?? (() => Date.now());\n const janitorMs = waitable(config.janitorMs ?? DEFAULT_JANITOR_MS);\n\n let running = false;\n let queued = false;\n let stopped = false;\n let cycle: Promise<void> | undefined;\n let scheduling: Promise<void> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const drain = async (): Promise<void> => {\n for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {\n const report = await tide.advance({ now: now() });\n if (progressOf(report) === 0) return;\n }\n console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps — stopping this pass; the janitor will resume it`);\n };\n\n // Never rejects: it runs detached, and an unhandled rejection would take the host's process down.\n const schedule = async (): Promise<void> => {\n if (stopped) return;\n let due: number | undefined;\n try {\n due = await tide.nextDue(now());\n } catch (err) {\n if (!stopped) console.error('[tide:driver] next due', err);\n return;\n }\n if (stopped) return;\n if (timer !== undefined) clearTimeout(timer);\n if (due === undefined) return;\n const delay = due - now();\n // Quiescent yet still due now means advance cannot progress it (facts waiting for reflexes\n // to load, say): retry on the janitor's beat, not in a hot loop.\n timer = setTimeout(() => void wake(), delay > 0 ? waitable(delay) : janitorMs);\n letProcessEnd(timer);\n };\n\n // A wake during a drain queues one more pass inside the same cycle, and every waker gets the\n // same cycle promise: awaiting it means quiescence including whatever landed while draining.\n const wake = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n queued = true;\n if (running) return cycle ?? Promise.resolve();\n running = true;\n cycle = (async () => {\n try {\n while (queued) {\n queued = false;\n await drain();\n }\n } catch (err) {\n console.error('[tide:driver]', err);\n } finally {\n running = false;\n cycle = undefined;\n scheduling = schedule();\n }\n })();\n return cycle;\n };\n\n const janitor = setInterval(() => {\n if (config.retention !== undefined) {\n void tide.sweep(now(), config.retention).catch((err) => console.error('[tide:driver] sweep', err));\n }\n void wake();\n }, janitorMs);\n letProcessEnd(janitor);\n\n return {\n ingest: async (fact, options) => {\n const stored = await tide.ingest(fact, options);\n if (stored !== undefined) void wake();\n return stored;\n },\n fire: async (reflexId, options) => {\n const fact = await tide.fire(reflexId, options);\n void wake();\n return fact;\n },\n wake,\n stop: async () => {\n stopped = true;\n clearInterval(janitor);\n if (timer !== undefined) clearTimeout(timer);\n await cycle;\n await scheduling;\n },\n };\n};\n","import { ReflexSchema } from '../schemas';\nimport type { Reflex, ReflexDraft, Timer } from '../schemas';\nimport { zonedParts } from './occurrence';\n\n// ═══════════════════════════════════════════════════════════════\n// Anchoring — a draft becomes a reflex when somebody saves it.\n//\n// A timer means \"this long from now\", and now is the moment of saving:\n// time spent reading the draft is not taken off it. The timer is fixed to\n// a one-shot clock at that instant plus its length, to the second, in the\n// host's timezone — so what is stored names an instant, and a restart\n// re-loads the same one. Any other trigger passes through unchanged.\n// ═══════════════════════════════════════════════════════════════\n\nexport const timerMs = (timer: Timer): number => (((timer.hours ?? 0) * 60 + (timer.minutes ?? 0)) * 60 + (timer.seconds ?? 0)) * 1000;\n\nconst pad2 = (value: number): string => String(value).padStart(2, '0');\n\nconst localDateTime = (instant: number, tz: string): string => {\n const p = zonedParts(instant, tz);\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}T${pad2(p.hour)}:${pad2(p.minute)}:${pad2(p.second)}`;\n};\n\nexport const anchorDraft = (draft: ReflexDraft, anchor: { at: number; tz: string }): Reflex => {\n if (!('timer' in draft.on)) return ReflexSchema.parse(draft);\n // A clock names whole seconds, so the instant is rounded — UP: a timer may\n // run a fraction of a second long, never short.\n const fires = Math.ceil((anchor.at + timerMs(draft.on.timer)) / 1000) * 1000;\n return ReflexSchema.parse({ ...draft, on: { clock: { at: localDateTime(fires, anchor.tz), tz: anchor.tz } } });\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/fact.schema.ts","../src/schemas/reflex.schema.ts","../src/errors.ts","../src/engine/runtime.ts","../src/engine/graph.ts","../src/engine/occurrence.ts","../src/engine/match.ts","../src/engine/materialize.ts","../src/engine/fanout.ts","../src/engine/facts.ts","../src/engine/execute.ts","../src/engine/advance.ts","../src/engine/due.ts","../src/engine/preview.ts","../src/tide.ts","../src/types.ts","../src/store/memory.ts","../src/driver.ts","../src/engine/anchor.ts"],"names":["z","require","time","pad2"],"mappings":";;;;;AAEO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AACb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkBA,MAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC;AAE/D,IAAM,oBAAA,GAAuBA,MACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,IAAIA,KAAA,CACD,KAAA,CAAM,CAACA,KAAA,CAAE,QAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,GAAA,CAAI,EAAE,CAAA,EAAGA,KAAA,CAAE,KAAK,QAAQ,CAAA,EAAGA,KAAA,CAAE,KAAA,CAAMA,MAAE,IAAA,CAAK,QAAQ,CAAC,CAAA,CAAE,IAAI,CAAC,CAAA,EAAGA,KAAA,CAAE,MAAA,GAAS,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACnH,UAAS,CACT,QAAA;AAAA,IACC;AAAA,GACF;AAAA,EACF,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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CAAA,EAAG,CAAA,CAAE,IAAI,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,KAAK,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,GAAG,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,IAAI,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,MAAM,CAAC,CAAA,CAAA,EAAIA,KAAAA,CAAK,CAAA,CAAE,MAAM,CAAC,CAAA,CAAA;AACtG,CAAA;AAEO,IAAM,WAAA,GAAc,CAAC,KAAA,EAAoB,MAAA,KAA+C;AAC7F,EAAA,IAAI,EAAE,OAAA,IAAW,KAAA,CAAM,KAAK,OAAO,YAAA,CAAa,MAAM,KAAK,CAAA;AAG3D,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,IAAA,CAAA,CAAM,MAAA,CAAO,EAAA,GAAK,OAAA,CAAQ,KAAA,CAAM,EAAA,CAAG,KAAK,CAAA,IAAK,GAAI,CAAA,GAAI,GAAA;AACxE,EAAA,OAAO,YAAA,CAAa,MAAM,EAAE,GAAG,OAAO,EAAA,EAAI,EAAE,OAAO,EAAE,EAAA,EAAI,cAAc,KAAA,EAAO,MAAA,CAAO,EAAE,CAAA,EAAG,EAAA,EAAI,OAAO,EAAA,EAAG,IAAK,CAAA;AAC/G","file":"index.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.array(z.enum(WEEKDAYS)).min(1), z.string().regex(MMDD)])\n .optional()\n .describe(\n 'week → a weekday, or a list of them: [\"mon\",\"tue\",\"wed\",\"thu\",\"fri\"] is every weekday; month → 1..31, where 31 is the last day of every month (a shorter month clamps to its end); year → \"MM-DD\". Omitted for day.',\n ),\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 const weekday = (value: unknown): boolean => typeof value === 'string' && WEEKDAYS.some((d) => d === value);\n const weekdays = Array.isArray(clock.on) && clock.on.length > 0 && new Set(clock.on).size === clock.on.length;\n if (clock.every === 'week' && !weekday(clock.on) && !weekdays) fail('a weekly clock needs `on` as a weekday (mon..sun), or a list of different weekdays');\n if (clock.every !== 'week' && Array.isArray(clock.on)) fail('only a weekly clock takes a list of weekdays');\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 { OpSchema } from './trigger.schema';\n\nexport const FactKindSchema = z.enum(['write', 'signal', 'manual', 'run']);\n\nexport const FactInputSchema = z\n .object({\n kind: FactKindSchema,\n\n entity: z.string().optional().describe('Which table or entity was written.'),\n op: OpSchema.optional().describe('Ops are distinct stimuli — \"only on create\" is op: \"insert\".'),\n row: z.record(z.string(), z.unknown()).optional().describe('The row, as the write returned it.'),\n\n name: z.string().optional().describe('Which named intake this arrived on.'),\n payload: z.unknown().optional().describe('The event body — validated at the HOST boundary before it gets here.'),\n\n reflex: z.string().optional(),\n runId: z.string().optional(),\n occurrence: z.string().optional().describe('The calendar key, when the clock was the cause.'),\n stats: z\n .object({ total: z.number().int(), done: z.number().int(), failed: z.number().int() })\n .strict()\n .optional(),\n\n target: z.string().optional().describe('The one reflex a manual fact is aimed at.'),\n by: z.string().optional().describe('Who fired it — recorded on the firing as manual:<who>.'),\n\n at: z.number().int().describe('Supplied by the caller. Tide reads no clocks.'),\n notBefore: z.number().int().optional().describe('A delayed fact — timers as data, visible and queryable.'),\n dedupeKey: z.string().optional().describe('Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error.'),\n cause: z.string().optional().describe('Set by tide when an effect emits — the causality chain.'),\n })\n .strict()\n .superRefine((fact, ctx) => {\n const require = (field: keyof typeof fact, why: string) => {\n if (fact[field] === undefined)\n ctx.addIssue({ code: 'custom', message: `a ${fact.kind} fact needs \\`${String(field)}\\` — ${why}`, path: [field] });\n };\n const refuse = (field: keyof typeof fact) => {\n if (fact[field] !== undefined)\n ctx.addIssue({ code: 'custom', message: `\\`${String(field)}\\` is not part of a ${fact.kind} fact`, path: [field] });\n };\n\n if (fact.kind === 'write') {\n require('entity', 'it is what a write trigger matches on');\n refuse('name');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'signal') {\n require('name', 'it is which named intake this arrived on');\n refuse('entity');\n refuse('op');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'manual') {\n require('target', 'a manual fact is aimed at exactly one reflex');\n refuse('entity');\n refuse('name');\n refuse('runId');\n }\n if (fact.kind === 'run') {\n require('reflex', 'it is whose run settled');\n require('runId', 'it is which run settled');\n refuse('entity');\n refuse('name');\n refuse('target');\n }\n });\n\nexport type FactInput = z.infer<typeof FactInputSchema>;\nexport type FactKind = z.infer<typeof FactKindSchema>;\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\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 you make up from the request, like \"call-mum\". Never ask the person for it.'),\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","export type TideErrorCode =\n | 'invalid_reflex'\n | 'invalid_fact'\n | 'duplicate_reflex'\n | 'unknown_reflex'\n | 'unknown_effect'\n | 'unguarded_cycle'\n | 'duplicate_unit'\n | 'no_transform'\n | 'store';\n\nexport class TideError extends Error {\n readonly code: TideErrorCode;\n readonly details?: unknown;\n\n constructor(code: TideErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = 'TideError';\n this.code = code;\n this.details = details;\n }\n}\n\nexport const isTideError = (value: unknown): value is TideError => value instanceof TideError;\n","import type { Reflex } from '../schemas';\nimport type { EffectRegistry, Row, SelectFn, TideEvent, TideStore, TransformFn } from '../types';\n\nexport type LoadedReflex = {\n reflex: Reflex;\n version: string;\n armedAt: number;\n};\n\nexport type EngineDeps = {\n store: TideStore;\n transform: TransformFn;\n select?: SelectFn;\n effectsFor: (as: string | undefined) => EffectRegistry;\n actorFor: (as: string | undefined) => unknown;\n maxChainDepth: number;\n maxChainFacts: number;\n maxFanOut: number;\n leaseMs: number;\n emit: (event: TideEvent) => void;\n reflexes: () => readonly LoadedReflex[];\n find: (id: string) => LoadedReflex | undefined;\n nextToken: () => string;\n};\n\nexport type EnvParts = {\n params?: Row;\n occurrence?: { key: string; at: number; tz?: string };\n fact?: Row;\n facts?: readonly Row[];\n row?: Row;\n rows?: readonly Row[];\n now: number;\n};\n\nexport const buildEnv = (parts: EnvParts): Row => {\n const env: Row = { params: parts.params ?? {}, now: parts.now };\n if (parts.occurrence !== undefined) env.occurrence = parts.occurrence;\n if (parts.fact !== undefined) env.fact = parts.fact;\n if (parts.facts !== undefined) env.facts = parts.facts;\n if (parts.row !== undefined) env.row = parts.row;\n if (parts.rows !== undefined) env.rows = parts.rows;\n return env;\n};\n\nexport const withNow = (env: Row, now: number): Row => ({ ...env, now });\n\nexport const evaluateTemplate = (transform: TransformFn, config: unknown, env: Row): unknown =>\n config === undefined ? undefined : transform(config, env);\n\nexport const isTruthy = (value: unknown): boolean => {\n if (value === undefined || value === null || value === false) return false;\n if (value === 0 || value === '') return false;\n if (Array.isArray(value)) return value.length > 0;\n return true;\n};\n\nconst canonical = (value: unknown): string => {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'null';\n if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`;\n const entries = Object.entries(value)\n .filter(([, entryValue]) => entryValue !== undefined)\n .sort(([left], [right]) => (left < right ? -1 : 1));\n return `{${entries.map(([key, entryValue]) => `${JSON.stringify(key)}:${canonical(entryValue)}`).join(',')}}`;\n};\n\nexport const versionOf = (reflex: Reflex): string => {\n const { enabled: _enabled, ...definition } = reflex;\n const text = canonical(definition);\n let hashA = 0x811c9dc5;\n let hashB = 0x01000193;\n for (let index = 0; index < text.length; index += 1) {\n const code = text.charCodeAt(index);\n hashA = Math.imul(hashA ^ code, 0x01000193) >>> 0;\n hashB = Math.imul(hashB ^ ((code << 3) | index % 7), 0x85ebca6b) >>> 0;\n }\n return `v_${hashA.toString(16).padStart(8, '0')}${hashB.toString(16).padStart(8, '0')}`;\n};\n","import { factOf } from '../schemas';\nimport type { Reflex } from '../schemas';\nimport type { EffectRegistry } from '../types';\n\nexport type Edge = { from: string; to: string; via: string };\n\nexport type GraphReport = {\n edges: readonly Edge[];\n cycles: readonly { reflexIds: readonly string[]; guarded: boolean }[];\n blind: readonly { reflexId: string; effect: string }[];\n errors: readonly string[];\n refusals: readonly { code: 'unknown_reflex' | 'unknown_effect' | 'unguarded_cycle'; message: string }[];\n warnings: readonly string[];\n};\n\nconst isGuarded = (reflex: Reflex): boolean => reflex.select !== undefined || reflex.when !== undefined;\n\nexport const buildGraph = (reflexes: readonly Reflex[], effects: EffectRegistry): GraphReport => {\n const edges: Edge[] = [];\n const refusals: { code: 'unknown_reflex' | 'unknown_effect' | 'unguarded_cycle'; message: string }[] = [];\n const warnings: string[] = [];\n const blind: { reflexId: string; effect: string }[] = [];\n\n const byId = new Map(reflexes.map((reflex) => [reflex.id, reflex]));\n\n const watchers = new Map<string, string[]>();\n const runWatchers = new Map<string, string[]>();\n for (const reflex of reflexes) {\n const fact = factOf(reflex.on);\n if (fact?.entity !== undefined) {\n const existing = watchers.get(fact.entity) ?? [];\n watchers.set(fact.entity, [...existing, reflex.id]);\n }\n if (fact?.run !== undefined) {\n const existing = runWatchers.get(fact.run) ?? [];\n runWatchers.set(fact.run, [...existing, reflex.id]);\n if (fact.run === reflex.id) warnings.push(`${reflex.id} subscribes to its own run — a drain loop; make sure it narrows`);\n if (!byId.has(fact.run)) refusals.push({ code: 'unknown_reflex', message: `${reflex.id} watches the run of unknown reflex \"${fact.run}\"` });\n }\n }\n\n for (const reflex of reflexes) {\n const handler = effects[reflex.effect.name];\n if (handler === undefined) {\n refusals.push({ code: 'unknown_effect', message: `${reflex.id} names effect \"${reflex.effect.name}\", which is not registered` });\n continue;\n }\n if (handler.writes === undefined) {\n blind.push({ reflexId: reflex.id, effect: reflex.effect.name });\n continue;\n }\n for (const entity of handler.writes)\n for (const target of watchers.get(entity) ?? []) edges.push({ from: reflex.id, to: target, via: entity });\n }\n\n for (const [source, targets] of runWatchers)\n for (const target of targets) if (byId.has(source)) edges.push({ from: source, to: target, via: `run:${source}` });\n\n const cycles = findCycles(reflexes, edges).map((reflexIds) => ({\n reflexIds,\n guarded: reflexIds.some((id) => {\n const reflex = byId.get(id);\n return reflex !== undefined && isGuarded(reflex);\n }),\n }));\n\n for (const cycle of cycles)\n if (!cycle.guarded)\n refusals.push({\n code: 'unguarded_cycle',\n message: `unguarded cycle: ${cycle.reflexIds.join(' → ')} → ${cycle.reflexIds[0]} — no selection and no \\`when\\` anywhere on the loop, so it diverges by construction`,\n });\n\n return { edges, cycles, blind, errors: refusals.map((refusal) => refusal.message), refusals, warnings };\n};\n\nconst findCycles = (reflexes: readonly Reflex[], edges: readonly Edge[]): string[][] => {\n const adjacency = new Map<string, string[]>();\n for (const reflex of reflexes) adjacency.set(reflex.id, []);\n for (const edge of edges) {\n const existing = adjacency.get(edge.from);\n if (existing !== undefined) existing.push(edge.to);\n }\n\n const index = new Map<string, number>();\n const low = new Map<string, number>();\n const onStack = new Set<string>();\n const stack: string[] = [];\n const components: string[][] = [];\n let counter = 0;\n\n const strongConnect = (node: string): void => {\n index.set(node, counter);\n low.set(node, counter);\n counter += 1;\n stack.push(node);\n onStack.add(node);\n\n for (const next of adjacency.get(node) ?? []) {\n const nextIndex = index.get(next);\n if (nextIndex === undefined) {\n strongConnect(next);\n const nextLow = low.get(next);\n const nodeLow = low.get(node);\n if (nextLow !== undefined && nodeLow !== undefined) low.set(node, Math.min(nodeLow, nextLow));\n } else if (onStack.has(next)) {\n const nodeLow = low.get(node);\n if (nodeLow !== undefined) low.set(node, Math.min(nodeLow, nextIndex));\n }\n }\n\n if (low.get(node) === index.get(node)) {\n const component: string[] = [];\n let popped = stack.pop();\n while (popped !== undefined) {\n onStack.delete(popped);\n component.push(popped);\n if (popped === node) break;\n popped = stack.pop();\n }\n components.push(component.reverse());\n }\n };\n\n for (const reflex of reflexes) if (!index.has(reflex.id)) strongConnect(reflex.id);\n\n const selfLooping = new Set(edges.filter((edge) => edge.from === edge.to).map((edge) => edge.from));\n return components.filter((component) => {\n if (component.length > 1) return true;\n const only = component[0];\n return only !== undefined && selfLooping.has(only);\n });\n};\n","import { WEEKDAYS, isRecurring } from '../schemas';\nimport type { Clock, ClockRecurring } from '../schemas';\n\nexport type LocalParts = { year: number; month: number; day: number; hour: number; minute: number; second: number };\nexport type LocalDay = { year: number; month: number; day: number };\nexport type Occurrence = { key: string; at: number };\n\nconst HALF_DAY_MS = 43_200_000;\nconst DAY_MS = 86_400_000;\nconst MAX_DAYS_SCANNED = 3_700;\n\nconst FORMATTERS = new Map<string, Intl.DateTimeFormat>();\n\nconst formatterFor = (tz: string): Intl.DateTimeFormat => {\n const cached = FORMATTERS.get(tz);\n if (cached !== undefined) return cached;\n const built = new Intl.DateTimeFormat('en-US', {\n timeZone: tz,\n hourCycle: 'h23',\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n });\n FORMATTERS.set(tz, built);\n return built;\n};\n\nexport const zonedParts = (instant: number, tz: string): LocalParts => {\n const parts = formatterFor(tz).formatToParts(new Date(instant));\n const read = (type: Intl.DateTimeFormatPartTypes): number => {\n const found = parts.find((part) => part.type === type);\n return found === undefined ? 0 : Number(found.value);\n };\n return {\n year: read('year'),\n month: read('month'),\n day: read('day'),\n hour: read('hour'),\n minute: read('minute'),\n second: read('second'),\n };\n};\n\nconst offsetAt = (instant: number, tz: string): number => {\n const parts = zonedParts(instant, tz);\n const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);\n return asIfUtc - Math.floor(instant / 1000) * 1000;\n};\n\nconst rendersAs = (instant: number, tz: string, day: LocalDay, hour: number, minute: number): boolean => {\n const parts = zonedParts(instant, tz);\n return (\n parts.year === day.year &&\n parts.month === day.month &&\n parts.day === day.day &&\n parts.hour === hour &&\n parts.minute === minute\n );\n};\n\n// The offset is probed half a day either side: across a transition that\n// yields both candidates, where a probe at the guess alone finds one.\n// Ambiguous (fall back): the first occurrence. Erased (spring forward):\n// shifted forward past the gap. Both as Temporal's `disambiguation: 'compatible'`.\nexport const zonedToUtc = (day: LocalDay, hour: number, minute: number, tz: string): number => {\n const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);\n const before = offsetAt(guess - HALF_DAY_MS, tz);\n const after = offsetAt(guess + HALF_DAY_MS, tz);\n const candidates = before === after ? [guess - before] : [guess - before, guess - after];\n const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));\n return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);\n};\n\nexport const daysInMonth = (year: number, month: number): number => new Date(Date.UTC(year, month, 0)).getUTCDate();\n\nconst weekdayOf = (day: LocalDay): string => {\n const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();\n // getUTCDay is Sunday-first; WEEKDAYS is Monday-first.\n return WEEKDAYS[(index + 6) % 7] ?? 'mon';\n};\n\nconst splitInts = (value: string, separator: string): number[] =>\n value.split(separator).map((part) => Number(part));\n\nconst at2 = (values: readonly number[], index: number): number => values[index] ?? 0;\n\nconst nextDay = (day: LocalDay): LocalDay => {\n const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);\n return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };\n};\n\nconst ordinalOf = (day: LocalDay): number => day.year * 10_000 + day.month * 100 + day.day;\n\nconst pad2 = (value: number): string => String(value).padStart(2, '0');\n\n// Day 31 clamps to the month's end, and a yearly Feb 29 likewise: a billing\n// rule never means \"skip February\".\nconst isDueOn = (clock: ClockRecurring, day: LocalDay): boolean => {\n if (clock.every === 'day') return true;\n if (clock.every === 'week') return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;\n if (clock.every === 'month')\n return typeof clock.on === 'number' && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));\n if (typeof clock.on !== 'string') return false;\n const parts = splitInts(clock.on, '-');\n const month = at2(parts, 0);\n const dayOfMonth = at2(parts, 1);\n return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));\n};\n\nexport const occurrenceKey = (clock: ClockRecurring, day: LocalDay): string => {\n if (clock.every === 'year') return String(day.year);\n if (clock.every === 'month') return `${day.year}-${pad2(day.month)}`;\n return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;\n};\n\nexport const occurrencesBetween = (clock: Clock, after: number, through: number, cap: number): Occurrence[] => {\n if (through <= after || cap <= 0) return [];\n\n if (!isRecurring(clock)) {\n const [date = '', time = ''] = clock.at.split('T');\n const ymd = splitInts(date, '-');\n const hms = splitInts(time, ':');\n // The second is added to the resolved minute: an offset changes on a\n // minute boundary, never inside one, so the minute decides the edge.\n const at =\n zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) +\n at2(hms, 2) * 1000;\n return at > after && at <= through ? [{ key: clock.at, at }] : [];\n }\n\n const time = splitInts(clock.at, ':');\n const hour = at2(time, 0);\n const minute = at2(time, 1);\n const start = zonedParts(after, clock.tz);\n const end = zonedParts(through, clock.tz);\n const endOrdinal = ordinalOf(end);\n\n const found: Occurrence[] = [];\n let cursor: LocalDay = { year: start.year, month: start.month, day: start.day };\n let scanned = 0;\n\n while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {\n scanned += 1;\n if (isDueOn(clock, cursor)) {\n const at = zonedToUtc(cursor, hour, minute, clock.tz);\n if (at > after && at <= through) {\n found.push({ key: occurrenceKey(clock, cursor), at });\n if (found.length >= cap) break;\n }\n }\n cursor = nextDay(cursor);\n }\n\n return found;\n};\n","import { factOf, isManual } from '../schemas';\nimport type { Fact, Row, Run } from '../types';\nimport { buildEnv, evaluateTemplate, isTruthy } from './runtime';\nimport type { EngineDeps, LoadedReflex } from './runtime';\n\nexport type OpenRunInput = {\n cause: string;\n depth: number;\n dueAt: number;\n now: number;\n occurrence?: string;\n factIds?: readonly string[];\n note?: string;\n state?: 'pending' | 'skipped';\n repeat?: boolean;\n};\n\nexport const openRun = async (deps: EngineDeps, loaded: LoadedReflex, input: OpenRunInput): Promise<Run | undefined> => {\n const { reflex, version } = loaded;\n\n const base = {\n reflexId: reflex.id,\n version,\n as: reflex.as,\n cause: input.cause,\n occurrence: input.occurrence,\n factIds: input.factIds,\n depth: input.depth,\n total: 0,\n done: 0,\n failed: 0,\n dueAt: input.dueAt,\n createdAt: input.now,\n };\n\n // Overlap governs repeats, not distinct events. An occurrence coming round\n // again, or a person firing twice, is the same work and may be skipped; a\n // write, a signal or a settlement happens once, and skipping it loses it.\n if (input.repeat !== false && input.state !== 'skipped' && reflex.policy.overlap === 'skip') {\n const [unsettled] = await deps.store.query({\n table: 'run',\n where: { reflexId: reflex.id, state: { in: ['pending', 'fanned'] } },\n limit: 1,\n });\n if (unsettled !== undefined) {\n await deps.store.appendIfAbsent('run', {\n ...base,\n state: 'skipped',\n settledAt: input.now,\n drained: true,\n note: `overlap: the previous run (${unsettled.id}) is still unsettled`,\n });\n deps.emit({ type: 'run.skipped', reflexId: reflex.id, reason: 'overlap' });\n return undefined;\n }\n }\n\n const skipped = input.state === 'skipped';\n const run = await deps.store.appendIfAbsent('run', {\n ...base,\n state: input.state ?? 'pending',\n settledAt: skipped ? input.now : undefined,\n drained: skipped ? true : undefined,\n note: input.note,\n });\n\n if (run !== undefined && run.state === 'pending') deps.emit({ type: 'run.created', run });\n return run;\n};\n\nconst factAsRow = (fact: Fact): Row => ({ ...fact });\n\nexport const reflexMatchesFact = (loaded: LoadedReflex, fact: Fact): boolean => {\n const { reflex } = loaded;\n\n // Before enablement and arming: a person can fire a reflex that is disabled.\n if (fact.kind === 'manual') return fact.target === reflex.id;\n\n // The tenant boundary inside the engine: a fact wakes only reflexes running\n // under the same identity, since its row reaches the effect with no query\n // and so no host policy. No identity wakes only reflexes with none.\n if (fact.as !== reflex.as) return false;\n\n if (!reflex.enabled) return false;\n if (fact.at < loaded.armedAt) return false;\n\n if (isManual(reflex.on)) return false;\n\n const watched = factOf(reflex.on);\n if (watched === undefined) return false;\n\n if (fact.kind === 'write')\n return watched.entity !== undefined && watched.entity === fact.entity && (watched.op === undefined || watched.op === fact.op);\n if (fact.kind === 'signal') return watched.signal !== undefined && watched.signal === fact.name;\n if (fact.kind === 'run') return watched.run !== undefined && watched.run === fact.reflex;\n return false;\n};\n\nexport type MatchReport = { factsMatched: number; runsCreated: number; parked: number };\n\nexport const matchFacts = async (deps: EngineDeps, now: number, limit: number): Promise<MatchReport> => {\n const report: MatchReport = { factsMatched: 0, runsCreated: 0, parked: 0 };\n\n // With no reflex loaded, facts wait: marked delivered here, a backlog would\n // be out of reach of the reflexes a `load()` brings a moment later.\n if (deps.reflexes().length === 0) return report;\n\n const due = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true } },\n order: [{ by: 'at' }],\n limit: limit * 4,\n });\n\n for (const fact of due.filter((candidate) => (candidate.notBefore ?? candidate.at) <= now).slice(0, limit)) {\n if (fact.depth > deps.maxChainDepth && fact.released !== true) {\n const reason = `chain depth ${fact.depth} exceeds maxChainDepth ${deps.maxChainDepth}`;\n await deps.store.cas('fact', fact.id, {}, { parked: reason });\n deps.emit({ type: 'fact.parked', fact, reason });\n report.parked += 1;\n continue;\n }\n\n let woke = false;\n\n for (const loaded of deps.reflexes()) {\n if (!reflexMatchesFact(loaded, fact)) continue;\n\n const env = buildEnv({ params: loaded.reflex.params, fact: factAsRow(fact), now });\n\n if (loaded.reflex.when !== undefined) {\n try {\n if (!isTruthy(evaluateTemplate(deps.transform, loaded.reflex.when, env))) {\n deps.emit({ type: 'fact.unmatched', fact, reflexId: loaded.reflex.id, reason: '`when` did not match' });\n continue;\n }\n } catch (error) {\n deps.emit({\n type: 'fact.unmatched',\n fact,\n reflexId: loaded.reflex.id,\n reason: `when: ${error instanceof Error ? error.message : String(error)}`,\n });\n continue;\n }\n }\n\n woke = true;\n\n const run = await openRun(deps, loaded, {\n cause: `fact:${fact.id}`,\n depth: fact.depth,\n dueAt: now,\n now,\n occurrence: fact.occurrence,\n factIds: [fact.id],\n repeat: fact.kind === 'manual',\n });\n if (run !== undefined) report.runsCreated += 1;\n }\n\n await deps.store.cas('fact', fact.id, {}, { deliveredAt: now });\n if (woke) report.factsMatched += 1;\n }\n\n return report;\n};\n","import { clockOf } from '../schemas';\nimport type { ReflexState } from '../types';\nimport type { EngineDeps, LoadedReflex } from './runtime';\nimport { occurrencesBetween } from './occurrence';\nimport { openRun } from './match';\n\nconst MAX_OCCURRENCES_PER_TICK = 500;\n\nexport const stateOf = async (deps: EngineDeps, reflexId: string): Promise<ReflexState | undefined> =>\n (await deps.store.query({ table: 'state', where: { reflexId }, limit: 1 }))[0];\n\nconst patchState = async (deps: EngineDeps, reflexId: string, patch: Partial<ReflexState>): Promise<void> => {\n if (await deps.store.cas('state', reflexId, {}, patch)) return;\n const created = await deps.store.appendIfAbsent('state', { reflexId, armedAt: 0, ...patch });\n if (created === undefined) await deps.store.cas('state', reflexId, {}, patch);\n};\n\nexport type MaterializeReport = { materialized: number; skippedOccurrences: number; runsCreated: number };\n\nexport const materializeClocks = async (deps: EngineDeps, now: number): Promise<MaterializeReport> => {\n const report: MaterializeReport = { materialized: 0, skippedOccurrences: 0, runsCreated: 0 };\n\n for (const loaded of deps.reflexes()) {\n const clock = clockOf(loaded.reflex.on);\n if (clock === undefined) continue;\n\n const state = await stateOf(deps, loaded.reflex.id);\n const through = state?.materializedThrough ?? (loaded.armedAt > 0 ? loaded.armedAt : now);\n\n // A disabled reflex materializes nothing and still moves its watermark:\n // otherwise enabling it again would mint every occurrence of the pause.\n if (!loaded.reflex.enabled || now <= through) {\n if (state?.materializedThrough === undefined || now > through)\n await patchState(deps, loaded.reflex.id, { materializedThrough: loaded.reflex.enabled ? through : now });\n continue;\n }\n\n const occurrences = occurrencesBetween(clock, through, now, MAX_OCCURRENCES_PER_TICK);\n const newest = occurrences.length === 0 ? undefined : occurrences[occurrences.length - 1];\n const { catchUp, lateMs } = loaded.reflex.policy;\n\n for (const occurrence of occurrences) {\n const isNewest = occurrence === newest;\n const late = now - occurrence.at > lateMs;\n const skip = catchUp === 'latest' ? !isNewest : catchUp === 'skip' ? late : false;\n\n const run = await openRun(deps, loaded, {\n cause: `occurrence:${occurrence.key}`,\n depth: 0,\n dueAt: occurrence.at,\n now,\n occurrence: occurrence.key,\n state: skip ? 'skipped' : 'pending',\n note: skip ? `catchUp: ${catchUp} — occurrence ${occurrence.key} was ${Math.round((now - occurrence.at) / 1000)}s late` : undefined,\n });\n\n if (skip) report.skippedOccurrences += 1;\n else if (run !== undefined) {\n report.materialized += 1;\n report.runsCreated += 1;\n }\n }\n\n // When the cap bites, the watermark stops at the last occurrence\n // materialized and the next advance resumes after it: `occurrencesBetween`\n // excludes its start.\n const capped = occurrences.length >= MAX_OCCURRENCES_PER_TICK && newest !== undefined;\n await patchState(deps, loaded.reflex.id, { materializedThrough: capped ? newest.at : now });\n }\n\n return report;\n};\n","import { TideError, isTideError } from '../errors';\nimport type { Fact, Row, Run, Task } from '../types';\nimport { buildEnv, evaluateTemplate } from './runtime';\nimport type { EngineDeps, LoadedReflex } from './runtime';\n\nexport const collectRows = async (\n source: AsyncIterable<Row> | Iterable<Row> | Promise<Iterable<Row>>,\n cap: number,\n): Promise<readonly Row[]> => {\n const resolved = await source;\n const rows: Row[] = [];\n if (Symbol.asyncIterator in Object(resolved)) {\n for await (const row of resolved as AsyncIterable<Row>) {\n rows.push(row);\n if (rows.length > cap) throw new TideError('duplicate_unit', `selection exceeded maxFanOut (${cap})`);\n }\n return rows;\n }\n for (const row of resolved as Iterable<Row>) {\n rows.push(row);\n if (rows.length > cap) throw new TideError('duplicate_unit', `selection exceeded maxFanOut (${cap})`);\n }\n return rows;\n};\n\ntype Unit = { unit: string; env: Row };\n\nconst unitsFrom = (rows: readonly Row[], unitKey: string | undefined, base: Row, reflexId: string): Unit[] => {\n const seen = new Set<string>();\n return rows.map((row) => {\n const raw = unitKey === undefined ? undefined : row[unitKey];\n const unit = raw === undefined || raw === null ? '' : String(raw);\n // Refused here: the unique key on tasks would drop the second row silently.\n if (seen.has(unit))\n throw new TideError('duplicate_unit', `${reflexId}: duplicate unit key \"${unit}\" — the selection's unitKey is not unique`);\n seen.add(unit);\n return { unit, env: { ...base, row } };\n });\n};\n\nconst factRowsOf = async (deps: EngineDeps, run: Run): Promise<readonly Fact[]> => {\n const ids = run.factIds ?? [];\n if (ids.length === 0) return [];\n return deps.store.query({ table: 'fact', where: { id: { in: [...ids] } } });\n};\n\nexport const fanOut = async (deps: EngineDeps, now: number, limit: number): Promise<number> => {\n let created = 0;\n\n const pending = await deps.store.query({\n table: 'run',\n where: { state: 'pending' },\n order: [{ by: 'dueAt' }],\n limit,\n });\n\n for (const run of pending) {\n const loaded = deps.find(run.reflexId);\n if (loaded === undefined) {\n await deps.store.cas('run', run.id, { state: 'pending' }, { state: 'skipped', settledAt: now, drained: true, note: 'reflex is no longer loaded' });\n continue;\n }\n\n try {\n const facts = await factRowsOf(deps, run);\n const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);\n created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n\n // A TideError means the reflex itself is wrong: the run is skipped, for\n // good. Anything else came out of a host seam (the selection, the\n // transform, the database): the run stays `pending` and is tried again.\n if (isTideError(error)) {\n await deps.store.cas('run', run.id, { state: 'pending' }, { state: 'skipped', settledAt: now, drained: true, note: `fan-out refused: ${reason}` });\n deps.emit({ type: 'run.skipped', reflexId: run.reflexId, reason });\n continue;\n }\n\n await deps.store.cas('run', run.id, { state: 'pending' }, { note: `fan-out deferred: ${reason}` });\n deps.emit({ type: 'run.deferred', reflexId: run.reflexId, runId: run.id, reason });\n }\n }\n\n return created;\n};\n\n// The tasks and the run's move to `fanned` commit together: after a crash the\n// run is still `pending` with no tasks, and the next fan-out selects afresh.\nconst commitFanout = async (\n deps: EngineDeps,\n run: Run,\n tasks: readonly Omit<Task, 'id'>[],\n selected: number,\n now: number,\n): Promise<number> =>\n deps.store.transact(async (tx) => {\n const claimed = await tx.cas('run', run.id, { state: 'pending' }, { state: 'fanned' });\n if (!claimed) return 0;\n\n let written = 0;\n for (const task of tasks) if ((await tx.appendIfAbsent('task', task)) !== undefined) written += 1;\n\n // `total` counts the tasks written, not offered: one the unique key refused\n // never lands, and a run waiting on it would never settle.\n const settledNow = written === 0;\n await tx.cas(\n 'run',\n run.id,\n {},\n {\n selected,\n total: written,\n state: settledNow ? 'settled' : 'fanned',\n settledAt: settledNow ? now : undefined,\n },\n );\n return written;\n });\n\nconst taskOf = (unit: Unit, run: Run, loaded: LoadedReflex, now: number): Omit<Task, 'id'> => ({\n runId: run.id,\n reflexId: loaded.reflex.id,\n unit: unit.unit,\n cause: run.cause,\n env: unit.env,\n // Carried on the task: a swept run must not reset the chain ceiling.\n depth: run.depth,\n state: 'pending',\n attempt: 0,\n claimedUntil: 0,\n notBefore: run.dueAt > now ? run.dueAt : now,\n createdAt: now,\n});\n\nexport type RunShape = { cause: string; occurrence?: string; dueAt: number };\n\nconst shapeOf = (run: Run): RunShape => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });\n\nexport const unitsForRun = async (\n deps: EngineDeps,\n loaded: LoadedReflex,\n run: RunShape,\n facts: readonly Fact[],\n now: number,\n): Promise<Unit[]> => {\n const { reflex } = loaded;\n\n const base = buildEnv({\n params: reflex.params,\n occurrence: run.occurrence === undefined ? undefined : { key: run.occurrence, at: run.dueAt },\n fact: facts.length === 1 ? { ...facts[0] } : undefined,\n facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : undefined,\n now,\n });\n\n const carried = facts.map((fact) => fact.row).filter((row): row is Row => row !== undefined);\n if (carried.length > 0 && reflex.select === undefined) return unitsFrom(carried, undefined, base, reflex.id);\n\n if (reflex.select === undefined) return [{ unit: '', env: base }];\n\n if (deps.select === undefined)\n throw new TideError('store', `${reflex.id} has a selection but no \\`select\\` seam is wired`);\n\n const query = evaluateTemplate(deps.transform, reflex.select.query, base);\n const rows = await collectRows(\n deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),\n deps.maxFanOut,\n );\n\n if (reflex.select.mode === 'batch') return [{ unit: '', env: { ...base, rows } }];\n return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);\n};\n\nexport type { Unit };\n","import type { Fact, NewFact, TideEvent, TideStore } from '../types';\n\nexport type Admission = { stored: Fact } | { refused: NewFact };\n\nconst rootOf = async (store: TideStore, cause: string | undefined): Promise<string | undefined> => {\n if (cause === undefined) return undefined;\n let runId: string | undefined;\n if (cause.startsWith('task:')) {\n const [task] = await store.query({ table: 'task', where: { id: cause.slice('task:'.length) }, limit: 1 });\n runId = task?.runId;\n } else if (cause.startsWith('run:')) {\n runId = cause.slice('run:'.length);\n }\n if (runId === undefined) return undefined;\n const [run] = await store.query({ table: 'run', where: { id: runId }, limit: 1 });\n const parentId = run?.factIds?.[0];\n if (parentId === undefined) return undefined;\n const [parent] = await store.query({ table: 'fact', where: { id: parentId }, limit: 1 });\n return parent === undefined ? undefined : (parent.root ?? parent.id);\n};\n\nexport const admitFact = async (store: TideStore, fact: NewFact, maxChainFacts: number): Promise<Admission> => {\n const root = await rootOf(store, fact.cause);\n let parked: string | undefined;\n if (root !== undefined && (await store.cas('fact', root, {}, { descendants: { inc: 1 } }))) {\n const [counted] = await store.query({ table: 'fact', where: { id: root }, limit: 1 });\n const minted = counted?.descendants ?? 0;\n if (minted > maxChainFacts) parked = `chain from fact ${root} minted ${minted} facts, past maxChainFacts ${maxChainFacts}`;\n }\n const row = { ...fact, ...(root === undefined ? {} : { root }), ...(parked === undefined ? {} : { parked }) };\n const stored = await store.appendIfAbsent('fact', row);\n return stored === undefined ? { refused: fact } : { stored };\n};\n\nexport const announceFact = (emit: (event: TideEvent) => void, admission: Admission): void => {\n if ('stored' in admission) emit({ type: 'fact.ingested', fact: admission.stored });\n else emit({ type: 'fact.deduped', fact: admission.refused });\n};\n","import { FactInputSchema } from '../schemas';\nimport { TideError } from '../errors';\nimport type { AttemptOutcome, FactInput, NewFact, Task, TideCtx, TideStore } from '../types';\nimport { evaluateTemplate, withNow } from './runtime';\nimport { admitFact, announceFact } from './facts';\nimport type { Admission } from './facts';\nimport type { EngineDeps } from './runtime';\n\nexport type ExecuteReport = { executed: number; succeeded: number; failed: number; retrying: number; reclaimed: number };\n\nconst TIMEOUT = Symbol('tide.timeout');\n\nconst raceTimeout = async (work: Promise<unknown>, timeoutMs: number): Promise<unknown> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMEOUT>((resolve) => {\n timer = setTimeout(() => resolve(TIMEOUT), timeoutMs);\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n};\n\nconst backoffFor = (attempt: number, base: number, kind: 'fixed' | 'exponential'): number =>\n kind === 'fixed' ? base : base * Math.pow(2, Math.max(0, attempt - 1));\n\nconst claimTasks = async (deps: EngineDeps, now: number, limit: number, token: string): Promise<readonly Task[]> => {\n const serialReflexIds = deps\n .reflexes()\n .filter((loaded) => loaded.reflex.policy.order === 'serial')\n .map((loaded) => loaded.reflex.id);\n\n return deps.store.claim({\n table: 'task',\n where: {\n state: { in: ['pending', 'retrying', 'claimed'] },\n notBefore: { lte: now },\n claimedUntil: { lte: now },\n },\n // `unit` breaks ties: one fan-out's tasks share `notBefore` and `createdAt`,\n // and two stores must order them the same way.\n order: [{ by: 'notBefore' }, { by: 'createdAt' }, { by: 'unit' }],\n limit,\n set: { state: 'claimed', token, claimedUntil: now + deps.leaseMs, attempt: { inc: 1 } },\n onePer:\n serialReflexIds.length === 0\n ? undefined\n : { column: 'reflexId', held: { state: 'claimed', claimedUntil: { gt: now } }, only: serialReflexIds },\n });\n};\n\nexport const executeTasks = async (deps: EngineDeps, now: number, limit: number): Promise<ExecuteReport> => {\n const report: ExecuteReport = { executed: 0, succeeded: 0, failed: 0, retrying: 0, reclaimed: 0 };\n\n // Read before the claim, which returns each row as it wrote it. Only a\n // metric, so a race between the two costs a count, not a guarantee.\n const lapsed = new Set(\n (\n await deps.store.query({\n table: 'task',\n where: { state: 'claimed', claimedUntil: { lte: now }, notBefore: { lte: now } },\n limit,\n })\n ).map((task) => task.id),\n );\n\n const token = deps.nextToken();\n const claimed = await claimTasks(deps, now, limit, token);\n\n for (const task of claimed) {\n if (lapsed.has(task.id)) {\n report.reclaimed += 1;\n deps.emit({ type: 'task.reclaimed', task });\n }\n\n const loaded = deps.find(task.reflexId);\n if (loaded === undefined) continue;\n\n const { reflex } = loaded;\n const registry = deps.effectsFor(reflex.as);\n const handler = registry[reflex.effect.name];\n const env = withNow(task.env, now);\n\n const buffered: NewFact[] = [];\n const ctx: TideCtx = {\n reflexId: reflex.id,\n runId: task.runId,\n taskId: task.id,\n taskKey: `${reflex.id}:${task.cause}:${task.unit}`,\n attempt: task.attempt,\n depth: task.depth,\n now,\n actor: deps.actorFor(reflex.as),\n // `write` and `signal` only: a `manual` fact fires a disabled reflex, and\n // `run` facts are minted by the settler alone.\n emit: (fact: Omit<FactInput, 'cause'>) => {\n if (fact.kind !== 'write' && fact.kind !== 'signal')\n throw new TideError('invalid_fact', `${reflex.id}: an effect may emit \\`write\\` or \\`signal\\` facts, not \\`${fact.kind}\\``);\n const parsed = FactInputSchema.safeParse({ ...fact, cause: `task:${task.id}` });\n if (!parsed.success)\n throw new TideError('invalid_fact', `${reflex.id}: emitted fact did not parse: ${parsed.error.issues.map((i) => i.message).join('; ')}`, {\n issues: parsed.error.issues,\n });\n buffered.push({ ...parsed.data, depth: 0 });\n },\n };\n\n let outcome: AttemptOutcome = 'ok';\n let output: unknown;\n let error: string | undefined;\n let input: unknown;\n\n try {\n input = evaluateTemplate(deps.transform, reflex.effect.input, env);\n if (handler === undefined) throw new Error(`effect \"${reflex.effect.name}\" is not registered`);\n const result = await raceTimeout(Promise.resolve(handler.run(input, ctx)), reflex.policy.timeoutMs);\n if (result === TIMEOUT) {\n outcome = 'timeout';\n error = `timed out after ${reflex.policy.timeoutMs}ms`;\n } else {\n output = result;\n }\n } catch (thrown) {\n outcome = 'error';\n error = thrown instanceof Error ? thrown.message : String(thrown);\n }\n\n // Depth and identity are stamped by the engine: a handler that chose\n // either could escape the chain ceiling or the tenant boundary.\n const emits = buffered.map((fact) => ({ ...fact, depth: task.depth + 1, as: reflex.as }));\n\n const retry = reflex.policy.retry;\n const maxAttempts = (retry?.max ?? 3) + 1;\n const next =\n outcome === 'ok'\n ? ({ state: 'done' } as const)\n : task.attempt >= maxAttempts\n ? ({ state: 'failed' } as const)\n : ({\n state: 'retrying',\n notBefore: now + backoffFor(task.attempt, retry?.baseMs ?? 60_000, retry?.backoff ?? 'exponential'),\n } as const);\n\n const recorded = await record(deps, task, token, {\n state: next.state,\n notBefore: next.state === 'retrying' ? next.notBefore : task.notBefore,\n output,\n error,\n // A failed attempt's emits are dropped: its retry would mint them again.\n emits: outcome === 'ok' ? emits : [],\n at: now,\n });\n\n if (recorded === undefined) continue;\n // Announced after the commit: a rollback would have taken these rows back.\n for (const admission of recorded) announceFact(deps.emit, admission);\n\n report.executed += 1;\n const [settled] = await deps.store.query({ table: 'task', where: { id: task.id }, limit: 1 });\n const reported = settled === undefined ? undefined : { ...settled, input };\n if (next.state === 'done') {\n report.succeeded += 1;\n if (reported !== undefined) deps.emit({ type: 'task.done', task: reported });\n } else if (next.state === 'failed') {\n report.failed += 1;\n if (reported !== undefined) deps.emit({ type: 'task.failed', task: reported });\n } else {\n report.retrying += 1;\n if (reported !== undefined) deps.emit({ type: 'task.retrying', task: reported, nextAt: next.notBefore });\n }\n }\n\n return report;\n};\n\ntype Settlement = {\n state: Task['state'];\n notBefore: number;\n output?: unknown;\n error?: string;\n emits: readonly NewFact[];\n at: number;\n};\n\nconst record = async (deps: EngineDeps, task: Task, token: string, settlement: Settlement): Promise<readonly Admission[] | undefined> =>\n deps.store.transact(async (tx: TideStore) => {\n const settles = settlement.state === 'done' || settlement.state === 'failed';\n\n // The fence: `expect` is this claim's token and attempt, so an attempt\n // that finishes late is discarded. Two engines' tokens can collide; the\n // attempt, which the store bumps on every claim, cannot.\n const accepted = await tx.cas(\n 'task',\n task.id,\n { token, attempt: task.attempt },\n {\n state: settlement.state,\n token: undefined,\n claimedUntil: 0,\n output: settlement.output,\n error: settlement.error,\n notBefore: settlement.notBefore,\n settledAt: settles ? settlement.at : undefined,\n },\n );\n if (!accepted) return undefined;\n\n const admissions: Admission[] = [];\n for (const emit of settlement.emits) admissions.push(await admitFact(tx, emit, deps.maxChainFacts));\n\n if (settles) {\n // Counted first, read second: the increment is the store's own\n // arithmetic, so the read sees every count that has landed. Read first,\n // two landings each find the run short of its total and neither settles it.\n await tx.cas(\n 'run',\n task.runId,\n {},\n { done: { inc: settlement.state === 'done' ? 1 : 0 }, failed: { inc: settlement.state === 'failed' ? 1 : 0 } },\n );\n const [run] = await tx.query({ table: 'run', where: { id: task.runId }, limit: 1 });\n if (run !== undefined && run.done + run.failed >= run.total && run.settledAt === undefined)\n await tx.cas('run', run.id, { state: 'fanned' }, { state: 'settled', settledAt: settlement.at });\n }\n return admissions;\n });\n\n// Two writes to the run. The count comes down whatever state the run is in: a\n// second retry finds it already rewound. The rewind applies to a `settled`\n// run only and leaves `drained` set, so the run fact is not emitted again.\nexport const reopenTask = async (deps: EngineDeps, taskId: string, now: number): Promise<boolean> =>\n deps.store.transact(async (tx) => {\n const [task] = await tx.query({ table: 'task', where: { id: taskId }, limit: 1 });\n if (task === undefined || task.state !== 'failed') return false;\n\n const reopened = await tx.cas(\n 'task',\n taskId,\n { state: 'failed' },\n { state: 'pending', notBefore: now, error: undefined, settledAt: undefined, token: undefined, claimedUntil: 0 },\n );\n if (!reopened) return false;\n\n await tx.cas('run', task.runId, {}, { failed: { inc: -1 } });\n await tx.cas('run', task.runId, { state: 'settled' }, { state: 'fanned', settledAt: undefined });\n return true;\n });\n\nexport const settleRuns = async (deps: EngineDeps, now: number): Promise<number> => {\n const settled = await deps.store.claim({\n table: 'run',\n where: { state: 'settled', drained: { ne: true } },\n order: [{ by: 'settledAt' }],\n limit: 200,\n set: { drained: true },\n });\n\n for (const run of settled) {\n deps.emit({ type: 'run.settled', run });\n const admission = await admitFact(deps.store, {\n kind: 'run',\n reflex: run.reflexId,\n runId: run.id,\n occurrence: run.occurrence,\n stats: { total: run.total, done: run.done, failed: run.failed },\n at: now,\n depth: run.depth + 1,\n cause: `run:${run.id}`,\n as: run.as,\n }, deps.maxChainFacts);\n announceFact(deps.emit, admission);\n }\n\n return settled.length;\n};\n","import type { AdvanceReport } from '../types';\nimport type { EngineDeps } from './runtime';\nimport { materializeClocks } from './materialize';\nimport { matchFacts } from './match';\nimport { fanOut } from './fanout';\nimport { executeTasks, settleRuns } from './execute';\n\nexport type AdvanceOptions = { now: number; limit?: number };\n\nconst DEFAULT_LIMIT = 100;\n\nexport const runAdvance = async (deps: EngineDeps, options: AdvanceOptions): Promise<AdvanceReport> => {\n const { now } = options;\n const limit = options.limit ?? DEFAULT_LIMIT;\n\n const clocks = await materializeClocks(deps, now);\n const matched = await matchFacts(deps, now, limit);\n const tasksCreated = await fanOut(deps, now, limit);\n const executed = await executeTasks(deps, now, limit);\n const runsSettled = await settleRuns(deps, now);\n\n return {\n now,\n materialized: clocks.materialized,\n skippedOccurrences: clocks.skippedOccurrences,\n factsMatched: matched.factsMatched,\n runsCreated: clocks.runsCreated + matched.runsCreated,\n tasksCreated,\n executed: executed.executed,\n succeeded: executed.succeeded,\n failed: executed.failed,\n retrying: executed.retrying,\n reclaimed: executed.reclaimed,\n runsSettled,\n parked: matched.parked,\n };\n};\n","import { clockOf } from '../schemas';\nimport { occurrencesBetween } from './occurrence';\nimport { stateOf } from './materialize';\nimport type { EngineDeps } from './runtime';\n\nconst CLOCK_HORIZON_MS = 370 * 24 * 60 * 60 * 1000;\n\nexport const nextDue = async (deps: EngineDeps, now: number): Promise<number | undefined> => {\n let due: number | undefined;\n const consider = (at: number | undefined): void => {\n if (at === undefined) return;\n if (due === undefined || at < due) due = at;\n };\n\n const [immediate] = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true }, notBefore: { isNull: true } },\n order: [{ by: 'at' }],\n limit: 1,\n });\n consider(immediate?.at);\n const [delayed] = await deps.store.query({\n table: 'fact',\n where: { deliveredAt: { isNull: true }, parked: { isNull: true }, notBefore: { isNull: false } },\n order: [{ by: 'notBefore' }],\n limit: 1,\n });\n consider(delayed?.notBefore);\n\n // Pending runs only: a fanned run waiting on a retrying task would report a\n // past instant on every call. Its tasks, below, are what is due.\n const [run] = await deps.store.query({ table: 'run', where: { state: 'pending' }, order: [{ by: 'dueAt' }], limit: 1 });\n consider(run?.dueAt);\n\n const [waiting] = await deps.store.query({\n table: 'task',\n where: { state: { in: ['pending', 'retrying'] } },\n order: [{ by: 'notBefore' }],\n limit: 1,\n });\n consider(waiting?.notBefore);\n const [claimed] = await deps.store.query({ table: 'task', where: { state: 'claimed' }, order: [{ by: 'claimedUntil' }], limit: 1 });\n consider(claimed?.claimedUntil);\n\n for (const loaded of deps.reflexes()) {\n const clock = clockOf(loaded.reflex.on);\n if (clock !== undefined) {\n const state = await stateOf(deps, loaded.reflex.id);\n // No watermark yet: due now, so the driver's next advance sets it.\n if (state?.materializedThrough === undefined) {\n consider(now);\n continue;\n }\n // A disabled clock is due too: the advance moves its watermark, or the\n // reflex would get its whole pause as a backlog when enabled again.\n consider(occurrencesBetween(clock, state.materializedThrough, state.materializedThrough + CLOCK_HORIZON_MS, 1)[0]?.at);\n }\n }\n\n return due;\n};\n","import { clockOf, isRecurring } from '../schemas';\nimport { TideError } from '../errors';\nimport type { Fact, FactInput, PreviewReport, PreviewUnit } from '../types';\nimport { evaluateTemplate, isTruthy, withNow } from './runtime';\nimport type { EngineDeps } from './runtime';\nimport { occurrencesBetween } from './occurrence';\nimport { unitsForRun } from './fanout';\n\nconst LOOKBACK_MS = 400 * 86_400_000;\nconst LOOKAHEAD_MS = 400 * 86_400_000;\n\nexport type PreviewOptions = { now: number; fact?: FactInput };\n\nexport const previewReflex = async (\n deps: EngineDeps,\n reflexId: string,\n options: PreviewOptions,\n): Promise<PreviewReport> => {\n const loaded = deps.find(reflexId);\n if (loaded === undefined) throw new TideError('unknown_reflex', `no reflex \"${reflexId}\" is loaded`);\n\n const { reflex, version } = loaded;\n const { now } = options;\n\n const clock = clockOf(reflex.on);\n const occurrence = clock === undefined ? undefined : nearestOccurrence(clock, now);\n\n const facts: Fact[] =\n options.fact === undefined ? [] : [{ ...options.fact, id: 'preview-fact', depth: 0 }];\n\n const cause =\n occurrence !== undefined\n ? `occurrence:${occurrence.key}`\n : facts.length > 0\n ? 'fact:preview-fact'\n : `manual:preview`;\n\n const report: PreviewReport = {\n reflexId,\n version,\n fired: true,\n effect: reflex.effect.name,\n cause,\n occurrence: occurrence?.key,\n selected: 0,\n units: [],\n };\n\n if (reflex.when !== undefined && facts.length > 0) {\n try {\n const env = { params: reflex.params ?? {}, fact: { ...facts[0] }, now };\n if (!isTruthy(evaluateTemplate(deps.transform, reflex.when, env)))\n return { ...report, fired: false, reason: '`when` did not match this fact' };\n } catch (error) {\n return { ...report, fired: false, reason: `when: ${error instanceof Error ? error.message : String(error)}` };\n }\n }\n\n let units;\n try {\n units = await unitsForRun(\n deps,\n loaded,\n { cause, occurrence: occurrence?.key, dueAt: occurrence?.at ?? now },\n facts,\n now,\n );\n } catch (error) {\n return { ...report, fired: false, reason: error instanceof Error ? error.message : String(error) };\n }\n\n const registry = deps.effectsFor(reflex.as);\n const handler = registry[reflex.effect.name];\n const actor = deps.actorFor(reflex.as);\n\n const previewed: PreviewUnit[] = units.map((unit) => {\n try {\n const input = evaluateTemplate(deps.transform, reflex.effect.input, withNow(unit.env, now));\n const render = handler?.preview?.(input, { reflexId, unit: unit.unit, now, actor });\n return { unit: unit.unit, env: unit.env, input, render };\n } catch (error) {\n return { unit: unit.unit, env: unit.env, error: error instanceof Error ? error.message : String(error) };\n }\n });\n\n return { ...report, selected: units.length, units: previewed };\n};\n\nconst nearestOccurrence = (\n clock: NonNullable<ReturnType<typeof clockOf>>,\n now: number,\n): { key: string; at: number } | undefined => {\n const past = occurrencesBetween(clock, now - LOOKBACK_MS, now, 500);\n if (past.length > 0) return past[past.length - 1];\n const future = occurrencesBetween(clock, now, now + LOOKAHEAD_MS, 1);\n if (future.length > 0) return future[0];\n return isRecurring(clock) ? undefined : { key: clock.at, at: now };\n};\n","import { FactInputSchema, ReflexSchema, factOf } from './schemas';\nimport type { Reflex, ReflexInput } from './schemas';\nimport { TideError } from './errors';\nimport type {\n AdvanceReport,\n EffectRegistry,\n Fact,\n FactInput,\n LoadReport,\n PreviewReport,\n Retention,\n Run,\n Task,\n TaskState,\n TideConfig,\n} from './types';\nimport { versionOf } from './engine/runtime';\nimport type { EngineDeps, LoadedReflex } from './engine/runtime';\nimport { buildGraph } from './engine/graph';\nimport type { GraphReport } from './engine/graph';\nimport { runAdvance } from './engine/advance';\nimport type { AdvanceOptions } from './engine/advance';\nimport { nextDue as computeNextDue } from './engine/due';\nimport { previewReflex } from './engine/preview';\nimport type { PreviewOptions } from './engine/preview';\nimport { reopenTask } from './engine/execute';\nimport { stateOf } from './engine/materialize';\nimport { admitFact, announceFact } from './engine/facts';\n\nexport type Tide = {\n load: (reflexes: readonly ReflexInput[], options?: { at?: number }) => Promise<LoadReport>;\n reflexes: () => readonly Reflex[];\n graph: () => GraphReport;\n\n ingest: (fact: FactInput, options?: { as?: string; cause?: string; depth?: number }) => Promise<Fact | undefined>;\n advance: (options: AdvanceOptions) => Promise<AdvanceReport>;\n nextDue: (now: number) => Promise<number | undefined>;\n\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n retry: (taskId: string, now: number) => Promise<boolean>;\n preview: (reflexId: string, options: PreviewOptions) => Promise<PreviewReport>;\n\n ledger: {\n runs: (filter?: { reflexId?: string; limit?: number }) => Promise<readonly Run[]>;\n run: (id: string) => Promise<Run | undefined>;\n tasks: (filter?: { runId?: string; reflexId?: string; state?: TaskState; limit?: number }) => Promise<readonly Task[]>;\n task: (id: string) => Promise<Task | undefined>;\n facts: (filter?: { reflexId?: string; limit?: number }) => Promise<readonly Fact[]>;\n fact: (id: string) => Promise<Fact | undefined>;\n causeChain: (factId: string) => Promise<readonly Fact[]>;\n releaseParked: (factId: string) => Promise<boolean>;\n };\n\n sweep: (now: number, retention: Retention) => Promise<number>;\n};\n\nconst DEFAULT_MAX_CHAIN_DEPTH = 24;\nconst DEFAULT_MAX_CHAIN_FACTS = 10_000;\nconst DEFAULT_MAX_FAN_OUT = 10_000;\nconst DEFAULT_LEASE_MS = 300_000;\n\nexport const createTide = (config: TideConfig): Tide => {\n const loaded = new Map<string, LoadedReflex>();\n let effectsCache: EffectRegistry | undefined;\n\n const effectsFor = (as: string | undefined): EffectRegistry => {\n if (typeof config.effects === 'function') return config.effects(as);\n if (effectsCache === undefined) effectsCache = config.effects ?? {};\n return effectsCache;\n };\n\n let tokens = 0;\n const deps: EngineDeps = {\n store: config.store,\n transform: config.transform,\n select: config.select,\n effectsFor,\n actorFor: config.actor ?? ((as) => as),\n maxChainDepth: config.maxChainDepth ?? DEFAULT_MAX_CHAIN_DEPTH,\n maxChainFacts: config.maxChainFacts ?? DEFAULT_MAX_CHAIN_FACTS,\n maxFanOut: config.maxFanOut ?? DEFAULT_MAX_FAN_OUT,\n leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,\n emit: config.onEvent ?? (() => undefined),\n reflexes: () => [...loaded.values()],\n find: (id) => loaded.get(id),\n nextToken: () => {\n tokens += 1;\n return `tok_${tokens.toString(36)}`;\n },\n };\n\n const load = async (input: readonly ReflexInput[], options?: { at?: number }): Promise<LoadReport> => {\n const parsed: Reflex[] = [];\n const seen = new Set<string>();\n\n for (const candidate of input) {\n const result = ReflexSchema.safeParse(candidate);\n if (!result.success)\n throw new TideError('invalid_reflex', `reflex did not parse: ${result.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`, {\n issues: result.error.issues,\n });\n if (seen.has(result.data.id)) throw new TideError('duplicate_reflex', `duplicate reflex id \"${result.data.id}\"`);\n seen.add(result.data.id);\n parsed.push(result.data);\n }\n\n const graph = buildGraph(parsed, mergedEffects(parsed));\n const refused = graph.refusals[0];\n if (refused !== undefined)\n throw new TideError(refused.code, `tide refused to load:\\n ${graph.errors.join('\\n ')}`, { errors: graph.errors, refusals: graph.refusals });\n\n const previously = new Set(loaded.keys());\n\n // Built aside and swapped in one synchronous step: a concurrent reader\n // never sees a half-loaded set.\n const next = new Map<string, LoadedReflex>();\n for (const reflex of parsed) {\n const stored = await stateOf(deps, reflex.id);\n // The stored arming time wins over `at`: a restart does not arm the\n // reflex again.\n const armedAt = stored?.armedAt ?? options?.at ?? 0;\n if (stored === undefined) await config.store.appendIfAbsent('state', { reflexId: reflex.id, armedAt });\n\n // A reflex entering the set has its watermark moved up to `at`: left out\n // of the load for a while, it would otherwise materialize all it missed.\n if (!previously.has(reflex.id) && stored?.materializedThrough !== undefined && options?.at !== undefined)\n await config.store.cas('state', reflex.id, {}, { materializedThrough: Math.max(stored.materializedThrough, options.at) });\n\n next.set(reflex.id, { reflex, version: versionOf(reflex), armedAt });\n }\n loaded.clear();\n for (const [id, entry] of next) loaded.set(id, entry);\n\n return { loaded: parsed.length, cycles: graph.cycles, blind: graph.blind, warnings: graph.warnings };\n };\n\n const mergedEffects = (parsed: readonly Reflex[]): EffectRegistry => {\n if (typeof config.effects !== 'function') return config.effects ?? {};\n const union: EffectRegistry = {};\n for (const reflex of parsed) Object.assign(union, config.effects(reflex.as));\n return union;\n };\n\n // Looser than the matcher on purpose: nothing is dropped while no reflex is\n // loaded, and `enabled`, `as` and `armedAt` are not consulted.\n const watchable = (fact: FactInput): boolean => {\n if (config.storeUnwatchedWrites !== false) return true;\n if (fact.kind !== 'write') return true;\n if (loaded.size === 0) return true;\n for (const entry of loaded.values()) {\n const watched = factOf(entry.reflex.on);\n if (watched === undefined) continue;\n if (watched.entity === fact.entity && (watched.op === undefined || watched.op === fact.op)) return true;\n }\n return false;\n };\n\n const ingest = async (fact: FactInput, options?: { as?: string; cause?: string; depth?: number }): Promise<Fact | undefined> => {\n const result = FactInputSchema.safeParse(fact);\n if (!result.success)\n throw new TideError('invalid_fact', `fact did not parse: ${result.error.issues.map((i) => i.message).join('; ')}`, {\n issues: result.error.issues,\n });\n // Identity, cause and depth come from the second argument, never from the\n // fact: the fact is what a webhook body parses into, so whoever talks to\n // the host could choose them. A `cause` inside the fact is discarded.\n if (!watchable(result.data)) return undefined;\n const admission = await admitFact(config.store, { ...result.data, cause: options?.cause, depth: options?.depth ?? 0, as: options?.as }, deps.maxChainFacts);\n announceFact(deps.emit, admission);\n return 'stored' in admission ? admission.stored : undefined;\n };\n\n const advance = (options: AdvanceOptions): Promise<AdvanceReport> => runAdvance(deps, options);\n\n const fire = async (reflexId: string, options: { now: number; input?: unknown; by?: string }): Promise<Fact | undefined> => {\n if (!loaded.has(reflexId)) throw new TideError('unknown_reflex', `no reflex \"${reflexId}\" is loaded`);\n return ingest(\n { kind: 'manual', target: reflexId, payload: options.input, by: options.by ?? 'operator', at: options.now },\n { as: loaded.get(reflexId)?.reflex.as },\n );\n };\n\n const preview = (reflexId: string, options: PreviewOptions): Promise<PreviewReport> => previewReflex(deps, reflexId, options);\n\n const one = async <T extends 'run' | 'task' | 'fact'>(table: T, id: string) =>\n (await config.store.query({ table, where: { id } as never, limit: 1 }))[0];\n\n const causeChain = async (factId: string): Promise<readonly Fact[]> => {\n const chain: Fact[] = [];\n let current = await one('fact', factId);\n while (current !== undefined && chain.length < 64) {\n chain.push(current);\n const cause = current.cause;\n if (cause === undefined) break;\n const parentRunId = cause.startsWith('task:')\n ? (await one('task', cause.slice(5)))?.runId\n : cause.startsWith('run:')\n ? cause.slice(4)\n : undefined;\n if (parentRunId === undefined) break;\n const parentId = (await one('run', parentRunId))?.factIds?.[0];\n current = parentId === undefined ? undefined : await one('fact', parentId);\n }\n return chain;\n };\n\n return {\n load,\n reflexes: () => [...loaded.values()].map((entry) => entry.reflex),\n graph: () => buildGraph([...loaded.values()].map((entry) => entry.reflex), mergedEffects([...loaded.values()].map((e) => e.reflex))),\n\n ingest,\n advance,\n nextDue: (now) => computeNextDue(deps, now),\n\n fire,\n retry: (taskId, now) => reopenTask(deps, taskId, now),\n preview,\n\n ledger: {\n runs: (filter) =>\n config.store.query({\n table: 'run',\n where: filter?.reflexId === undefined ? undefined : { reflexId: filter.reflexId },\n order: [{ by: 'createdAt', dir: 'desc' }],\n limit: filter?.limit,\n }),\n run: (id) => one('run', id),\n tasks: (filter) =>\n config.store.query({\n table: 'task',\n where: {\n ...(filter?.runId === undefined ? {} : { runId: filter.runId }),\n ...(filter?.reflexId === undefined ? {} : { reflexId: filter.reflexId }),\n ...(filter?.state === undefined ? {} : { state: filter.state }),\n },\n order: [{ by: 'createdAt', dir: 'desc' }],\n limit: filter?.limit,\n }),\n task: (id) => one('task', id),\n facts: async (filter) => {\n const found = await config.store.query({\n table: 'fact',\n order: [{ by: 'at', dir: 'desc' }],\n limit: filter?.reflexId === undefined ? filter?.limit : undefined,\n });\n const matched = filter?.reflexId === undefined ? found : found.filter((fact) => fact.reflex === filter.reflexId || fact.target === filter.reflexId);\n return filter?.limit === undefined ? matched : matched.slice(0, filter.limit);\n },\n fact: (id) => one('fact', id),\n causeChain,\n // `released` as well: with `parked` alone cleared, the depth check would\n // park the fact again on the next advance.\n releaseParked: async (factId) => {\n const fact = await one('fact', factId);\n if (fact?.parked === undefined) return false;\n return config.store.cas('fact', factId, {}, { parked: undefined, released: true });\n },\n },\n\n sweep: async (now, retention) => {\n let removed = 0;\n if (retention.facts !== undefined)\n removed += await config.store.remove({ table: 'fact', where: { deliveredAt: { lt: now - retention.facts } } });\n if (retention.tasks !== undefined)\n removed += await config.store.remove({ table: 'task', where: { settledAt: { lt: now - retention.tasks } } });\n if (retention.runs !== undefined)\n removed += await config.store.remove({ table: 'run', where: { settledAt: { lt: now - retention.runs } } });\n return removed;\n },\n };\n};\n","import type { FactInput, Reflex, ReflexInput } from './schemas';\n\nexport type Row = Record<string, unknown>;\n\nexport type Fact = FactInput & {\n id: string;\n as?: string;\n depth: number;\n deliveredAt?: number;\n parked?: string;\n released?: boolean;\n root?: string;\n descendants?: number;\n};\n\nexport type RunState = 'pending' | 'fanned' | 'settled' | 'skipped';\n\nexport type Run = {\n id: string;\n reflexId: string;\n version: string;\n as?: string;\n cause: string;\n occurrence?: string;\n factIds?: readonly string[];\n state: RunState;\n depth: number;\n selected?: number;\n total: number;\n done: number;\n failed: number;\n dueAt: number;\n createdAt: number;\n settledAt?: number;\n // Set when no run fact is owed: the settlement has been emitted as one, or\n // the run was skipped. Apart from `settledAt`: a retried task settles its\n // run again, and that must not emit a second fact.\n drained?: boolean;\n note?: string;\n};\n\nexport type AttemptOutcome = 'ok' | 'error' | 'timeout';\n\nexport type TaskState = 'pending' | 'claimed' | 'retrying' | 'done' | 'failed';\n\nexport type Task = {\n id: string;\n runId: string;\n reflexId: string;\n unit: string;\n cause: string;\n // Frozen at fan-out: a retry evaluates against the data the selection saw.\n env: Row;\n depth: number;\n state: TaskState;\n attempt: number;\n token?: string;\n // Zero, not null, when unclaimed: \"never claimed or lapsed\" is then one\n // comparison, in a query grammar that has no OR.\n claimedUntil: number;\n notBefore: number;\n input?: unknown;\n output?: unknown;\n error?: string;\n createdAt: number;\n settledAt?: number;\n};\n\nexport type ReflexState = {\n reflexId: string;\n armedAt: number;\n materializedThrough?: number;\n};\n\nexport type TideCtx = {\n reflexId: string;\n runId: string;\n taskId: string;\n // The idempotency key a handler passes to an external provider: the same\n // on every attempt of the task.\n taskKey: string;\n attempt: number;\n depth: number;\n now: number;\n actor: unknown;\n emit: (fact: Omit<FactInput, 'cause'>) => void;\n};\n\nexport type EffectHandler = {\n run: (input: unknown, ctx: TideCtx) => Promise<unknown> | unknown;\n writes?: readonly string[];\n preview?: (input: unknown, ctx: PreviewCtx) => unknown;\n};\n\nexport type PreviewCtx = { reflexId: string; unit: string; now: number; actor: unknown };\n\nexport type EffectRegistry = Record<string, EffectHandler>;\n\nexport type TransformFn = (config: unknown, source: Row) => unknown;\n\nexport type SelectFn = (query: unknown, ctx: SelectCtx) => AsyncIterable<Row> | Iterable<Row> | Promise<Iterable<Row>>;\n\nexport type SelectCtx = { reflexId: string; now: number; actor: unknown; env: Row };\n\nexport type ActorFn = (as: string | undefined) => unknown;\n\nexport type Retention = Partial<Record<'facts' | 'runs' | 'tasks', number>>;\n\nexport type TideConfig = {\n store: TideStore;\n transform: TransformFn;\n select?: SelectFn;\n effects?: EffectRegistry | ((as: string | undefined) => EffectRegistry);\n actor?: ActorFn;\n maxChainDepth?: number;\n maxChainFacts?: number;\n storeUnwatchedWrites?: boolean;\n maxFanOut?: number;\n leaseMs?: number;\n onEvent?: (event: TideEvent) => void;\n};\n\nexport type TideEvent =\n | { type: 'run.created'; run: Run }\n | { type: 'run.settled'; run: Run }\n | { type: 'run.skipped'; reflexId: string; reason: string }\n | { type: 'run.deferred'; reflexId: string; runId: string; reason: string }\n | { type: 'task.done'; task: Task }\n | { type: 'task.failed'; task: Task }\n | { type: 'task.retrying'; task: Task; nextAt: number }\n | { type: 'task.reclaimed'; task: Task }\n | { type: 'fact.ingested'; fact: Fact }\n | { type: 'fact.deduped'; fact: NewFact }\n | { type: 'fact.parked'; fact: Fact; reason: string }\n | { type: 'fact.unmatched'; fact: Fact; reflexId: string; reason: string };\n\nexport type AdvanceReport = {\n now: number;\n materialized: number;\n skippedOccurrences: number;\n factsMatched: number;\n runsCreated: number;\n tasksCreated: number;\n executed: number;\n succeeded: number;\n failed: number;\n retrying: number;\n reclaimed: number;\n runsSettled: number;\n parked: number;\n};\n\nexport type LoadReport = {\n loaded: number;\n cycles: readonly { reflexIds: readonly string[]; guarded: boolean }[];\n blind: readonly { reflexId: string; effect: string }[];\n warnings: readonly string[];\n};\n\nexport type PreviewUnit = {\n unit: string;\n env: Row;\n input?: unknown;\n render?: unknown;\n error?: string;\n};\n\nexport type PreviewReport = {\n reflexId: string;\n version: string;\n fired: boolean;\n reason?: string;\n cause?: string;\n occurrence?: string;\n effect: string;\n selected: number;\n units: readonly PreviewUnit[];\n};\n\nexport type NewFact = FactInput & { depth: number; as?: string };\n\nexport type TideTables = {\n fact: Fact;\n run: Run;\n task: Task;\n state: ReflexState;\n};\n\nexport type TableName = keyof TideTables;\n\nexport const PRIMARY_KEY: { [T in TableName]: keyof TideTables[T] & string } = {\n fact: 'id',\n run: 'id',\n task: 'id',\n state: 'reflexId',\n};\n\nexport type UniqueKey<T extends TableName> = {\n by: readonly (keyof TideTables[T] & string)[];\n // The key applies only to rows that have this column set: in Postgres, a\n // partial unique index.\n when?: keyof TideTables[T] & string;\n};\n\nexport const UNIQUE_BY: { [T in TableName]: UniqueKey<T> } = {\n // `entity` is in the key: two polls over different tables can agree on a cursor value.\n fact: { by: ['kind', 'entity', 'name', 'dedupeKey'], when: 'dedupeKey' },\n run: { by: ['reflexId', 'cause'] },\n task: { by: ['runId', 'unit'] },\n state: { by: ['reflexId'] },\n};\n\nexport type Comparison<V> = {\n eq?: V;\n ne?: V;\n lt?: V;\n lte?: V;\n gt?: V;\n gte?: V;\n in?: readonly V[];\n notIn?: readonly V[];\n isNull?: boolean;\n};\n\nexport const COMPARISON_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'notIn', 'isNull'] as const;\n\nexport type Where<R> = { [K in keyof R]?: R[K] | Comparison<R[K]> };\n\nexport type Order<R> = readonly { by: keyof R & string; dir?: 'asc' | 'desc' }[];\n\nexport type QuerySpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n order?: Order<TideTables[T]>;\n limit?: number;\n};\n\nexport type Mutation<R> = { [K in keyof R]?: R[K] | { inc: number } };\n\nexport type ClaimSpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n order?: Order<TideTables[T]>;\n limit: number;\n set: Mutation<TideTables[T]>;\n // At most one row per value of `column` is held at a time, counting rows\n // matching `held` that an earlier claim took. Applies to the values in\n // `only`; every other value claims freely.\n onePer?: { column: keyof TideTables[T] & string; held: Where<TideTables[T]>; only: readonly string[] };\n};\n\nexport type RemoveSpec<T extends TableName = TableName> = {\n table: T;\n where?: Where<TideTables[T]>;\n};\n\nexport type TideStore = {\n transact: <T>(fn: (tx: TideStore) => Promise<T>) => Promise<T>;\n\n appendIfAbsent: <T extends TableName>(\n table: T,\n row: Omit<TideTables[T], 'id'> & { id?: string },\n ) => Promise<TideTables[T] | undefined>;\n\n claim: <T extends TableName>(spec: ClaimSpec<T>) => Promise<readonly TideTables[T][]>;\n\n cas: <T extends TableName>(\n table: T,\n id: string,\n expect: Where<TideTables[T]>,\n set: Mutation<TideTables[T]>,\n ) => Promise<boolean>;\n\n query: <T extends TableName>(spec: QuerySpec<T>) => Promise<readonly TideTables[T][]>;\n\n // Removing a run removes its tasks.\n remove: <T extends TableName>(spec: RemoveSpec<T>) => Promise<number>;\n};\n\nexport type { Reflex, ReflexInput, FactInput };\n","import { COMPARISON_OPS, PRIMARY_KEY, UNIQUE_BY } from '../types';\nimport type {\n ClaimSpec,\n Comparison,\n Fact,\n Mutation,\n Order,\n QuerySpec,\n ReflexState,\n RemoveSpec,\n Row,\n Run,\n TableName,\n Task,\n TideStore,\n TideTables,\n Where,\n} from '../types';\n\nexport type MemoryStore = TideStore & {\n snapshot: () => { facts: readonly Fact[]; runs: readonly Run[]; tasks: readonly Task[]; state: readonly ReflexState[] };\n};\n\nconst ID_PREFIX: Record<TableName, string> = { fact: 'fact', run: 'run', task: 'task', state: 'st' };\n\nconst isComparison = (value: unknown): value is Comparison<unknown> => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return false;\n const keys = Object.keys(value);\n return keys.length > 0 && keys.every((key) => (COMPARISON_OPS as readonly string[]).includes(key));\n};\n\nconst compare = (left: unknown, right: unknown): number => {\n if (typeof left === 'number' && typeof right === 'number') return left - right;\n return String(left) < String(right) ? -1 : String(left) > String(right) ? 1 : 0;\n};\n\nconst satisfies = (value: unknown, test: unknown): boolean => {\n if (!isComparison(test)) return value === test;\n const check = test;\n if (check.eq !== undefined && value !== check.eq) return false;\n if (check.ne !== undefined && value === check.ne) return false;\n if (check.lt !== undefined && !(value !== undefined && compare(value, check.lt) < 0)) return false;\n if (check.lte !== undefined && !(value !== undefined && compare(value, check.lte) <= 0)) return false;\n if (check.gt !== undefined && !(value !== undefined && compare(value, check.gt) > 0)) return false;\n if (check.gte !== undefined && !(value !== undefined && compare(value, check.gte) >= 0)) return false;\n if (check.in !== undefined && !check.in.includes(value as never)) return false;\n if (check.notIn !== undefined && check.notIn.includes(value as never)) return false;\n if (check.isNull !== undefined && (value === undefined || value === null) !== check.isNull) return false;\n return true;\n};\n\nconst matches = (row: Row, where: Where<Row> | undefined): boolean => {\n if (where === undefined) return true;\n for (const [column, test] of Object.entries(where)) if (!satisfies(row[column], test)) return false;\n return true;\n};\n\nconst sorted = <R extends Row>(rows: readonly R[], order: Order<Row> | undefined): R[] => {\n if (order === undefined || order.length === 0) return [...rows];\n return [...rows].sort((left, right) => {\n for (const key of order) {\n const result = compare(left[key.by], right[key.by]) * (key.dir === 'desc' ? -1 : 1);\n if (result !== 0) return result;\n }\n return 0;\n });\n};\n\nconst applied = <R extends Row>(row: R, set: Mutation<R>): R => {\n const next: Row = { ...row };\n for (const [column, value] of Object.entries(set)) {\n if (value !== null && typeof value === 'object' && 'inc' in value) {\n next[column] = Number(row[column] ?? 0) + Number((value as { inc: number }).inc);\n continue;\n }\n if (value === undefined) delete next[column];\n else next[column] = value;\n }\n return next as R;\n};\n\nexport const createMemoryStore = (): MemoryStore => {\n let tables: { [T in TableName]: Map<string, TideTables[T]> } = {\n fact: new Map(),\n run: new Map(),\n task: new Map(),\n state: new Map(),\n };\n\n let sequence = 0;\n\n const rowsOf = <T extends TableName>(table: T): TideTables[T][] => [...tables[table].values()];\n const keyOf = <T extends TableName>(table: T, row: TideTables[T]): string => String(row[PRIMARY_KEY[table]]);\n\n const query = async <T extends TableName>(spec: QuerySpec<T>): Promise<readonly TideTables[T][]> => {\n const found = sorted(\n rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined)),\n spec.order as unknown as Order<Row> | undefined,\n ) as TideTables[T][];\n return spec.limit === undefined ? found : found.slice(0, spec.limit);\n };\n\n const appendIfAbsent = async <T extends TableName>(\n table: T,\n input: Omit<TideTables[T], 'id'> & { id?: string },\n ): Promise<TideTables[T] | undefined> => {\n const unique = UNIQUE_BY[table];\n const candidate = input as unknown as Row;\n\n const guarded = unique.when === undefined || candidate[unique.when] !== undefined;\n if (guarded) {\n const collides = rowsOf(table).some((existing) =>\n unique.by.every((column) => (existing as unknown as Row)[column] === candidate[column]),\n );\n if (collides) return undefined;\n }\n\n sequence += 1;\n // An `undefined` value is not kept as a key, as on a row read back from a\n // database: a transform that looks at which keys a fact has sees the same\n // fact from either store.\n const given: Row = Object.fromEntries(Object.entries(candidate).filter(([, value]) => value !== undefined));\n const row = (PRIMARY_KEY[table] === 'id' ? { ...given, id: given.id ?? `${ID_PREFIX[table]}_${sequence}` } : given) as TideTables[T];\n tables[table].set(keyOf(table, row), row);\n return row;\n };\n\n const claim = async <T extends TableName>(spec: ClaimSpec<T>): Promise<readonly TideTables[T][]> => {\n const candidates = sorted(\n rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined)),\n spec.order as unknown as Order<Row> | undefined,\n ) as TideTables[T][];\n\n const taken = new Set<string>();\n const restricted = new Set(spec.onePer?.only ?? []);\n if (spec.onePer !== undefined)\n for (const row of rowsOf(spec.table))\n if (matches(row as Row, spec.onePer.held as Where<Row>)) taken.add(String((row as Row)[spec.onePer.column]));\n\n const claimed: TideTables[T][] = [];\n for (const row of candidates) {\n if (claimed.length >= spec.limit) break;\n if (spec.onePer !== undefined) {\n const group = String((row as Row)[spec.onePer.column]);\n if (restricted.has(group)) {\n if (taken.has(group)) continue;\n taken.add(group);\n }\n }\n const next = applied(row as Row, spec.set as Mutation<Row>) as TideTables[T];\n tables[spec.table].set(keyOf(spec.table, next), next);\n claimed.push(next);\n }\n return claimed;\n };\n\n const cas = async <T extends TableName>(\n table: T,\n id: string,\n expect: Where<TideTables[T]>,\n set: Mutation<TideTables[T]>,\n ): Promise<boolean> => {\n const row = tables[table].get(id);\n if (row === undefined || !matches(row as Row, expect as Where<Row>)) return false;\n tables[table].set(id, applied(row as Row, set as Mutation<Row>) as TideTables[T]);\n return true;\n };\n\n const remove = async <T extends TableName>(spec: RemoveSpec<T>): Promise<number> => {\n const doomed = rowsOf(spec.table).filter((row) => matches(row as Row, spec.where as Where<Row> | undefined));\n for (const row of doomed) {\n tables[spec.table].delete(keyOf(spec.table, row));\n if (spec.table === 'run')\n for (const task of rowsOf('task')) if (task.runId === (row as unknown as Run).id) tables.task.delete(task.id);\n }\n return doomed.length;\n };\n\n const transact = async <T>(fn: (tx: TideStore) => Promise<T>): Promise<T> => {\n const saved = { fact: new Map(tables.fact), run: new Map(tables.run), task: new Map(tables.task), state: new Map(tables.state) };\n try {\n return await fn(store);\n } catch (error) {\n tables = saved;\n throw error;\n }\n };\n\n const store: MemoryStore = {\n transact,\n appendIfAbsent,\n claim,\n cas,\n query,\n remove,\n snapshot: () => ({ facts: rowsOf('fact'), runs: rowsOf('run'), tasks: rowsOf('task'), state: rowsOf('state') }),\n };\n\n return store;\n};\n","import type { Tide } from './tide';\nimport type { AdvanceReport, Fact, Retention } from './types';\n\nexport type TideDriver = {\n ingest: Tide['ingest'];\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n wake: () => Promise<void>;\n stop: () => Promise<void>;\n};\n\nexport type TideDriverConfig = {\n tide: Tide;\n now?: () => number;\n janitorMs?: number;\n retention?: Retention;\n};\n\nconst DEFAULT_JANITOR_MS = 300_000;\nconst MAX_STEPS_PER_DRAIN = 10_000;\n\n// Node does not refuse a delay over 2^31 - 1 ms (24.8 days): it warns and waits 1 ms, which\n// would turn a far-off wake into a loop. Waking early costs one advance that finds nothing.\nconst LONGEST_TIMER_MS = 2 ** 31 - 1;\nconst waitable = (ms: number): number => Math.min(ms, LONGEST_TIMER_MS);\n\n// Asked of the value and not of its type, so this file needs no runtime's types: Node's timers\n// have `unref`, and a timer anywhere else is a number that holds nothing open.\nconst letProcessEnd = (timer: unknown): void => {\n if (typeof timer !== 'object' || timer === null || !('unref' in timer)) return;\n const unref: unknown = timer.unref;\n if (typeof unref === 'function') Reflect.apply(unref, timer, []);\n};\n\nconst progressOf = (report: AdvanceReport): number =>\n report.materialized +\n report.skippedOccurrences +\n report.factsMatched +\n report.runsCreated +\n report.tasksCreated +\n report.executed +\n report.reclaimed +\n report.runsSettled +\n report.parked;\n\nexport const createTideDriver = (config: TideDriverConfig): TideDriver => {\n const { tide } = config;\n const now = config.now ?? (() => Date.now());\n const janitorMs = waitable(config.janitorMs ?? DEFAULT_JANITOR_MS);\n\n let running = false;\n let queued = false;\n let stopped = false;\n let cycle: Promise<void> | undefined;\n let scheduling: Promise<void> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const drain = async (): Promise<void> => {\n for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {\n const report = await tide.advance({ now: now() });\n if (progressOf(report) === 0) return;\n }\n console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps — stopping this pass; the janitor will resume it`);\n };\n\n // Never rejects: it runs detached, and an unhandled rejection would take the host's process down.\n const schedule = async (): Promise<void> => {\n if (stopped) return;\n let due: number | undefined;\n try {\n due = await tide.nextDue(now());\n } catch (err) {\n if (!stopped) console.error('[tide:driver] next due', err);\n return;\n }\n if (stopped) return;\n if (timer !== undefined) clearTimeout(timer);\n if (due === undefined) return;\n const delay = due - now();\n // Still due after a drain means advance cannot progress it (facts waiting for reflexes\n // to load, say): retry on the janitor's beat, not in a hot loop.\n timer = setTimeout(() => void wake(), delay > 0 ? waitable(delay) : janitorMs);\n letProcessEnd(timer);\n };\n\n const wake = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n queued = true;\n if (running) return cycle ?? Promise.resolve();\n running = true;\n cycle = (async () => {\n try {\n while (queued) {\n queued = false;\n await drain();\n }\n } catch (err) {\n console.error('[tide:driver]', err);\n } finally {\n running = false;\n cycle = undefined;\n scheduling = schedule();\n }\n })();\n return cycle;\n };\n\n const janitor = setInterval(() => {\n if (config.retention !== undefined) {\n void tide.sweep(now(), config.retention).catch((err) => console.error('[tide:driver] sweep', err));\n }\n void wake();\n }, janitorMs);\n letProcessEnd(janitor);\n\n return {\n ingest: async (fact, options) => {\n const stored = await tide.ingest(fact, options);\n if (stored !== undefined) void wake();\n return stored;\n },\n fire: async (reflexId, options) => {\n const fact = await tide.fire(reflexId, options);\n void wake();\n return fact;\n },\n wake,\n stop: async () => {\n stopped = true;\n clearInterval(janitor);\n if (timer !== undefined) clearTimeout(timer);\n await cycle;\n await scheduling;\n },\n };\n};\n","import { ReflexSchema } from '../schemas';\nimport type { Reflex, ReflexDraft, Timer } from '../schemas';\nimport { zonedParts } from './occurrence';\n\nexport const timerMs = (timer: Timer): number => (((timer.hours ?? 0) * 60 + (timer.minutes ?? 0)) * 60 + (timer.seconds ?? 0)) * 1000;\n\nconst pad2 = (value: number): string => String(value).padStart(2, '0');\n\nconst localDateTime = (instant: number, tz: string): string => {\n const p = zonedParts(instant, tz);\n return `${p.year}-${pad2(p.month)}-${pad2(p.day)}T${pad2(p.hour)}:${pad2(p.minute)}:${pad2(p.second)}`;\n};\n\nexport const anchorDraft = (draft: ReflexDraft, anchor: { at: number; tz: string }): Reflex => {\n if (!('timer' in draft.on)) return ReflexSchema.parse(draft);\n // A clock names whole seconds. Rounded up: a timer may run a fraction of a\n // second long, never short.\n const fires = Math.ceil((anchor.at + timerMs(draft.on.timer)) / 1000) * 1000;\n return ReflexSchema.parse({ ...draft, on: { clock: { at: localDateTime(fires, anchor.tz), tz: anchor.tz } } });\n};\n"]}
|