@niscorp/tide 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/DESIGN.md +4 -4
- package/DOCS.md +22 -4
- package/dist/agent.cjs +3 -9
- package/dist/agent.cjs.map +1 -1
- package/dist/agent.js +1 -3
- package/dist/agent.js.map +1 -1
- package/dist/{chunk-UEG3UZDG.js → chunk-4TXWZFRE.js} +5 -13
- package/dist/chunk-4TXWZFRE.js.map +1 -0
- package/dist/{chunk-4CUQXWVY.js → chunk-7KHOAJNL.js} +3 -4
- package/dist/chunk-7KHOAJNL.js.map +1 -0
- package/dist/index.cjs +12 -64
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +12 -55
- package/dist/index.js.map +1 -1
- package/dist/postgres.cjs +1 -7
- package/dist/postgres.cjs.map +1 -1
- package/dist/postgres.js +2 -3
- package/dist/postgres.js.map +1 -1
- 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 +5 -5
- package/dist/chunk-4CUQXWVY.js.map +0 -1
- package/dist/chunk-UEG3UZDG.js.map +0 -1
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":";AA2BA,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EAChC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF,CAAA;AAEA,IAAM,MAAA,GAAS,CAAC,SAAA,EAAoB,OAAA,KAA0B;AAC5D,EAAA,IAAI,CAAC,SAAA,EAAW,MAAM,IAAI,cAAc,OAAO,CAAA;AACjD,CAAA;AAEA,IAAM,KAAA,GAAQ,CAAC,MAAA,EAAiB,QAAA,EAAmB,SAC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AA,CAAA,CAAO,MAAM,KAAA,CAAM,KAAA,CAAM,EAAE,KAAA,EAAO,KAAA,EAAO,CAAA,EAAG,CAAC,CAAA,EAAG,KAAA,EAAO,QAAA,EAAU,2BAA2B,CAAA;AAAA,IAC9F;AAAA;AAEJ","file":"testing.js","sourcesContent":["import type { Run, Task, TideStore } from './types';\n\n// ═══════════════════════════════════════════════════════════════\n// THE STORE CONTRACT, AS EXECUTABLE CHECKS\n//\n// Shipped from the package rather than left in `test/`, because the\n// contract is not tide's private business: anyone implementing a\n// store — moss over vex, a host over its own pool — has to be able\n// to run the same checks tide holds its own reference store to.\n//\n// This exists because the last Postgres store claimed in its header\n// to be \"held to the same tests\" and had none. It diverged from the\n// memory store in eleven ways: LIMIT applied before the serial\n// filter, `listFacts` answering the opposite end of the list, a\n// dedupe index that outlived its rows, `total` counted from the\n// input array rather than the rows written. Every one of those was\n// invisible because there was nothing to run.\n//\n// No test framework. Each check is a function that throws, so any\n// runner can drive it:\n//\n// for (const check of STORE_CONTRACT)\n// it(check.name, () => check.run(makeStore()));\n// ═══════════════════════════════════════════════════════════════\n\nexport type StoreCheck = { name: string; run: (store: TideStore) => Promise<void> };\n\nclass ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ContractError';\n }\n}\n\nconst assert = (condition: boolean, message: string): void => {\n if (!condition) throw new ContractError(message);\n};\n\nconst equal = (actual: unknown, expected: unknown, what: string): void =>\n assert(actual === expected, `${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);\n\n// A minimal task, so a check reads as the thing it is checking rather than as\n// a wall of required fields.\nconst task = (over: Partial<Task> = {}): Omit<Task, 'id'> & { id?: string } => ({\n runId: 'run_1',\n reflexId: 'r',\n unit: 'u1',\n cause: 'manual:test',\n env: {},\n depth: 0,\n state: 'pending' as const,\n attempt: 0,\n claimedUntil: 0,\n notBefore: 0,\n createdAt: 0,\n ...over,\n});\n\nconst run = (over: Partial<Run> = {}): Omit<Run, 'id'> & { id?: string } => ({\n reflexId: 'r',\n version: 'v_0',\n cause: 'occurrence:2026-03-01',\n state: 'pending' as const,\n depth: 0,\n total: 0,\n done: 0,\n failed: 0,\n dueAt: 0,\n createdAt: 0,\n ...over,\n});\n\n// A task belongs to a run, and a store is entitled to enforce that — the SQL\n// one does, with a foreign key, which is what makes `remove` cascade. So\n// every check that wants work opens the run that owns it first.\nconst withRuns = async (store: TideStore, ...ids: readonly string[]): Promise<void> => {\n for (const id of ids) await store.appendIfAbsent('run', run({ id, cause: `occurrence:${id}` }));\n};\n\nexport const STORE_CONTRACT: readonly StoreCheck[] = [\n // ── appendIfAbsent ───────────────────────────────────────────\n\n {\n name: 'appendIfAbsent mints an id and returns the stored row',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run());\n assert(stored !== undefined, 'the first append must succeed');\n assert(typeof stored?.id === 'string' && stored.id.length > 0, 'the store mints the id');\n equal((await store.query({ table: 'run' })).length, 1, 'rows after one append');\n },\n },\n {\n name: 'appendIfAbsent refuses a duplicate on the unique key — this IS the idempotency',\n run: async (store) => {\n await store.appendIfAbsent('run', run());\n const second = await store.appendIfAbsent('run', run({ note: 'a different note' }));\n equal(second, undefined, 'a colliding append is a refusal, not an error');\n equal((await store.query({ table: 'run' })).length, 1, 'rows after the collision');\n },\n },\n {\n name: 'a different cause on the same reflex is a different run',\n run: async (store) => {\n await store.appendIfAbsent('run', run());\n const second = await store.appendIfAbsent('run', run({ cause: 'occurrence:2026-03-02' }));\n assert(second !== undefined, 'a distinct occurrence must open');\n },\n },\n {\n name: 'UNIQUE(runId, unit) — the grain the effect is written behind',\n run: async (store) => {\n await withRuns(store, 'run_1', 'run_2');\n await store.appendIfAbsent('task', task());\n equal(await store.appendIfAbsent('task', task()), undefined, 'the same unit twice is refused');\n assert((await store.appendIfAbsent('task', task({ unit: 'u2' }))) !== undefined, 'a different unit is a different task');\n assert((await store.appendIfAbsent('task', task({ runId: 'run_2' }))) !== undefined, 'the same unit in another run is another task');\n },\n },\n {\n name: 'a fact with no dedupeKey is never a duplicate',\n run: async (store) => {\n const one = { kind: 'signal' as const, name: 'ping', at: 1, depth: 0 };\n assert((await store.appendIfAbsent('fact', one)) !== undefined, 'first');\n assert((await store.appendIfAbsent('fact', one)) !== undefined, 'a fact claiming no identity is a distinct occurrence');\n equal((await store.query({ table: 'fact' })).length, 2, 'both are kept');\n },\n },\n {\n name: 'a fact WITH a dedupeKey is deduped, and entity is part of the key',\n run: async (store) => {\n const paid = { kind: 'write' as const, entity: 'payments', at: 1, depth: 0, dedupeKey: 'evt_1' };\n assert((await store.appendIfAbsent('fact', paid)) !== undefined, 'first');\n equal(await store.appendIfAbsent('fact', paid), undefined, 'a replayed provider event drops silently');\n // The old index was (kind, name, dedupe_key) and ignored `entity`, so\n // two producers over different tables that agreed on a key value ate\n // each other's rows.\n assert((await store.appendIfAbsent('fact', { ...paid, entity: 'refunds' })) !== undefined, 'another entity is another fact');\n },\n },\n\n // ── claim ────────────────────────────────────────────────────\n\n {\n name: 'claim takes a row exactly once',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task());\n const first = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 10, set: { state: 'claimed', token: 't1' } });\n const second = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 10, set: { state: 'claimed', token: 't2' } });\n equal(first.length, 1, 'the first claim takes it');\n equal(second.length, 0, 'the second finds nothing — this is the whole promise');\n equal(first[0]?.token, 't1', 'the claim returns the row as written');\n },\n },\n {\n name: 'claim increments in one step, so a poison pill cannot retry forever',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ attempt: 2 }));\n const [claimed] = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 1, set: { state: 'claimed', attempt: { inc: 1 } } });\n equal(claimed?.attempt, 3, 'attempt rises with the claim, not after the effect');\n },\n },\n {\n name: 'claim honours limit and order',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ unit: 'late', notBefore: 100 }));\n await store.appendIfAbsent('task', task({ unit: 'early', notBefore: 1 }));\n const claimed = await store.claim({\n table: 'task',\n where: { state: 'pending' },\n order: [{ by: 'notBefore' }],\n limit: 1,\n set: { state: 'claimed' },\n });\n equal(claimed.length, 1, 'limit is respected');\n equal(claimed[0]?.unit, 'early', 'the oldest due work goes first');\n },\n },\n {\n name: 'a lapsed lease is claimable again — the only recovery a dead process needs',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ state: 'claimed', token: 'gone', claimedUntil: 50 }));\n const alive = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying', 'claimed'] }, notBefore: { lte: 40 }, claimedUntil: { lte: 40 } },\n limit: 10,\n set: { state: 'claimed', token: 'fresh' },\n });\n equal(alive.length, 0, 'a live lease is not stealable');\n\n const lapsed = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying', 'claimed'] }, notBefore: { lte: 60 }, claimedUntil: { lte: 60 } },\n limit: 10,\n set: { state: 'claimed', token: 'fresh' },\n });\n equal(lapsed.length, 1, 'a lapsed lease is taken back');\n equal(lapsed[0]?.token, 'fresh', 'and fenced under a new token');\n },\n },\n {\n name: 'onePer holds one row per group, counting what is already held',\n run: async (store) => {\n // Two serial reflexes with two units each, and one of them already busy.\n await withRuns(store, 'a', 'b', 'c');\n await store.appendIfAbsent('task', task({ runId: 'a', unit: 'a1', reflexId: 'serial.a' }));\n await store.appendIfAbsent('task', task({ runId: 'a', unit: 'a2', reflexId: 'serial.a' }));\n await store.appendIfAbsent('task', task({ runId: 'b', unit: 'b1', reflexId: 'serial.b', state: 'claimed', claimedUntil: 900 }));\n await store.appendIfAbsent('task', task({ runId: 'b', unit: 'b2', reflexId: 'serial.b' }));\n await store.appendIfAbsent('task', task({ runId: 'c', unit: 'c1', reflexId: 'parallel' }));\n await store.appendIfAbsent('task', task({ runId: 'c', unit: 'c2', reflexId: 'parallel' }));\n\n const claimed = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying'] }, notBefore: { lte: 100 } },\n order: [{ by: 'unit' }],\n limit: 10,\n set: { state: 'claimed', claimedUntil: 900 },\n onePer: { column: 'reflexId', held: { state: 'claimed', claimedUntil: { gt: 100 } }, only: ['serial.a', 'serial.b'] },\n });\n\n const byReflex = (id: string) => claimed.filter((row) => row.reflexId === id).length;\n equal(byReflex('serial.a'), 1, 'one at a time, within the claim');\n equal(byReflex('serial.b'), 0, 'none — its slot is already held by an earlier claim');\n equal(byReflex('parallel'), 2, 'a reflex outside `only` claims freely');\n },\n },\n\n // ── cas ──────────────────────────────────────────────────────\n\n {\n name: 'cas moves a row only from the state it expected — this is the fence',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const stored = await store.appendIfAbsent('task', task({ state: 'claimed', token: 'live' }));\n const id = stored?.id ?? '';\n equal(await store.cas('task', id, { token: 'stale' }, { state: 'done' }), false, 'a superseded attempt is refused');\n equal((await store.query({ table: 'task', where: { id } }))[0]?.state, 'claimed', 'and changed nothing');\n equal(await store.cas('task', id, { token: 'live' }, { state: 'done' }), true, 'the live attempt lands');\n equal((await store.query({ table: 'task', where: { id } }))[0]?.state, 'done', 'and is written');\n },\n },\n {\n name: 'cas on a row that is not there is false, not a throw',\n run: async (store) => {\n equal(await store.cas('task', 'nope', {}, { state: 'done' }), false, 'a missing row is a refusal');\n },\n },\n {\n name: 'setting undefined CLEARS a column',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const stored = await store.appendIfAbsent('task', task({ state: 'claimed', token: 'live' }));\n await store.cas('task', stored?.id ?? '', {}, { token: undefined });\n const [after] = await store.query({ table: 'task', where: { id: stored?.id ?? '' } });\n equal(after?.token, undefined, 'a settled task holds no token');\n },\n },\n\n // ── query ────────────────────────────────────────────────────\n\n {\n name: 'query filters, compares, orders and limits',\n run: async (store) => {\n await store.appendIfAbsent('run', run({ cause: 'a', createdAt: 30, state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'b', createdAt: 10, state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'c', createdAt: 20, state: 'pending' }));\n\n const settled = await store.query({ table: 'run', where: { state: 'settled' } });\n equal(settled.length, 2, 'equality');\n\n const recent = await store.query({ table: 'run', where: { createdAt: { gte: 20 } } });\n equal(recent.length, 2, 'comparison');\n\n const oneOf = await store.query({ table: 'run', where: { state: { in: ['pending'] } } });\n equal(oneOf.length, 1, 'in');\n\n const newest = await store.query({ table: 'run', order: [{ by: 'createdAt', dir: 'desc' }], limit: 1 });\n equal(newest[0]?.cause, 'a', 'a limit means the most recent N, in every store');\n },\n },\n {\n name: 'isNull distinguishes absent from present',\n run: async (store) => {\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'one', at: 1, depth: 0 });\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'two', at: 2, depth: 0, deliveredAt: 5 });\n equal((await store.query({ table: 'fact', where: { deliveredAt: { isNull: true } } })).length, 1, 'undelivered');\n equal((await store.query({ table: 'fact', where: { deliveredAt: { isNull: false } } })).length, 1, 'delivered');\n },\n },\n {\n name: 'ne treats an absent column as not-equal',\n run: async (store) => {\n await store.appendIfAbsent('run', run({ cause: 'fresh', state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'announced', state: 'settled', drained: true }));\n const undrained = await store.query({ table: 'run', where: { state: 'settled', drained: { ne: true } } });\n equal(undrained.length, 1, 'a run that has never been drained is not drained');\n equal(undrained[0]?.cause, 'fresh', 'and it is the right one');\n },\n },\n\n // ── remove ───────────────────────────────────────────────────\n\n {\n name: 'remove deletes what matches and counts it',\n run: async (store) => {\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'old', at: 1, depth: 0, deliveredAt: 1 });\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'new', at: 90, depth: 0, deliveredAt: 90 });\n equal(await store.remove({ table: 'fact', where: { deliveredAt: { lt: 50 } } }), 1, 'removed');\n equal((await store.query({ table: 'fact' })).length, 1, 'kept');\n },\n },\n {\n name: 'removing a run takes its tasks with it',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run({ state: 'settled', settledAt: 1 }));\n await store.appendIfAbsent('task', task({ runId: stored?.id ?? '' }));\n await store.remove({ table: 'run', where: { settledAt: { lt: 50 } } });\n // Keeping the tasks would destroy the UNIQUE(runId, unit) row that IS\n // the \"this unit already ran\" record — and a restore then re-charges\n // the invoice.\n equal((await store.query({ table: 'task' })).length, 0, 'orphans are not left behind');\n },\n },\n\n // ── transact ─────────────────────────────────────────────────\n\n {\n name: 'a throwing transaction leaves nothing behind',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const before = (await store.query({ table: 'task' })).length;\n let raised: unknown;\n try {\n await store.transact(async (tx) => {\n await tx.appendIfAbsent('task', task({ unit: 'a' }));\n await tx.appendIfAbsent('task', task({ unit: 'b' }));\n throw new Error('the selection died half way through');\n });\n } catch (error) {\n raised = error;\n }\n // THE CALLER'S error, not merely SOME error. A store whose transaction\n // is broken outright also throws and also writes nothing, which is how\n // a check for \"it threw\" passes against an implementation that never\n // opened a transaction at all.\n equal((raised as Error | undefined)?.message, 'the selection died half way through', 'the caller’s error propagates unchanged');\n equal((await store.query({ table: 'task' })).length, before, 'and nothing was written — fan-out depends on this');\n },\n },\n {\n name: 'a transaction that returns commits everything in it',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run());\n await store.transact(async (tx) => {\n await tx.appendIfAbsent('task', task({ runId: stored?.id ?? '', unit: 'a' }));\n await tx.cas('run', stored?.id ?? '', { state: 'pending' }, { state: 'fanned', total: 1 });\n });\n equal((await store.query({ table: 'task' })).length, 1, 'the task landed');\n equal((await store.query({ table: 'run' }))[0]?.state, 'fanned', 'with the run that owns it');\n },\n },\n];\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":";AAIA,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EAChC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAA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AA,EAAO,GAAG,CAAA;AAAA,MAC3F,CAAC,CAAA;AACD,MAAA,KAAA,CAAA,CAAO,MAAM,KAAA,CAAM,KAAA,CAAM,EAAE,KAAA,EAAO,QAAQ,CAAA,EAAG,MAAA,EAAQ,CAAA,EAAG,iBAAiB,CAAA;AACzE,MAAA,KAAA,CAAA,CAAO,MAAM,KAAA,CAAM,KAAA,CAAM,EAAE,KAAA,EAAO,KAAA,EAAO,CAAA,EAAG,CAAC,CAAA,EAAG,KAAA,EAAO,QAAA,EAAU,2BAA2B,CAAA;AAAA,IAC9F;AAAA;AAEJ","file":"testing.js","sourcesContent":["import type { Run, Task, TideStore } from './types';\n\nexport type StoreCheck = { name: string; run: (store: TideStore) => Promise<void> };\n\nclass ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ContractError';\n }\n}\n\nconst assert = (condition: boolean, message: string): void => {\n if (!condition) throw new ContractError(message);\n};\n\nconst equal = (actual: unknown, expected: unknown, what: string): void =>\n assert(actual === expected, `${what}: expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);\n\nconst task = (over: Partial<Task> = {}): Omit<Task, 'id'> & { id?: string } => ({\n runId: 'run_1',\n reflexId: 'r',\n unit: 'u1',\n cause: 'manual:test',\n env: {},\n depth: 0,\n state: 'pending' as const,\n attempt: 0,\n claimedUntil: 0,\n notBefore: 0,\n createdAt: 0,\n ...over,\n});\n\nconst run = (over: Partial<Run> = {}): Omit<Run, 'id'> & { id?: string } => ({\n reflexId: 'r',\n version: 'v_0',\n cause: 'occurrence:2026-03-01',\n state: 'pending' as const,\n depth: 0,\n total: 0,\n done: 0,\n failed: 0,\n dueAt: 0,\n createdAt: 0,\n ...over,\n});\n\n// A store may enforce that a task's run exists (the SQL one does, with a\n// foreign key), so a check that wants a task opens its run first.\nconst withRuns = async (store: TideStore, ...ids: readonly string[]): Promise<void> => {\n for (const id of ids) await store.appendIfAbsent('run', run({ id, cause: `occurrence:${id}` }));\n};\n\nexport const STORE_CONTRACT: readonly StoreCheck[] = [\n {\n name: 'appendIfAbsent mints an id and returns the stored row',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run());\n assert(stored !== undefined, 'the first append must succeed');\n assert(typeof stored?.id === 'string' && stored.id.length > 0, 'the store mints the id');\n equal((await store.query({ table: 'run' })).length, 1, 'rows after one append');\n },\n },\n {\n name: 'appendIfAbsent refuses a duplicate on the unique key — this IS the idempotency',\n run: async (store) => {\n await store.appendIfAbsent('run', run());\n const second = await store.appendIfAbsent('run', run({ note: 'a different note' }));\n equal(second, undefined, 'a colliding append is a refusal, not an error');\n equal((await store.query({ table: 'run' })).length, 1, 'rows after the collision');\n },\n },\n {\n name: 'a different cause on the same reflex is a different run',\n run: async (store) => {\n await store.appendIfAbsent('run', run());\n const second = await store.appendIfAbsent('run', run({ cause: 'occurrence:2026-03-02' }));\n assert(second !== undefined, 'a distinct occurrence must open');\n },\n },\n {\n name: 'UNIQUE(runId, unit) — the grain the effect is written behind',\n run: async (store) => {\n await withRuns(store, 'run_1', 'run_2');\n await store.appendIfAbsent('task', task());\n equal(await store.appendIfAbsent('task', task()), undefined, 'the same unit twice is refused');\n assert((await store.appendIfAbsent('task', task({ unit: 'u2' }))) !== undefined, 'a different unit is a different task');\n assert((await store.appendIfAbsent('task', task({ runId: 'run_2' }))) !== undefined, 'the same unit in another run is another task');\n },\n },\n {\n name: 'a fact with no dedupeKey is never a duplicate',\n run: async (store) => {\n const one = { kind: 'signal' as const, name: 'ping', at: 1, depth: 0 };\n assert((await store.appendIfAbsent('fact', one)) !== undefined, 'first');\n assert((await store.appendIfAbsent('fact', one)) !== undefined, 'a fact claiming no identity is a distinct occurrence');\n equal((await store.query({ table: 'fact' })).length, 2, 'both are kept');\n },\n },\n {\n name: 'a fact WITH a dedupeKey is deduped, and entity is part of the key',\n run: async (store) => {\n const paid = { kind: 'write' as const, entity: 'payments', at: 1, depth: 0, dedupeKey: 'evt_1' };\n assert((await store.appendIfAbsent('fact', paid)) !== undefined, 'first');\n equal(await store.appendIfAbsent('fact', paid), undefined, 'a replayed provider event drops silently');\n assert((await store.appendIfAbsent('fact', { ...paid, entity: 'refunds' })) !== undefined, 'another entity is another fact');\n },\n },\n\n {\n name: 'claim takes a row exactly once',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task());\n const first = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 10, set: { state: 'claimed', token: 't1' } });\n const second = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 10, set: { state: 'claimed', token: 't2' } });\n equal(first.length, 1, 'the first claim takes it');\n equal(second.length, 0, 'the second finds nothing — this is the whole promise');\n equal(first[0]?.token, 't1', 'the claim returns the row as written');\n },\n },\n {\n name: 'claim increments in one step, so a poison pill cannot retry forever',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ attempt: 2 }));\n const [claimed] = await store.claim({ table: 'task', where: { state: 'pending' }, limit: 1, set: { state: 'claimed', attempt: { inc: 1 } } });\n equal(claimed?.attempt, 3, 'attempt rises with the claim, not after the effect');\n },\n },\n {\n name: 'claim honours limit and order',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ unit: 'late', notBefore: 100 }));\n await store.appendIfAbsent('task', task({ unit: 'early', notBefore: 1 }));\n const claimed = await store.claim({\n table: 'task',\n where: { state: 'pending' },\n order: [{ by: 'notBefore' }],\n limit: 1,\n set: { state: 'claimed' },\n });\n equal(claimed.length, 1, 'limit is respected');\n equal(claimed[0]?.unit, 'early', 'the oldest due work goes first');\n },\n },\n {\n name: 'a lapsed lease is claimable again — the only recovery a dead process needs',\n run: async (store) => {\n await withRuns(store, 'run_1');\n await store.appendIfAbsent('task', task({ state: 'claimed', token: 'gone', claimedUntil: 50 }));\n const alive = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying', 'claimed'] }, notBefore: { lte: 40 }, claimedUntil: { lte: 40 } },\n limit: 10,\n set: { state: 'claimed', token: 'fresh' },\n });\n equal(alive.length, 0, 'a live lease is not stealable');\n\n const lapsed = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying', 'claimed'] }, notBefore: { lte: 60 }, claimedUntil: { lte: 60 } },\n limit: 10,\n set: { state: 'claimed', token: 'fresh' },\n });\n equal(lapsed.length, 1, 'a lapsed lease is taken back');\n equal(lapsed[0]?.token, 'fresh', 'and fenced under a new token');\n },\n },\n {\n name: 'onePer holds one row per group, counting what is already held',\n run: async (store) => {\n await withRuns(store, 'a', 'b', 'c');\n await store.appendIfAbsent('task', task({ runId: 'a', unit: 'a1', reflexId: 'serial.a' }));\n await store.appendIfAbsent('task', task({ runId: 'a', unit: 'a2', reflexId: 'serial.a' }));\n await store.appendIfAbsent('task', task({ runId: 'b', unit: 'b1', reflexId: 'serial.b', state: 'claimed', claimedUntil: 900 }));\n await store.appendIfAbsent('task', task({ runId: 'b', unit: 'b2', reflexId: 'serial.b' }));\n await store.appendIfAbsent('task', task({ runId: 'c', unit: 'c1', reflexId: 'parallel' }));\n await store.appendIfAbsent('task', task({ runId: 'c', unit: 'c2', reflexId: 'parallel' }));\n\n const claimed = await store.claim({\n table: 'task',\n where: { state: { in: ['pending', 'retrying'] }, notBefore: { lte: 100 } },\n order: [{ by: 'unit' }],\n limit: 10,\n set: { state: 'claimed', claimedUntil: 900 },\n onePer: { column: 'reflexId', held: { state: 'claimed', claimedUntil: { gt: 100 } }, only: ['serial.a', 'serial.b'] },\n });\n\n const byReflex = (id: string) => claimed.filter((row) => row.reflexId === id).length;\n equal(byReflex('serial.a'), 1, 'one at a time, within the claim');\n equal(byReflex('serial.b'), 0, 'none — its slot is already held by an earlier claim');\n equal(byReflex('parallel'), 2, 'a reflex outside `only` claims freely');\n },\n },\n\n {\n name: 'cas moves a row only from the state it expected — this is the fence',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const stored = await store.appendIfAbsent('task', task({ state: 'claimed', token: 'live' }));\n const id = stored?.id ?? '';\n equal(await store.cas('task', id, { token: 'stale' }, { state: 'done' }), false, 'a superseded attempt is refused');\n equal((await store.query({ table: 'task', where: { id } }))[0]?.state, 'claimed', 'and changed nothing');\n equal(await store.cas('task', id, { token: 'live' }, { state: 'done' }), true, 'the live attempt lands');\n equal((await store.query({ table: 'task', where: { id } }))[0]?.state, 'done', 'and is written');\n },\n },\n {\n name: 'cas on a row that is not there is false, not a throw',\n run: async (store) => {\n equal(await store.cas('task', 'nope', {}, { state: 'done' }), false, 'a missing row is a refusal');\n },\n },\n {\n name: 'setting undefined CLEARS a column',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const stored = await store.appendIfAbsent('task', task({ state: 'claimed', token: 'live' }));\n await store.cas('task', stored?.id ?? '', {}, { token: undefined });\n const [after] = await store.query({ table: 'task', where: { id: stored?.id ?? '' } });\n equal(after?.token, undefined, 'a settled task holds no token');\n },\n },\n\n {\n name: 'query filters, compares, orders and limits',\n run: async (store) => {\n await store.appendIfAbsent('run', run({ cause: 'a', createdAt: 30, state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'b', createdAt: 10, state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'c', createdAt: 20, state: 'pending' }));\n\n const settled = await store.query({ table: 'run', where: { state: 'settled' } });\n equal(settled.length, 2, 'equality');\n\n const recent = await store.query({ table: 'run', where: { createdAt: { gte: 20 } } });\n equal(recent.length, 2, 'comparison');\n\n const oneOf = await store.query({ table: 'run', where: { state: { in: ['pending'] } } });\n equal(oneOf.length, 1, 'in');\n\n const newest = await store.query({ table: 'run', order: [{ by: 'createdAt', dir: 'desc' }], limit: 1 });\n equal(newest[0]?.cause, 'a', 'a limit means the most recent N, in every store');\n },\n },\n {\n name: 'isNull distinguishes absent from present',\n run: async (store) => {\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'one', at: 1, depth: 0 });\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'two', at: 2, depth: 0, deliveredAt: 5 });\n equal((await store.query({ table: 'fact', where: { deliveredAt: { isNull: true } } })).length, 1, 'undelivered');\n equal((await store.query({ table: 'fact', where: { deliveredAt: { isNull: false } } })).length, 1, 'delivered');\n },\n },\n {\n name: 'ne treats an absent column as not-equal',\n run: async (store) => {\n await store.appendIfAbsent('run', run({ cause: 'fresh', state: 'settled' }));\n await store.appendIfAbsent('run', run({ cause: 'announced', state: 'settled', drained: true }));\n const undrained = await store.query({ table: 'run', where: { state: 'settled', drained: { ne: true } } });\n equal(undrained.length, 1, 'a run that has never been drained is not drained');\n equal(undrained[0]?.cause, 'fresh', 'and it is the right one');\n },\n },\n\n {\n name: 'remove deletes what matches and counts it',\n run: async (store) => {\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'old', at: 1, depth: 0, deliveredAt: 1 });\n await store.appendIfAbsent('fact', { kind: 'signal', name: 'new', at: 90, depth: 0, deliveredAt: 90 });\n equal(await store.remove({ table: 'fact', where: { deliveredAt: { lt: 50 } } }), 1, 'removed');\n equal((await store.query({ table: 'fact' })).length, 1, 'kept');\n },\n },\n {\n name: 'removing a run takes its tasks with it',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run({ state: 'settled', settledAt: 1 }));\n await store.appendIfAbsent('task', task({ runId: stored?.id ?? '' }));\n await store.remove({ table: 'run', where: { settledAt: { lt: 50 } } });\n equal((await store.query({ table: 'task' })).length, 0, 'orphans are not left behind');\n },\n },\n\n {\n name: 'a throwing transaction leaves nothing behind',\n run: async (store) => {\n await withRuns(store, 'run_1');\n const before = (await store.query({ table: 'task' })).length;\n let raised: unknown;\n try {\n await store.transact(async (tx) => {\n await tx.appendIfAbsent('task', task({ unit: 'a' }));\n await tx.appendIfAbsent('task', task({ unit: 'b' }));\n throw new Error('the selection died half way through');\n });\n } catch (error) {\n raised = error;\n }\n // The caller's own error, not just any: a store whose transaction is\n // broken outright also throws and also writes nothing.\n equal((raised as Error | undefined)?.message, 'the selection died half way through', 'the caller’s error propagates unchanged');\n equal((await store.query({ table: 'task' })).length, before, 'and nothing was written — fan-out depends on this');\n },\n },\n {\n name: 'a transaction that returns commits everything in it',\n run: async (store) => {\n const stored = await store.appendIfAbsent('run', run());\n await store.transact(async (tx) => {\n await tx.appendIfAbsent('task', task({ runId: stored?.id ?? '', unit: 'a' }));\n await tx.cas('run', stored?.id ?? '', { state: 'pending' }, { state: 'fanned', total: 1 });\n });\n equal((await store.query({ table: 'task' })).length, 1, 'the task landed');\n equal((await store.query({ table: 'run' }))[0]?.state, 'fanned', 'with the run that owns it');\n },\n },\n];\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@niscorp/tide",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.7",
|
|
4
4
|
"description": "Host-blind automation engine — a reflex turns the clock and the fact into one named effect, through a durable ledger.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -66,8 +66,8 @@
|
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
68
|
"zod": "^4.2.0",
|
|
69
|
-
"@niscorp/cortex": "^0.1.
|
|
70
|
-
"@niscorp/strata": "^0.1.
|
|
69
|
+
"@niscorp/cortex": "^0.1.4",
|
|
70
|
+
"@niscorp/strata": "^0.1.7"
|
|
71
71
|
},
|
|
72
72
|
"devDependencies": {
|
|
73
73
|
"@electric-sql/pglite": "^0.5.1",
|
|
@@ -76,8 +76,8 @@
|
|
|
76
76
|
"typescript": "^6.0.2",
|
|
77
77
|
"vitest": "^4.1.2",
|
|
78
78
|
"zod": "^4.6.5",
|
|
79
|
-
"@niscorp/cortex": "^0.1.
|
|
80
|
-
"@niscorp/strata": "^0.1.
|
|
79
|
+
"@niscorp/cortex": "^0.1.4",
|
|
80
|
+
"@niscorp/strata": "^0.1.7"
|
|
81
81
|
},
|
|
82
82
|
"peerDependenciesMeta": {
|
|
83
83
|
"@niscorp/cortex": {
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";AAuWO,IAAM,WAAA,GAAkE;AAAA,EAC7E,IAAA,EAAM,IAAA;AAAA,EACN,GAAA,EAAK,IAAA;AAAA,EACL,IAAA,EAAM,IAAA;AAAA,EACN,KAAA,EAAO;AACT;AAaO,IAAM,SAAA,GAAgD;AAAA;AAAA;AAAA,EAG3D,IAAA,EAAM,EAAE,EAAA,EAAI,CAAC,MAAA,EAAQ,UAAU,MAAA,EAAQ,WAAW,CAAA,EAAG,IAAA,EAAM,WAAA,EAAY;AAAA,EACvE,KAAK,EAAE,EAAA,EAAI,CAAC,UAAA,EAAY,OAAO,CAAA,EAAE;AAAA,EACjC,MAAM,EAAE,EAAA,EAAI,CAAC,OAAA,EAAS,MAAM,CAAA,EAAE;AAAA,EAC9B,KAAA,EAAO,EAAE,EAAA,EAAI,CAAC,UAAU,CAAA;AAC1B;AAcO,IAAM,cAAA,GAAiB,CAAC,IAAA,EAAM,IAAA,EAAM,IAAA,EAAM,OAAO,IAAA,EAAM,KAAA,EAAO,IAAA,EAAM,OAAA,EAAS,QAAQ","file":"chunk-4CUQXWVY.js","sourcesContent":["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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas/trigger.schema.ts","../src/schemas/policy.schema.ts","../src/schemas/fact.schema.ts","../src/schemas/reflex.schema.ts"],"names":["z","require"],"mappings":";;;AAYO,IAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAAO,KAAA,EAAO,KAAA,EAAO,OAAO,KAAK;AAExE,IAAM,IAAA,GAAO,2BAAA;AACb,IAAM,IAAA,GAAO,yCAAA;AAEb,IAAM,cAAA,GAAiB,wDAAA;AAEhB,IAAM,eAAA,GAAkB,EAAE,IAAA,CAAK,CAAC,OAAO,MAAA,EAAQ,OAAA,EAAS,MAAM,CAAC;AAE/D,IAAM,oBAAA,GAAuB,EACjC,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,eAAA,CAAgB,QAAA,CAAS,6JAAwJ,CAAA;AAAA,EACxL,EAAA,EAAI,CAAA,CACD,KAAA,CAAM,CAAC,CAAA,CAAE,MAAA,EAAO,CAAE,GAAA,EAAI,CAAE,GAAA,CAAI,CAAC,CAAA,CAAE,IAAI,EAAE,CAAA,EAAG,CAAA,CAAE,IAAA,CAAK,QAAQ,CAAA,EAAG,CAAA,CAAE,MAAA,EAAO,CAAE,KAAA,CAAM,IAAI,CAAC,CAAC,CAAA,CACjF,QAAA,EAAS,CACT,S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AAA,MAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAA,GAAA,CAAK,MAAA,CAAO,QAAA,IAAY,kBAAA,EAAoB,GAAA,CAAI,CAAC,IAAA,KAAuC,cAAA,CAAe,IAAI,CAAC,CAAA;AACjI,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAM,IAAI,MAAM,+CAA+C,CAAA;AACxF,EAAA,MAAM,EAAA,GAAmC,IAAA,CAAK,MAAA,KAAW,CAAA,GAAI,KAAA,GAAQA,CAAAA,CAAE,KAAA,CAAM,CAAC,KAAA,EAAO,GAAG,IAAI,CAAC,CAAA;AAC7F,EAAA,MAAM,MAAM,CAAC,KAAA,KAA+B,OAAO,MAAA,EAAQ,QAAA,CAAS,KAAK,CAAA,IAAK,KAAA;AAC9E,EAAA,MAAM,IAAA,GAA8C;AAAA,IAClD,EAAA,EAAI,IAAA;AAAA,IACJ,MAAA,EAAQ,IAAA;AAAA,IACR,MAAA,EAAQ,IAAA;AAAA,IACR,EAAA,EAAI,IAAA;AAAA,IACJ,GAAI,IAAI,QAAQ,CAAA,GAAI,EAAE,MAAA,EAAQ,IAAA,KAAkB,EAAC;AAAA,IACjD,GAAI,IAAI,QAAQ,CAAA,GAAI,EAAE,MAAA,EAAQ,IAAA,KAAkB,EAAC;AAAA,IACjD,GAAI,IAAI,MAAM,CAAA,GAAI,EAAE,IAAA,EAAM,IAAA,KAAkB;AAAC,GAC/C;AACA,EAAA,OAAO,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,CAAE,MAAA,CAAO,EAAE,EAAA,EAAI,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,CAAY,WAAW,CAAA;AACrF;AAGO,IAAM,oBAAoB,aAAA","file":"chunk-UEG3UZDG.js","sourcesContent":["import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Triggers — four kinds, closed.\n//\n// Structured on purpose: a reflex is shown to the operator it\n// affects, and `{ every: 'month', on: 1, at: '03:00' }` is\n// reviewable by the person it bills where `0 3 1 * *` is a\n// shibboleth. Cron-string sugar belongs in tooling, never in the\n// stored artifact.\n// ═══════════════════════════════════════════════════════════════\n\nexport const WEEKDAYS = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const;\n\nconst HHMM = /^([01]\\d|2[0-3]):[0-5]\\d$/;\nconst MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])$/;\n// Seconds are optional: a one-shot can name the second it fires on.\nconst LOCAL_DATETIME = /^\\d{4}-\\d{2}-\\d{2}T([01]\\d|2[0-3]):[0-5]\\d(:[0-5]\\d)?$/;\n\nexport const ClockUnitSchema = z.enum(['day', 'week', 'month', 'year']);\n\nexport const ClockRecurringSchema = z\n .object({\n every: ClockUnitSchema.describe('The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed — only for a request that says it repeats.'),\n on: z\n .union([z.number().int().min(1).max(31), z.enum(WEEKDAYS), z.string().regex(MMDD)])\n .optional()\n .describe('week → a weekday; month → 1..31 (clamped to month end); year → \"MM-DD\". Omitted for day.'),\n at: z.string().regex(HHMM).describe('Local wall-clock time, \"HH:MM\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .superRefine((clock, ctx) => {\n const fail = (message: string) => ctx.addIssue({ code: 'custom', message, path: ['on'] });\n if (clock.every === 'day' && clock.on !== undefined) fail('a daily clock takes no `on`');\n if (clock.every === 'week' && !(typeof clock.on === 'string' && WEEKDAYS.some((d) => d === clock.on)))\n fail('a weekly clock needs `on` as a weekday (mon..sun)');\n if (clock.every === 'month' && typeof clock.on !== 'number') fail('a monthly clock needs `on` as a day number');\n if (clock.every === 'year' && !(typeof clock.on === 'string' && MMDD.test(clock.on)))\n fail('a yearly clock needs `on` as \"MM-DD\"');\n })\n .describe('Repeats: fires on every day, week, month or year, at a time of day, until the reflex is removed.');\n\nexport const ClockOnceSchema = z\n .object({\n at: z.string().regex(LOCAL_DATETIME).describe('A fixed local date and time, once: \"YYYY-MM-DDTHH:MM\" or, to the second, \"YYYY-MM-DDTHH:MM:SS\".'),\n tz: z.string().describe('IANA timezone name.'),\n })\n .strict()\n .describe('Once: fires at one date and time, then never again.');\n\nexport const ClockTriggerSchema = z\n .object({ clock: z.union([ClockRecurringSchema, ClockOnceSchema]) })\n .strict()\n .describe('Fires on the calendar: once, at a date and time, or repeating at a time of day.');\n\nexport const OpSchema = z.enum(['insert', 'update', 'delete']);\n\nexport const WriteTriggerSchema = z\n .object({\n fact: z\n .object({\n entity: z.string().describe('The table or entity whose writes wake this reflex.'),\n op: OpSchema.optional().describe('Narrow to one op — \"only on create\" is op: \"insert\".'),\n })\n .strict(),\n })\n .strict()\n .describe('Fires when a row of an entity is written — created, changed or deleted.');\n\nexport const SignalTriggerSchema = z\n .object({ fact: z.object({ signal: z.string().describe('A named external intake.') }).strict() })\n .strict()\n .describe('Fires when an event arrives from outside, on a named intake.');\n\nexport const RunTriggerSchema = z\n .object({\n fact: z\n .object({ run: z.string().describe('A reflex id — fires when THAT reflex\\'s run settles. Fan-in and dependency.') })\n .strict(),\n })\n .strict()\n .describe('Fires when another reflex has run: one automation after another.');\n\n// There is NO poll trigger, and the absence is a decision. Polls existed\n// for hosts with no write choke point — run a selection, diff a cursor,\n// mint write facts for the delta. In this stack the host's DAL IS the\n// choke point: every application write becomes a fact at the vex bridge,\n// so a poll could only ever re-discover what was already pushed, one\n// interval late. An external source with no choke point enters through an\n// importer that ingests write facts at the door — the same shape, without\n// a reflex secretly re-querying.\nexport const ManualTriggerSchema = z\n .object({ manual: z.object({}).strict() })\n .strict()\n .describe('Fires only when somebody fires it by hand.');\n\nexport const TriggerSchema = z.union([\n ClockTriggerSchema,\n WriteTriggerSchema,\n SignalTriggerSchema,\n RunTriggerSchema,\n ManualTriggerSchema,\n]);\n\nexport type ClockRecurring = z.infer<typeof ClockRecurringSchema>;\nexport type ClockOnce = z.infer<typeof ClockOnceSchema>;\nexport type Clock = ClockRecurring | ClockOnce;\nexport type Trigger = z.infer<typeof TriggerSchema>;\nexport type Op = z.infer<typeof OpSchema>;\nexport type Weekday = (typeof WEEKDAYS)[number];\n\n// ── narrowing helpers: the union is structural, so every consumer\n// would otherwise re-derive these three checks ───────────────────\n\nexport const clockOf = (trigger: Trigger): Clock | undefined => ('clock' in trigger ? trigger.clock : undefined);\n\nexport const isRecurring = (clock: Clock): clock is ClockRecurring => 'every' in clock;\n\nexport const factOf = (\n trigger: Trigger,\n): { entity?: string; op?: Op; signal?: string; run?: string } | undefined =>\n 'fact' in trigger ? trigger.fact : undefined;\n\nexport const isManual = (trigger: Trigger): boolean => 'manual' in trigger;\n","import { z } from 'zod';\n\n// ═══════════════════════════════════════════════════════════════\n// Policy — the execution semantics, as authored data.\n//\n// Everything the requirements doc said \"must not be hand-waved\",\n// declared per reflex rather than guessed by the engine.\n// ═══════════════════════════════════════════════════════════════\n\nexport const RetrySchema = z\n .object({\n max: z.number().int().min(0).default(3).describe('Attempts after the first before the task parks `failed`.'),\n backoff: z.enum(['fixed', 'exponential']).default('exponential'),\n baseMs: z.number().int().positive().default(60_000),\n })\n .strict();\n\n// THERE IS NO COALESCE, and its absence is the design.\n//\n// It cost two port methods, a table, an exactly-once promise and a\n// `DELETE … RETURNING` on every tick, and nothing ever set it — its only\n// driver was one test. A digest that genuinely needs batching is a DELAYED\n// RUN: the first fact of a group mints one at `now + window` with\n// `cause: 'coalesce:<key>:<start>'`, the rest collide on\n// UNIQUE(reflexId, cause) and are refused, and when it comes due the reflex\n// selects what changed. Mechanisms that already exist, and no new table.\nexport const PolicySchema = z\n .object({\n retry: RetrySchema.optional(),\n timeoutMs: z.number().int().positive().default(30_000),\n // May a firing start while the previous one is unsettled? The long\n // billing run still going at the next tick must not double-start.\n overlap: z.enum(['skip', 'allow']).default('skip'),\n catchUp: z.enum(['run', 'skip', 'latest']).default('run'),\n // How late is \"missed\"? Only `catchUp: 'skip'` reads it — 'run' opens\n // everything and 'latest' keeps the newest regardless of age. What\n // `catchUp` opens still passes `overlap`: occurrences missed together are\n // repeats of one another, so under 'skip' the oldest runs and the rest\n // are recorded as overlap skips.\n lateMs: z.number().int().positive().default(3_600_000),\n order: z.enum(['any', 'serial']).default('any'),\n })\n .strict();\n\nexport type Retry = z.infer<typeof RetrySchema>;\nexport type Policy = z.infer<typeof PolicySchema>;\n\n// Every field defaults, so the empty policy is a real, complete policy —\n// which is what lets a reflex omit `policy` entirely and still be governed.\nexport const DEFAULT_POLICY: Policy = PolicySchema.parse({});\n","import { z } from 'zod';\nimport { OpSchema } from './trigger.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Fact — the public intake contract.\n//\n// Tide's whole ingestion surface. Anything that can produce this\n// shape can drive tide; nothing else about the producer is tide's\n// business. A host that sees its own writes pushes them — the vex\n// bridge is that host. Either way, what arrives is this.\n// ═══════════════════════════════════════════════════════════════\n\nexport const FactKindSchema = z.enum(['write', 'signal', 'manual', 'run']);\n\nexport const FactInputSchema = z\n .object({\n kind: FactKindSchema,\n\n // write facts\n entity: z.string().optional().describe('Which table or entity was written.'),\n op: OpSchema.optional().describe('Ops are distinct stimuli — \"only on create\" is op: \"insert\".'),\n row: z.record(z.string(), z.unknown()).optional().describe('The row, as the write returned it.'),\n\n // signal facts\n name: z.string().optional().describe('Which named intake this arrived on.'),\n payload: z.unknown().optional().describe('The event body — validated at the HOST boundary before it gets here.'),\n\n // run facts (minted by tide when a run settles — the fan-in mechanism)\n reflex: z.string().optional(),\n runId: z.string().optional(),\n occurrence: z.string().optional().describe('The calendar key, when the clock was the cause.'),\n stats: z\n .object({ total: z.number().int(), done: z.number().int(), failed: z.number().int() })\n .strict()\n .optional(),\n\n // manual facts (minted by `fire`)\n target: z.string().optional().describe('The one reflex a manual fact is aimed at.'),\n by: z.string().optional().describe('Who fired it — recorded on the firing as manual:<who>.'),\n\n at: z.number().int().describe('Supplied by the caller. Tide reads no clocks.'),\n notBefore: z.number().int().optional().describe('A delayed fact — timers as data, visible and queryable.'),\n dedupeKey: z.string().optional().describe('Provider event ids. A repeat is refused and announced as fact.deduped; it is not an error.'),\n cause: z.string().optional().describe('Set by tide when an effect emits — the causality chain.'),\n })\n .strict()\n // THE UNION IS ENFORCED, because an unenforced one is worse than none.\n //\n // `{ kind: 'write' }` with no entity used to parse, store, match nothing,\n // get marked delivered, and vanish — the producer had no way to learn its\n // fact was never going to wake anything. Each kind names the fields that\n // make it addressable, and a fact that cannot be addressed is refused at\n // the intake rather than swallowed by the matcher.\n .superRefine((fact, ctx) => {\n const require = (field: keyof typeof fact, why: string) => {\n if (fact[field] === undefined)\n ctx.addIssue({ code: 'custom', message: `a ${fact.kind} fact needs \\`${String(field)}\\` — ${why}`, path: [field] });\n };\n const refuse = (field: keyof typeof fact) => {\n if (fact[field] !== undefined)\n ctx.addIssue({ code: 'custom', message: `\\`${String(field)}\\` is not part of a ${fact.kind} fact`, path: [field] });\n };\n\n if (fact.kind === 'write') {\n require('entity', 'it is what a write trigger matches on');\n refuse('name');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'signal') {\n require('name', 'it is which named intake this arrived on');\n refuse('entity');\n refuse('op');\n refuse('target');\n refuse('runId');\n }\n if (fact.kind === 'manual') {\n require('target', 'a manual fact is aimed at exactly one reflex');\n refuse('entity');\n refuse('name');\n refuse('runId');\n }\n if (fact.kind === 'run') {\n require('reflex', 'it is whose run settled');\n require('runId', 'it is which run settled');\n refuse('entity');\n refuse('name');\n refuse('target');\n }\n });\n\nexport type FactInput = z.infer<typeof FactInputSchema>;\nexport type FactKind = z.infer<typeof FactKindSchema>;\n","import { z } from 'zod';\nimport { ClockTriggerSchema, ManualTriggerSchema, RunTriggerSchema, SignalTriggerSchema, TriggerSchema, WriteTriggerSchema } from './trigger.schema';\nimport { DEFAULT_POLICY, PolicySchema } from './policy.schema';\n\n// ═══════════════════════════════════════════════════════════════\n// Reflex — the artifact.\n//\n// A trigger, an optional selection, exactly one effect, a policy.\n// A straight arc from stimulus to response with no deliberation\n// between: there is no step language here, and a multi-step flow\n// is a CHAIN of reflexes joined by committed rows.\n//\n// `select.query` and every template are `unknown` ON PURPOSE. The\n// moment tide validates a query it owns a query language; the\n// moment it evaluates an expression it owns an evaluator. Both\n// exist in the stack already, behind seams. Tide stores, diffs and\n// hashes these blobs, and hands them over verbatim.\n// ═══════════════════════════════════════════════════════════════\n\nexport const SelectionSchema = z\n .object({\n query: z.unknown().describe('Handed to the `select` seam verbatim. Under moss: a vex { fingerprint, context } replay.'),\n mode: z\n .enum(['each', 'batch'])\n .default('each')\n .describe('each → one task per row; batch → one task carrying all rows (bounded sets only).'),\n unitKey: z.string().optional().describe('The row field keying a unit task. `each` mode only; duplicates fail the firing.'),\n })\n .strict();\n\nexport const EffectRefSchema = z\n .object({\n name: z.string().describe('A registered effect. The reflex names it; the registry supplies the handler.'),\n input: z.unknown().optional().describe('A template, evaluated per unit by the `transform` seam.'),\n })\n .strict();\n\nconst reflexFields = {\n id: z.string().min(1).describe(\"Unique. A tenant's reflex is the tenant's own row, with its own id.\"),\n intent: z.string().min(1).describe(\"One factual sentence — what this does, in the person's language.\"),\n on: TriggerSchema,\n as: z.string().optional().describe('The identity this runs under. Opaque to tide; the host resolves it.'),\n params: z.record(z.string(), z.unknown()).optional().describe('Authored knobs, visible to templates as $.params.'),\n select: SelectionSchema.optional().describe('Omitted = the trigger itself is the unit.'),\n when: z.unknown().optional().describe('A predicate template. FACT triggers only — a query belongs in `select`.'),\n effect: EffectRefSchema,\n policy: PolicySchema.default(DEFAULT_POLICY),\n enabled: z.boolean().default(true).describe('A switch on the row, not part of the definition — flipping it is not an edit.'),\n};\n\nconst reflexRules = (reflex: { on: object; when?: unknown; select?: { mode: string; unitKey?: string | undefined } | undefined }, ctx: z.RefinementCtx): void => {\n if (reflex.when !== undefined && !('fact' in reflex.on))\n ctx.addIssue({ code: 'custom', message: '`when` is for fact triggers; a clock condition belongs in `select`', path: ['when'] });\n if (reflex.select?.mode === 'each' && reflex.select.unitKey === undefined)\n ctx.addIssue({ code: 'custom', message: \"`each` mode needs a unitKey — it is the task's idempotency grain\", path: ['select', 'unitKey'] });\n};\n\nexport const ReflexSchema = z.object(reflexFields).strict().superRefine(reflexRules);\n\n// ═══════════════════════════════════════════════════════════════\n// Draft — a reflex as it is WRITTEN, before it is saved.\n//\n// What a model writes: a name, an intent, a trigger and an effect — and\n// nothing that is the host's (who it runs as, its policy, whether it is\n// enabled). Which triggers, and whether the extra fields a data-driven\n// automation needs, are the CALLER'S choice (`draftSchemaOf`): a draft may\n// only use what its host can run, the way it may only name the effects its\n// host offers. That schema is what the model is shown, and what it is held\n// to; what is stored is still the full ReflexSchema, completed when the\n// draft is saved (`anchorDraft`).\n//\n// One trigger exists only here: the TIMER — \"this long from now\". A timer\n// is sugar, never stored. `now` is only known when somebody saves the\n// draft, so the host anchors it then, and what is stored and run is an\n// ordinary one-shot clock — which survives a restart, because it names an\n// instant rather than a distance from one.\n// ═══════════════════════════════════════════════════════════════\n\nexport const TimerSchema = z\n .object({\n hours: z.number().int().min(0).optional(),\n minutes: z.number().int().min(0).optional(),\n seconds: z.number().int().min(0).optional(),\n })\n .strict()\n .refine((timer) => (timer.hours ?? 0) + (timer.minutes ?? 0) + (timer.seconds ?? 0) > 0, { message: 'a timer needs a length' });\n\nexport const TimerTriggerSchema = z\n .object({ timer: TimerSchema.describe('A length of time from now, as hours, minutes and seconds (each optional, together more than zero). Fires once, that long after the reflex is saved — not after it is written. A clock is for a time of day or a date.') })\n .strict();\n\n// The trigger kinds a draft can be offered, by name.\nexport const DRAFT_TRIGGERS = {\n clock: ClockTriggerSchema,\n timer: TimerTriggerSchema,\n write: WriteTriggerSchema,\n signal: SignalTriggerSchema,\n run: RunTriggerSchema,\n manual: ManualTriggerSchema,\n} as const;\nexport type DraftTrigger = keyof typeof DRAFT_TRIGGERS;\nconst ALL_DRAFT_TRIGGERS: readonly DraftTrigger[] = ['clock', 'timer', 'write', 'signal', 'run', 'manual'];\n\n// The fields beyond name, intent, trigger and effect a draft can be offered —\n// for automations that select rows or test a fact before they act.\nexport type DraftField = 'params' | 'select' | 'when';\n\n// What the caller offers a draft: its trigger kinds (every kind, if it names\n// none) and its extra fields (none, if it names none).\nexport type DraftChoice = { triggers?: readonly DraftTrigger[]; fields?: readonly DraftField[] };\n\nconst draftCore = {\n id: z.string().min(1).describe('A short name for this automation.'),\n intent: reflexFields.intent,\n effect: EffectRefSchema,\n};\n\n// The widest draft: every trigger, every extra field — the TYPE every\n// narrower draft is, and what `anchorDraft` completes.\nconst WidestDraftSchema = z\n .object({ ...draftCore, on: z.union([TriggerSchema, TimerTriggerSchema]), params: reflexFields.params, select: reflexFields.select, when: reflexFields.when })\n .strict();\nexport type ReflexDraft = z.infer<typeof WidestDraftSchema>;\n\n// The draft schema for what the caller offers — tide's own pieces, each with\n// the description it already has: the widest draft, cut to the chosen fields,\n// its trigger narrowed to the chosen kinds. Nothing is restated here.\nexport const draftSchemaOf = (choice: DraftChoice = {}): z.ZodType<ReflexDraft> => {\n const [first, ...rest] = (choice.triggers ?? ALL_DRAFT_TRIGGERS).map((kind): z.ZodType<ReflexDraft['on']> => DRAFT_TRIGGERS[kind]);\n if (first === undefined) throw new Error('tide: a draft needs at least one trigger kind');\n const on: z.ZodType<ReflexDraft['on']> = rest.length === 0 ? first : z.union([first, ...rest]);\n const has = (field: DraftField): boolean => choice.fields?.includes(field) ?? false;\n const keep: { [key in keyof ReflexDraft]?: true } = {\n id: true,\n intent: true,\n effect: true,\n on: true,\n ...(has('params') ? { params: true as const } : {}),\n ...(has('select') ? { select: true as const } : {}),\n ...(has('when') ? { when: true as const } : {}),\n };\n return WidestDraftSchema.pick(keep).extend({ on }).strict().superRefine(reflexRules);\n};\n\n// The default draft: every trigger kind, no extra fields.\nexport const ReflexDraftSchema = draftSchemaOf();\n\nexport type Selection = z.infer<typeof SelectionSchema>;\nexport type EffectRef = z.infer<typeof EffectRefSchema>;\nexport type Reflex = z.infer<typeof ReflexSchema>;\nexport type ReflexInput = z.input<typeof ReflexSchema>;\nexport type Timer = z.infer<typeof TimerSchema>;\n"]}
|