From 500642ac9204b77e8f1f8c67fd1f92244953e1de Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:22:00 +0000 Subject: [PATCH 1/5] docs(skills): vetted overlap-check hook template for insert and update The data skill's hook reference and the record hooks docs page carry a template that refuses two live records of one owner over overlapping time: stored row merged under the patch on update, the record itself excluded, ignored statuses named with $nin, half-open ranges, a declared refusal. Its four known limits sit next to it. The runtime test runs the template on a real SQLite driver and the QuickJS sandbox. Restating subsections under Key Properties are removed to pay for the new text. Claude-Session: https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU Co-Authored-By: Claude --- .../32979-skills-overlap-hook-template.md | 13 ++ content/docs/automation/hooks.mdx | 62 +++++++ .../overlap-hook-template.integration.test.ts | 158 ++++++++++++++++++ .../objectstack-data/references/data-hooks.md | 115 +++++-------- 4 files changed, 272 insertions(+), 76 deletions(-) create mode 100644 .changeset/32979-skills-overlap-hook-template.md create mode 100644 packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts diff --git a/.changeset/32979-skills-overlap-hook-template.md b/.changeset/32979-skills-overlap-hook-template.md new file mode 100644 index 00000000000..92cdd24db16 --- /dev/null +++ b/.changeset/32979-skills-overlap-hook-template.md @@ -0,0 +1,13 @@ +--- +'@objectstack/skills': patch +--- + +docs(skills): a vetted hook template refuses two records of one owner over overlapping time + +Clause-②: no +Metadata-protocol: none + +The platform has no declarative way to say "two leave requests of one person may not overlap": a validation rule sees one record and a unique index compares equal values only. That rule stays in a hook script for now, and the published data skill now carries the form to copy. + +- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Four known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, and rows of one bulk insert do not see each other. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties are removed: each restated the comments of the `defineHook` example above them, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. +- The record hooks page (`content/docs/automation/hooks.mdx`) carries the same template with the reason for each line and the same limits. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 2498dcacd71..753ff86a302 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -327,6 +327,68 @@ would move a handler's own `ctx.api` writes *outside* the transaction the write ran in, which is a worse guarantee than the one documented here. +## Recipe — refuse overlapping time ranges + +Leave, overtime, room and shift bookings share one rule: two live records of the +same owner may not cover the same time. There is no declarative key for it, and +a validation rule cannot see the other records, so write it as a `before*` hook +on **both** insert and update. This is the vetted form; rename the object and +fields: + +```ts +import { defineHook } from '@objectstack/spec/data'; + +export default defineHook({ + name: 'leave_request_no_overlap', + object: 'leave_request', + events: ['beforeInsert', 'beforeUpdate'], + refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, + body: { + language: 'js', + capabilities: ['api.read'], + source: ` + const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch + const off = ['rejected', 'cancelled']; + if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const where = { + owner_id: r.owner_id, + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and + end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + }; + if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself + if (await ctx.api.object('leave_request').count({ where }) > 0) + throw Object.assign(new Error(), { code: 'OVERLAP' }); + `, + }, +}); +``` + +Each line is there for a reason: + +- **Merge the stored row under the patch.** On update `ctx.input` carries only + the fields this write changes, so a patch that moves `start_at` alone must be + judged with the stored `end_at`, `owner_id` and `status`. +- **Exclude the record itself** with `id: { $ne: … }`, or every update of a + booking collides with its own stored row. +- **Name the ignored statuses with `$nin` (or `$ne`), never the live ones with + `$in`.** A status added later then counts as live until someone decides + otherwise, and a row with no status counts too. A record saved in an ignored + status is not checked; reviving it into an overlap is refused. +- **Half-open ranges.** `start < other.end && end > other.start`: a booking + ending at 18:00 and one starting at 18:00 do not overlap. +- **A declared refusal.** The body throws the code alone; the saver gets the + catalogue's fixed sentence (translated through the key + `hooks.leave_request_no_overlap.refusals.OVERLAP.message`) and the caller a + `409` whose `declaredCode` is `OVERLAP`. + +Known limits — the hook does not cover these, so do not assume it does: + +- It reads, then the write happens: two saves at the same moment can both pass. +- A recycle-bin restore runs no insert hook. +- An import run with automations off skips hooks. +- Rows of one bulk insert do not see each other. + ## Hook Context `handler` receives a `HookContext` with these fields: diff --git a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts new file mode 100644 index 00000000000..90ec0c349f4 --- /dev/null +++ b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts @@ -0,0 +1,158 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The overlap-check hook template, run as written. + * + * Ruling 6876330213 keeps "no two of mine overlap" in hook scripts (no + * `exclusions` key, no kernel change) and orders a vetted template into the + * published skill (`skills/objectstack-data/references/data-hooks.md`, + * pattern 5) and the docs (`content/docs/automation/hooks.mdx`). This file is + * the vetting: {@link TEMPLATE} is that template's hook, byte for byte, and + * it runs here in composition — a real `ObjectQL`, a real SQLite driver, the + * real `QuickJSScriptRunner` and hook binder — for the five cases the order + * names, read off `mapDataError`, the ADR-0112 table every data door answers + * with. + * + * The copy is held here, not read from `skills/`: this package's suites do + * not read outside it. When you edit the template there, edit it here. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { mapDataError } from '@objectstack/types'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { hookBodyRunnerFactory } from './body-runner.js'; +import { QuickJSScriptRunner } from './quickjs-runner.js'; + +/** The published template's hook (data-hooks.md pattern 5), byte for byte. */ +const TEMPLATE = { + name: 'leave_request_no_overlap', + object: 'leave_request', + events: ['beforeInsert', 'beforeUpdate'], + refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, + body: { + language: 'js', + capabilities: ['api.read'], + source: ` + const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch + const off = ['rejected', 'cancelled']; + if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const where = { + owner_id: r.owner_id, + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and + end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + }; + if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself + if (await ctx.api.object('leave_request').count({ where }) > 0) + throw Object.assign(new Error(), { code: 'OVERLAP' }); + `, + }, +}; + +const LEAVE = { + name: 'leave_request', + fields: { + owner_id: { type: 'text', name: 'owner_id' }, + start_at: { type: 'datetime', name: 'start_at' }, + end_at: { type: 'datetime', name: 'end_at' }, + status: { type: 'text', name: 'status' }, + note: { type: 'text', name: 'note' }, + }, +}; + +describe('overlap-check hook template (data-hooks.md pattern 5)', () => { + let engine: ObjectQL | null = null; + let dir: string | null = null; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + engine = null; + if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; } + }); + + async function boot(): Promise { + dir = mkdtempSync(join(tmpdir(), 'os-overlap-template-')); + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); + await driver.initObjects([LEAVE]); + engine = new ObjectQL(); + engine.registerDriver(driver as any, true); + await engine.init(); + engine.registry.registerObject(LEAVE as any); + const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'overlap' }); + bindHooksToEngine(engine, [TEMPLATE as any], { packageId: 'overlap', bodyRunner }); + return engine; + } + + const day = (from: string, to: string, extra: Record = {}) => ({ + owner_id: 'u1', + start_at: `2026-11-10T${from}:00.000Z`, + end_at: `2026-11-10T${to}:00.000Z`, + status: 'approved', + ...extra, + }); + + async function refusal(p: Promise) { + const err = await p.then(() => null, (x) => x); + expect(err, 'the write must be refused').not.toBeNull(); + return mapDataError(err, 'leave_request'); + } + + function expectOverlapRefusal(r: ReturnType) { + expect(r.status).toBe(409); + expect((r.body as any).declaredCode).toBe('OVERLAP'); + expect(String(r.body.error)).toContain('This overlaps another request of yours.'); + } + + it('refuses an insert that overlaps a live row of the same owner, and writes nothing', async () => { + const e = await boot(); + await e.insert('leave_request', day('18:30', '21:30')); + expectOverlapRefusal(await refusal(e.insert('leave_request', day('18:30', '21:30', { status: 'draft' })))); + expectOverlapRefusal(await refusal(e.insert('leave_request', day('20:00', '23:00')))); + expect(await e.count('leave_request', {})).toBe(1); + }, 30_000); + + it('fails closed: a sibling with no status, or in a status the list does not name, still counts', async () => { + const e = await boot(); + await e.insert('leave_request', day('08:00', '09:00', { status: null })); + await e.insert('leave_request', day('10:00', '11:00', { status: 'escalated' })); + expectOverlapRefusal(await refusal(e.insert('leave_request', day('08:30', '08:45')))); + expectOverlapRefusal(await refusal(e.insert('leave_request', day('10:30', '10:45')))); + }, 30_000); + + it('accepts an adjacent range (half-open), another owner, and a row with an ignored status', async () => { + const e = await boot(); + await e.insert('leave_request', day('18:30', '21:30')); + await e.insert('leave_request', day('21:30', '23:00')); + await e.insert('leave_request', day('17:00', '18:30')); + await e.insert('leave_request', day('18:30', '21:30', { owner_id: 'u2' })); + // The rejected row is ignored as a sibling, and a rejected write is not checked. + await e.insert('leave_request', day('19:00', '20:00', { status: 'rejected' })); + await e.insert('leave_request', day('09:00', '10:00', { status: 'rejected' })); + await e.insert('leave_request', day('09:30', '10:30')); + expect(await e.count('leave_request', {})).toBe(7); + }, 30_000); + + it('refuses an update that moves a row into overlap, merging the stored row under the patch', async () => { + const e = await boot(); + await e.insert('leave_request', day('18:30', '21:30')); + const later = await e.insert('leave_request', day('22:00', '23:00')) as any; + // The patch carries only `start_at`; `end_at`, `owner_id` and `status` come from the stored row. + expectOverlapRefusal(await refusal(e.update('leave_request', { id: later.id, start_at: '2026-11-10T21:00:00.000Z' }))); + // Reviving a rejected row into an overlap is refused too. + const dead = await e.insert('leave_request', day('19:00', '20:00', { status: 'rejected' })) as any; + expectOverlapRefusal(await refusal(e.update('leave_request', { id: dead.id, status: 'approved' }))); + }, 30_000); + + it('does not refuse an update of the record against itself', async () => { + const e = await boot(); + const row = await e.insert('leave_request', day('18:30', '21:30')) as any; + await e.update('leave_request', { id: row.id, note: 'renamed' }); + await e.update('leave_request', { id: row.id, start_at: '2026-11-10T18:00:00.000Z' }); + const got = await e.findOne('leave_request', { where: { id: row.id } }) as any; + expect(got.note).toBe('renamed'); + }, 30_000); +}); diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index 84761075053..5a37d2eea81 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -125,32 +125,6 @@ const myHook = defineHook({ ### Key Properties Explained -#### `object` — Target Scope - -```typescript -// Single object -object: 'account' - -// Multiple objects -object: ['account', 'contact', 'lead'] - -// All objects (use sparingly — performance impact) -object: '*' -``` - -#### `events` — Lifecycle Events - -```typescript -// Single event -events: ['beforeInsert'] - -// Multiple events (common pattern) -events: ['beforeInsert', 'beforeUpdate'] - -// After events for side effects -events: ['afterInsert', 'afterUpdate', 'afterDelete'] -``` - #### `body` — Implementation A `source` of statements against `ctx`; a throw aborts the write @@ -166,42 +140,6 @@ body: { The deprecated `handler` takes an inline function or a registered function's name ([Registration Methods](#registration-methods)). -#### `priority` — Execution Order - -Lower numbers execute first: - -```typescript -// System hooks (framework internals) -priority: 50 - -// Application hooks (your app logic) -priority: 100 // default - -// User customizations -priority: 1000 -``` - -#### `async` — Background Execution - -Only applicable for `after*` events: - -```typescript -// Blocking (default) — runs within transaction -async: false - -// Fire-and-forget — runs in background -async: true -``` - -**When to use async: true:** -- Sending notifications -- Non-critical side effects - -**When to use async: false:** -- Creating related records -- Updating dependent data -- Critical consistency requirements - #### `condition` — Declarative Filtering Skip the hook if the condition is false. Author it as a **CEL @@ -284,20 +222,6 @@ fields, and on an insert event read `previous` only against `null` — a column read off it there is the mistake that used to cost you a hook that quietly never ran, and now costs you every write the hook is attached to. -#### `onError` — Error Handling - -The default is `'abort'` **unconditionally** — for `after*` hooks too, a sync -after-hook that throws rolls back the transaction. Set `onError: 'log'` -explicitly on `after*` side-effect hooks: - -```typescript -// Abort operation on error — the default for ALL hooks (before* AND after*) -onError: 'abort' - -// Log error and continue — set this on after* side-effect hooks -onError: 'log' -``` - --- ## Sandboxed Hook Bodies (`body`) — What the Sandbox `ctx` Can Call @@ -852,6 +776,45 @@ const maskSensitiveData = defineHook({ }); ``` +### 5. No two of mine overlap (sandboxed `body`) + +No declarative key refuses two overlapping leave requests of one person; use +this hook, renaming object and fields. + + +```typescript +import { defineHook } from '@objectstack/spec/data'; + +export default defineHook({ + name: 'leave_request_no_overlap', + object: 'leave_request', + events: ['beforeInsert', 'beforeUpdate'], + refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, + body: { + language: 'js', + capabilities: ['api.read'], + source: ` + const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch + const off = ['rejected', 'cancelled']; + if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const where = { + owner_id: r.owner_id, + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and + end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + }; + if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself + if (await ctx.api.object('leave_request').count({ where }) > 0) + throw Object.assign(new Error(), { code: 'OVERLAP' }); + `, + }, +}); +``` + +Known limits: it is a read-then-write check, so two concurrent saves can both +pass; a recycle-bin restore runs no insert hook; an import with automations off +skips hooks; and rows of one bulk insert do not see each other. + --- ## Registration Methods From 5b241662f1025a18390b6b11d38a28fa585b93ca Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:08:58 +0000 Subject: [PATCH 2/5] docs(skills): overlap template handles date end days and reads elevated Contract review round 1. The template now compares a date range with its end day inclusive (the same day twice is refused) while a datetime range stays half-open, declares runAs system so its count sees rows the saver cannot read, and counts in ctx.object so only field names need renaming. The limits name bulk updates and rows with no start or end. The proving test adds a date-field case and a delegate-under-sharing case. The previous-state example under Hook Context API, which restated the sandbox ctx table, is removed to pay for the new text. Claude-Session: https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU Co-Authored-By: Claude --- .../32979-skills-overlap-hook-template.md | 2 +- content/docs/automation/hooks.mdx | 37 ++++++--- .../overlap-hook-template.integration.test.ts | 80 ++++++++++++++++--- .../objectstack-data/references/data-hooks.md | 35 +++----- 4 files changed, 104 insertions(+), 50 deletions(-) diff --git a/.changeset/32979-skills-overlap-hook-template.md b/.changeset/32979-skills-overlap-hook-template.md index 92cdd24db16..3dffcf03838 100644 --- a/.changeset/32979-skills-overlap-hook-template.md +++ b/.changeset/32979-skills-overlap-hook-template.md @@ -9,5 +9,5 @@ Metadata-protocol: none The platform has no declarative way to say "two leave requests of one person may not overlap": a validation rule sees one record and a unique index compares equal values only. That rule stays in a hook script for now, and the published data skill now carries the form to copy. -- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Four known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, and rows of one bulk insert do not see each other. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties are removed: each restated the comments of the `defineHook` example above them, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. +- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; `datetime` ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap, while a `date` range's end day is inclusive, so the same day cannot be booked twice; it declares `runAs: 'system'`, so the count also sees rows the saver cannot read; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Its known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, rows of one bulk insert or update do not see each other, and a row with no start or end is neither checked nor counted. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties, and the `previous` example under Hook Context API, are removed: each restated the comments of the `defineHook` example, the sandbox `ctx` table, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. - The record hooks page (`content/docs/automation/hooks.mdx`) carries the same template with the reason for each line and the same limits. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 753ff86a302..62d04393043 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -329,11 +329,11 @@ ran in, which is a worse guarantee than the one documented here. ## Recipe — refuse overlapping time ranges -Leave, overtime, room and shift bookings share one rule: two live records of the -same owner may not cover the same time. There is no declarative key for it, and -a validation rule cannot see the other records, so write it as a `before*` hook -on **both** insert and update. This is the vetted form; rename the object and -fields: +Leave and overtime requests share one rule: two live records of the same owner +may not cover the same time (a room or shift booking is the same rule grouped by +the room or the shift). There is no declarative key for it, and a validation +rule cannot see the other records, so write it as a `before*` hook on **both** +insert and update. This is the vetted form; rename its fields: ```ts import { defineHook } from '@objectstack/spec/data'; @@ -342,6 +342,7 @@ export default defineHook({ name: 'leave_request_no_overlap', object: 'leave_request', events: ['beforeInsert', 'beforeUpdate'], + runAs: 'system', // count the rows the saver cannot read too refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, body: { language: 'js', @@ -350,14 +351,15 @@ export default defineHook({ const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const day = String(r.end_at).length === 10; // a date field: its end day is inclusive const where = { owner_id: r.owner_id, - status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and - end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself - if (await ctx.api.object('leave_request').count({ where }) > 0) + if (await ctx.api.object(ctx.object).count({ where }) > 0) throw Object.assign(new Error(), { code: 'OVERLAP' }); `, }, @@ -375,8 +377,18 @@ Each line is there for a reason: `$in`.** A status added later then counts as live until someone decides otherwise, and a row with no status counts too. A record saved in an ignored status is not checked; reviving it into an overlap is refused. -- **Half-open ranges.** `start < other.end && end > other.start`: a booking - ending at 18:00 and one starting at 18:00 do not overlap. +- **Half-open ranges for `datetime`.** `start < other.end && end > other.start`: + a booking ending at 18:00 and one starting at 18:00 do not overlap. +- **Inclusive end days for `date`.** A `date` value is `YYYY-MM-DD`, ten + characters, and a one-day leave has `start == end`; the half-open test would + let the same day be booked twice, so date ranges compare with `<=` / `>=`. +- **`runAs: 'system'`.** The count must see rows the saver cannot read: a + delegate filing for someone under private sharing, or a room booked by + others. Without it the hook's `ctx.api` reads as the saver (see + [Elevation](#elevation--runas)) and misses them. The hook only counts; the + write itself still runs as the saver. +- **`ctx.api.object(ctx.object)`** counts in the object the hook fired on, so + only the field names need renaming. - **A declared refusal.** The body throws the code alone; the saver gets the catalogue's fixed sentence (translated through the key `hooks.leave_request_no_overlap.refusals.OVERLAP.message`) and the caller a @@ -387,7 +399,8 @@ Known limits — the hook does not cover these, so do not assume it does: - It reads, then the write happens: two saves at the same moment can both pass. - A recycle-bin restore runs no insert hook. - An import run with automations off skips hooks. -- Rows of one bulk insert do not see each other. +- Rows of one bulk insert or bulk update do not see each other. +- A row with no start or no end is neither checked nor counted. ## Hook Context diff --git a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts index 90ec0c349f4..4c6ce253c5b 100644 --- a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts +++ b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts @@ -9,9 +9,11 @@ * pattern 5) and the docs (`content/docs/automation/hooks.mdx`). This file is * the vetting: {@link TEMPLATE} is that template's hook, byte for byte, and * it runs here in composition — a real `ObjectQL`, a real SQLite driver, the - * real `QuickJSScriptRunner` and hook binder — for the five cases the order - * names, read off `mapDataError`, the ADR-0112 table every data door answers - * with. + * real `QuickJSScriptRunner` and hook binder — for the cases the order and + * its contract review name (overlap on insert and update, adjacency, self + * update, ignored statuses, inclusive `date` end days, a saver who cannot read + * the overlapping row), read off `mapDataError`, the ADR-0112 table every data + * door answers with. * * The copy is held here, not read from `skills/`: this package's suites do * not read outside it. When you edit the template there, edit it here. @@ -32,6 +34,7 @@ const TEMPLATE = { name: 'leave_request_no_overlap', object: 'leave_request', events: ['beforeInsert', 'beforeUpdate'], + runAs: 'system', // count the rows the saver cannot read too refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, body: { language: 'js', @@ -40,14 +43,15 @@ const TEMPLATE = { const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const day = String(r.end_at).length === 10; // a date field: its end day is inclusive const where = { owner_id: r.owner_id, - status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and - end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself - if (await ctx.api.object('leave_request').count({ where }) > 0) + if (await ctx.api.object(ctx.object).count({ where }) > 0) throw Object.assign(new Error(), { code: 'OVERLAP' }); `, }, @@ -61,9 +65,35 @@ const LEAVE = { end_at: { type: 'datetime', name: 'end_at' }, status: { type: 'text', name: 'status' }, note: { type: 'text', name: 'note' }, + filed_by: { type: 'text', name: 'filed_by' }, }, }; +/** The same template on `date` fields, where the end day is inclusive. */ +const LEAVE_DAY = { + name: 'leave_day', + fields: { + owner_id: { type: 'text', name: 'owner_id' }, + start_at: { type: 'date', name: 'start_at' }, + end_at: { type: 'date', name: 'end_at' }, + status: { type: 'text', name: 'status' }, + }, +}; + +/** + * A stand-in for private sharing: an unelevated read of `leave_request` sees + * only the rows its user filed. `runAs: 'system'` is what lets the template's + * count see past it. + */ +function filedByOnly(opCtx: any, next: () => Promise) { + if (opCtx.object === 'leave_request' && (opCtx.operation === 'count' || opCtx.operation === 'find') + && opCtx.context && !opCtx.context.isSystem && opCtx.ast) { + const mine = { filed_by: opCtx.context.userId ?? null }; + opCtx.ast = { ...opCtx.ast, where: opCtx.ast.where ? { $and: [opCtx.ast.where, mine] } : mine }; + } + return next(); +} + describe('overlap-check hook template (data-hooks.md pattern 5)', () => { let engine: ObjectQL | null = null; let dir: string | null = null; @@ -77,13 +107,15 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { async function boot(): Promise { dir = mkdtempSync(join(tmpdir(), 'os-overlap-template-')); const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true }); - await driver.initObjects([LEAVE]); + await driver.initObjects([LEAVE, LEAVE_DAY]); engine = new ObjectQL(); engine.registerDriver(driver as any, true); await engine.init(); - engine.registry.registerObject(LEAVE as any); + for (const o of [LEAVE, LEAVE_DAY]) engine.registry.registerObject(o as any); + engine.registerMiddleware(filedByOnly as any); const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'overlap' }); - bindHooksToEngine(engine, [TEMPLATE as any], { packageId: 'overlap', bodyRunner }); + // The template as written, and the same hook bound to the `date` object (only `object` differs). + bindHooksToEngine(engine, [TEMPLATE as any, { ...TEMPLATE, name: 'leave_day_no_overlap', object: 'leave_day' } as any], { packageId: 'overlap', bodyRunner }); return engine; } @@ -98,7 +130,7 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { async function refusal(p: Promise) { const err = await p.then(() => null, (x) => x); expect(err, 'the write must be refused').not.toBeNull(); - return mapDataError(err, 'leave_request'); + return mapDataError(err); } function expectOverlapRefusal(r: ReturnType) { @@ -155,4 +187,30 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { const got = await e.findOne('leave_request', { where: { id: row.id } }) as any; expect(got.note).toBe('renamed'); }, 30_000); + + it('date fields: the end day is inclusive, so the same day twice is refused and the next day is not', async () => { + const e = await boot(); + const d = (from: string, to: string, extra: Record = {}) => + ({ owner_id: 'u1', start_at: from, end_at: to, status: 'approved', ...extra }); + await e.insert('leave_day', d('2026-11-10', '2026-11-10')); + expectOverlapRefusal(await refusal(e.insert('leave_day', d('2026-11-10', '2026-11-10')))); + expectOverlapRefusal(await refusal(e.insert('leave_day', d('2026-11-09', '2026-11-10')))); + await e.insert('leave_day', d('2026-11-11', '2026-11-12')); + await e.insert('leave_day', d('2026-11-09', '2026-11-09')); + // An update that keeps the stored (date) end and moves the start into another row's days. + const later = await e.insert('leave_day', d('2026-11-14', '2026-11-14')) as any; + expectOverlapRefusal(await refusal(e.update('leave_day', { id: later.id, start_at: '2026-11-12' }))); + await e.update('leave_day', { id: later.id, start_at: '2026-11-13' }); + expect(await e.count('leave_day', {})).toBe(4); + }, 30_000); + + it('runs elevated: a saver who cannot read the overlapping row is still refused', async () => { + const e = await boot(); + await e.insert('leave_request', day('18:30', '21:30', { filed_by: 'u1' })); + const delegate = { userId: 'd1', tenantId: 'org_1', isSystem: false, positions: [], permissions: [] } as any; + // The delegate's own read does not see u1's row… + expect(await e.count('leave_request', {}, { context: delegate } as any)).toBe(0); + // …and the template's count, declared `runAs: 'system'`, does. + expectOverlapRefusal(await refusal(e.insert('leave_request', day('19:00', '20:00', { filed_by: 'd1' }), { context: delegate } as any))); + }, 30_000); }); diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index 5a37d2eea81..b5e5ecc649e 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -621,26 +621,6 @@ result: { } ``` -### `previous` — Previous State - -Available in update/delete hooks: - -```typescript -// beforeUpdate, afterUpdate -ctx.previous: { - id: '123', - status: 'pending', // Old value - updated_at: '2026-04-01T00:00:00Z', -} - -// beforeDelete, afterDelete -ctx.previous: { - id: '123', - name: 'Old Account', - // ... full record state -} -``` - ### Cross-Object API Access other objects within the same transaction. `ctx.api.object(name)` is the @@ -779,7 +759,7 @@ const maskSensitiveData = defineHook({ ### 5. No two of mine overlap (sandboxed `body`) No declarative key refuses two overlapping leave requests of one person; use -this hook, renaming object and fields. +this hook, renaming its fields. ```typescript @@ -789,6 +769,7 @@ export default defineHook({ name: 'leave_request_no_overlap', object: 'leave_request', events: ['beforeInsert', 'beforeUpdate'], + runAs: 'system', // count the rows the saver cannot read too refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } }, body: { language: 'js', @@ -797,14 +778,15 @@ export default defineHook({ const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; + const day = String(r.end_at).length === 10; // a date field: its end day is inclusive const where = { owner_id: r.owner_id, - status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: { $lt: r.end_at }, // half-open: one ending 18:00 and - end_at: { $gt: r.start_at }, // one starting 18:00 do not overlap + status: { $nin: off }, // fail closed: a new status counts until listed here + start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself - if (await ctx.api.object('leave_request').count({ where }) > 0) + if (await ctx.api.object(ctx.object).count({ where }) > 0) throw Object.assign(new Error(), { code: 'OVERLAP' }); `, }, @@ -813,7 +795,8 @@ export default defineHook({ Known limits: it is a read-then-write check, so two concurrent saves can both pass; a recycle-bin restore runs no insert hook; an import with automations off -skips hooks; and rows of one bulk insert do not see each other. +skips hooks; rows of one bulk insert or update do not see each other; and a row +with no start or end is neither checked nor counted. --- From da1e5906e6c9d50e1f9b353628522708ecbeb231 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 16:29:49 +0000 Subject: [PATCH 3/5] test(runtime): type the delegate context in the overlap template test The delegate case passed its context through an options bag cast to any, which the query-options erasure ratchet counts as a new test-surface site. Typed as ExecutionContext, the cast is gone and the count returns to its ceiling. Claude-Session: https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU Co-Authored-By: Claude --- .../src/sandbox/overlap-hook-template.integration.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts index 4c6ce253c5b..17265e58956 100644 --- a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts +++ b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts @@ -23,6 +23,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; import { mapDataError } from '@objectstack/types'; import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; @@ -207,10 +208,10 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { it('runs elevated: a saver who cannot read the overlapping row is still refused', async () => { const e = await boot(); await e.insert('leave_request', day('18:30', '21:30', { filed_by: 'u1' })); - const delegate = { userId: 'd1', tenantId: 'org_1', isSystem: false, positions: [], permissions: [] } as any; + const delegate: ExecutionContext = { userId: 'd1', tenantId: 'org_1', isSystem: false, positions: [], permissions: [] }; // The delegate's own read does not see u1's row… - expect(await e.count('leave_request', {}, { context: delegate } as any)).toBe(0); + expect(await e.count('leave_request', {}, { context: delegate })).toBe(0); // …and the template's count, declared `runAs: 'system'`, does. - expectOverlapRefusal(await refusal(e.insert('leave_request', day('19:00', '20:00', { filed_by: 'd1' }), { context: delegate } as any))); + expectOverlapRefusal(await refusal(e.insert('leave_request', day('19:00', '20:00', { filed_by: 'd1' }), { context: delegate }))); }, 30_000); }); From 7f6e8dbf360dde93790caa6014f423cd34fa1b99 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:08:44 +0000 Subject: [PATCH 4/5] docs(skills): overlap template states DATE_ONLY instead of reading the spelling A before* hook sees a date value as the caller wrote it (a Date, or any string with a leading YYYY-MM-DD); drivers cut it to the day only after the hook runs. The template now takes a DATE_ONLY constant from the author and, when it is set, cuts both ends to their leading day before comparing. The lead-ins say the hook's name and object are renamed with the fields. The proving test adds an end written as a full ISO instant and as a Date. The token cost is paid by deleting the Cross-Object API note, which restated the ctx.api.object(name) section of the same file. Claude-Session: https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU Co-Authored-By: Claude --- .../32979-skills-overlap-hook-template.md | 2 +- content/docs/automation/hooks.mdx | 21 +++++---- .../overlap-hook-template.integration.test.ts | 46 +++++++++++++++---- .../objectstack-data/references/data-hooks.md | 16 +++---- 4 files changed, 57 insertions(+), 28 deletions(-) diff --git a/.changeset/32979-skills-overlap-hook-template.md b/.changeset/32979-skills-overlap-hook-template.md index 3dffcf03838..944f831c184 100644 --- a/.changeset/32979-skills-overlap-hook-template.md +++ b/.changeset/32979-skills-overlap-hook-template.md @@ -9,5 +9,5 @@ Metadata-protocol: none The platform has no declarative way to say "two leave requests of one person may not overlap": a validation rule sees one record and a unique index compares equal values only. That rule stays in a hook script for now, and the published data skill now carries the form to copy. -- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; `datetime` ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap, while a `date` range's end day is inclusive, so the same day cannot be booked twice; it declares `runAs: 'system'`, so the count also sees rows the saver cannot read; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Its known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, rows of one bulk insert or update do not see each other, and a row with no start or end is neither checked nor counted. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties, and the `previous` example under Hook Context API, are removed: each restated the comments of the `defineHook` example, the sandbox `ctx` table, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. +- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; `datetime` ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap, and for `date` fields the author sets `DATE_ONLY`, which cuts both ends to their leading `YYYY-MM-DD` and counts the end day as booked; it declares `runAs: 'system'`, so the count also sees rows the saver cannot read; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Its known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, rows of one bulk insert or update do not see each other, and a row with no start or end is neither checked nor counted. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties, and the `previous` example and the Cross-Object API note under Hook Context API, are removed: each restated the comments of the `defineHook` example, the sandbox `ctx` table, the `ctx.api.object(name)` section, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. - The record hooks page (`content/docs/automation/hooks.mdx`) carries the same template with the reason for each line and the same limits. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 62d04393043..915bbd17de4 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -333,7 +333,8 @@ Leave and overtime requests share one rule: two live records of the same owner may not cover the same time (a room or shift booking is the same rule grouped by the room or the shift). There is no declarative key for it, and a validation rule cannot see the other records, so write it as a `before*` hook on **both** -insert and update. This is the vetted form; rename its fields: +insert and update. This is the vetted form; rename its `name` (the refusal's +translation key follows it), its `object` and its fields: ```ts import { defineHook } from '@objectstack/spec/data'; @@ -348,15 +349,16 @@ export default defineHook({ language: 'js', capabilities: ['api.read'], source: ` + const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = String(r.end_at).length === 10; // a date field: its end day is inclusive + const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: - end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0) @@ -379,16 +381,19 @@ Each line is there for a reason: status is not checked; reviving it into an overlap is refused. - **Half-open ranges for `datetime`.** `start < other.end && end > other.start`: a booking ending at 18:00 and one starting at 18:00 do not overlap. -- **Inclusive end days for `date`.** A `date` value is `YYYY-MM-DD`, ten - characters, and a one-day leave has `start == end`; the half-open test would - let the same day be booked twice, so date ranges compare with `<=` / `>=`. +- **Inclusive end days for `date` — set `DATE_ONLY`.** A one-day leave has + `start == end`, so the half-open test would let the same day be booked twice. + With `DATE_ONLY = true` the template compares with `<=` / `>=`, and first cuts + each value to its leading `YYYY-MM-DD`: a `date` field also accepts a full ISO + instant or a `Date` and stores only that day, but a `before*` hook sees the + value as it was written. - **`runAs: 'system'`.** The count must see rows the saver cannot read: a delegate filing for someone under private sharing, or a room booked by others. Without it the hook's `ctx.api` reads as the saver (see [Elevation](#elevation--runas)) and misses them. The hook only counts; the write itself still runs as the saver. - **`ctx.api.object(ctx.object)`** counts in the object the hook fired on, so - only the field names need renaming. + the body names no object. - **A declared refusal.** The body throws the code alone; the saver gets the catalogue's fixed sentence (translated through the key `hooks.leave_request_no_overlap.refusals.OVERLAP.message`) and the caller a diff --git a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts index 17265e58956..2b7747248c9 100644 --- a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts +++ b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts @@ -11,9 +11,9 @@ * it runs here in composition — a real `ObjectQL`, a real SQLite driver, the * real `QuickJSScriptRunner` and hook binder — for the cases the order and * its contract review name (overlap on insert and update, adjacency, self - * update, ignored statuses, inclusive `date` end days, a saver who cannot read - * the overlapping row), read off `mapDataError`, the ADR-0112 table every data - * door answers with. + * update, ignored statuses, inclusive `date` end days with `DATE_ONLY` set + * however the day is written, a saver who cannot read the overlapping row), + * read off `mapDataError`, the ADR-0112 table every data door answers with. * * The copy is held here, not read from `skills/`: this package's suites do * not read outside it. When you edit the template there, edit it here. @@ -41,15 +41,16 @@ const TEMPLATE = { language: 'js', capabilities: ['api.read'], source: ` + const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = String(r.end_at).length === 10; // a date field: its end day is inclusive + const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: - end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0) @@ -70,6 +71,13 @@ const LEAVE = { }, }; +/** The author's one edit for `date` fields, made exactly once. */ +function dateOnly(source: string): string { + const flag = 'const DATE_ONLY = false;'; + expect(source.split(flag)).toHaveLength(2); + return source.replace(flag, 'const DATE_ONLY = true;'); +} + /** The same template on `date` fields, where the end day is inclusive. */ const LEAVE_DAY = { name: 'leave_day', @@ -115,8 +123,10 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { for (const o of [LEAVE, LEAVE_DAY]) engine.registry.registerObject(o as any); engine.registerMiddleware(filedByOnly as any); const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'overlap' }); - // The template as written, and the same hook bound to the `date` object (only `object` differs). - bindHooksToEngine(engine, [TEMPLATE as any, { ...TEMPLATE, name: 'leave_day_no_overlap', object: 'leave_day' } as any], { packageId: 'overlap', bodyRunner }); + // The template as written, and the same hook bound to the `date` object with the + // one edit an author makes for date fields: `DATE_ONLY = true`. + const DAYS = { ...TEMPLATE, name: 'leave_day_no_overlap', object: 'leave_day', body: { ...TEMPLATE.body, source: dateOnly(TEMPLATE.body.source) } }; + bindHooksToEngine(engine, [TEMPLATE as any, DAYS as any], { packageId: 'overlap', bodyRunner }); return engine; } @@ -145,7 +155,11 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { await e.insert('leave_request', day('18:30', '21:30')); expectOverlapRefusal(await refusal(e.insert('leave_request', day('18:30', '21:30', { status: 'draft' })))); expectOverlapRefusal(await refusal(e.insert('leave_request', day('20:00', '23:00')))); - expect(await e.count('leave_request', {})).toBe(1); + // The same instant spelled with an offset: 19:00+08:00 is 11:00Z, inside 10:30Z to 13:30Z. + await e.insert('leave_request', day('10:30', '13:30')); + expectOverlapRefusal(await refusal(e.insert('leave_request', + { owner_id: 'u1', start_at: '2026-11-10T19:00:00+08:00', end_at: '2026-11-10T20:00:00+08:00', status: 'approved' }))); + expect(await e.count('leave_request', {})).toBe(2); }, 30_000); it('fails closed: a sibling with no status, or in a status the list does not name, still counts', async () => { @@ -205,6 +219,20 @@ describe('overlap-check hook template (data-hooks.md pattern 5)', () => { expect(await e.count('leave_day', {})).toBe(4); }, 30_000); + it('date fields: a day written as a full ISO instant or as a Date is the day stored, and still refused', async () => { + const e = await boot(); + await e.insert('leave_day', { owner_id: 'u1', start_at: '2026-11-10', end_at: '2026-11-10', status: 'approved' }); + expectOverlapRefusal(await refusal(e.insert('leave_day', + { owner_id: 'u1', start_at: '2026-11-10T00:00:00.000Z', end_at: '2026-11-10T00:00:00.000Z', status: 'approved' }))); + expectOverlapRefusal(await refusal(e.insert('leave_day', + { owner_id: 'u1', start_at: new Date('2026-11-10T00:00:00Z'), end_at: new Date('2026-11-10T00:00:00Z'), status: 'approved' }))); + // The next day, written the long way, is not a clash; and it is stored as its day. + const next = await e.insert('leave_day', + { owner_id: 'u1', start_at: new Date('2026-11-11T00:00:00Z'), end_at: '2026-11-11T00:00:00.000Z', status: 'approved' }) as any; + const got = await e.findOne('leave_day', { where: { id: next.id } }) as any; + expect([got.start_at, got.end_at]).toEqual(['2026-11-11', '2026-11-11']); + }, 30_000); + it('runs elevated: a saver who cannot read the overlapping row is still refused', async () => { const e = await boot(); await e.insert('leave_request', day('18:30', '21:30', { filed_by: 'u1' })); diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index b5e5ecc649e..ad58a996f66 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -621,11 +621,6 @@ result: { } ``` -### Cross-Object API - -Access other objects within the same transaction. `ctx.api.object(name)` is the -same repository in both forms; the canonical query key is **`where`**. - --- ## Common Patterns @@ -758,8 +753,8 @@ const maskSensitiveData = defineHook({ ### 5. No two of mine overlap (sandboxed `body`) -No declarative key refuses two overlapping leave requests of one person; use -this hook, renaming its fields. +No declarative key refuses two overlapping leave requests of one person; copy +this hook, renaming its `name`, `object` and fields (`date` fields: set `DATE_ONLY`). ```typescript @@ -775,15 +770,16 @@ export default defineHook({ language: 'js', capabilities: ['api.read'], source: ` + const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = String(r.end_at).length === 10; // a date field: its end day is inclusive + const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: day ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: - end_at: day ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0) From e417fbfcfccaec33e34313e7dd8045c26ba08ddf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:10:59 +0000 Subject: [PATCH 5/5] docs(skills): overlap template leaves the day cut to the query The drivers read a date comparand by the field's own storage rule, so a value written as a full ISO instant or a Date already matches the stored day; the template's own slice was redundant (a mutation removing it stayed green) and would have mangled a non-string value. DATE_ONLY stays: it is what the value's spelling cannot tell. Claude-Session: https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU Co-Authored-By: Claude --- .changeset/32979-skills-overlap-hook-template.md | 2 +- content/docs/automation/hooks.mdx | 13 ++++++------- .../overlap-hook-template.integration.test.ts | 5 ++--- skills/objectstack-data/references/data-hooks.md | 5 ++--- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/.changeset/32979-skills-overlap-hook-template.md b/.changeset/32979-skills-overlap-hook-template.md index 944f831c184..37b02c5e07a 100644 --- a/.changeset/32979-skills-overlap-hook-template.md +++ b/.changeset/32979-skills-overlap-hook-template.md @@ -9,5 +9,5 @@ Metadata-protocol: none The platform has no declarative way to say "two leave requests of one person may not overlap": a validation rule sees one record and a unique index compares equal values only. That rule stays in a hook script for now, and the published data skill now carries the form to copy. -- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; `datetime` ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap, and for `date` fields the author sets `DATE_ONLY`, which cuts both ends to their leading `YYYY-MM-DD` and counts the end day as booked; it declares `runAs: 'system'`, so the count also sees rows the saver cannot read; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Its known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, rows of one bulk insert or update do not see each other, and a row with no start or end is neither checked nor counted. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties, and the `previous` example and the Cross-Object API note under Hook Context API, are removed: each restated the comments of the `defineHook` example, the sandbox `ctx` table, the `ctx.api.object(name)` section, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. +- **`@objectstack/skills`** (`objectstack-data`, `references/data-hooks.md`): Common Patterns gains pattern 5, a `beforeInsert` + `beforeUpdate` hook with a sandboxed `body`. On update it merges the stored row under the patch and leaves the record itself out of the count; it names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts; `datetime` ranges are half-open, so 18:00–21:30 and 21:30–23:00 do not overlap, and for `date` fields the author sets `DATE_ONLY`, which counts the end day as booked; it declares `runAs: 'system'`, so the count also sees rows the saver cannot read; and it refuses through a declared `refusals` entry (`OVERLAP`, `409`). Its known limits are stated next to it: two concurrent saves can both pass, a recycle-bin restore runs no insert hook, an import with automations off skips hooks, rows of one bulk insert or update do not see each other, and a row with no start or end is neither checked nor counted. The `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties, and the `previous` example and the Cross-Object API note under Hook Context API, are removed: each restated the comments of the `defineHook` example, the sandbox `ctx` table, the `ctx.api.object(name)` section, the Before vs After table or Best Practices. No schema, runtime or behaviour changes. - The record hooks page (`content/docs/automation/hooks.mdx`) carries the same template with the reason for each line and the same limits. diff --git a/content/docs/automation/hooks.mdx b/content/docs/automation/hooks.mdx index 915bbd17de4..9b1bfde3500 100644 --- a/content/docs/automation/hooks.mdx +++ b/content/docs/automation/hooks.mdx @@ -353,12 +353,11 @@ export default defineHook({ const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: - end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0) @@ -383,10 +382,10 @@ Each line is there for a reason: a booking ending at 18:00 and one starting at 18:00 do not overlap. - **Inclusive end days for `date` — set `DATE_ONLY`.** A one-day leave has `start == end`, so the half-open test would let the same day be booked twice. - With `DATE_ONLY = true` the template compares with `<=` / `>=`, and first cuts - each value to its leading `YYYY-MM-DD`: a `date` field also accepts a full ISO - instant or a `Date` and stores only that day, but a `before*` hook sees the - value as it was written. + With `DATE_ONLY = true` the template compares with `<=` / `>=`. The flag is + needed because a `before*` hook sees the value as it was written: a `date` + field also takes a full ISO instant or a `Date`, so the spelling does not say + which kind the field is. The query reads each value as the day it stores. - **`runAs: 'system'`.** The count must see rows the saver cannot read: a delegate filing for someone under private sharing, or a room booked by others. Without it the hook's `ctx.api` reads as the saver (see diff --git a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts index 2b7747248c9..595cf5717c7 100644 --- a/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts +++ b/packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts @@ -45,12 +45,11 @@ const TEMPLATE = { const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: - end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0) diff --git a/skills/objectstack-data/references/data-hooks.md b/skills/objectstack-data/references/data-hooks.md index ad58a996f66..b3cae97fdb5 100644 --- a/skills/objectstack-data/references/data-hooks.md +++ b/skills/objectstack-data/references/data-hooks.md @@ -774,12 +774,11 @@ export default defineHook({ const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch const off = ['rejected', 'cancelled']; if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return; - const day = (v) => String(v).slice(0, 10); // the day a date field stores, however it was written const where = { owner_id: r.owner_id, status: { $nin: off }, // fail closed: a new status counts until listed here - start_at: DATE_ONLY ? { $lte: day(r.end_at) } : { $lt: r.end_at }, // datetime is half-open: - end_at: DATE_ONLY ? { $gte: day(r.start_at) } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap + start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open: + end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap }; if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself if (await ctx.api.object(ctx.object).count({ where }) > 0)