Skip to content

Commit b5f2f51

Browse files
docs(skills): a vetted overlap-check hook template for insert and update (#33292)
<!-- claude-projects-attribution: {"github_login":"os-project-manager"} --> _Requested by **Leehom** · [project thread](https://claude.ai/code/project/chan_01TenzsRopZj4jMbvjX8uz1X?thread=cmsg_01TenzsRopZj4jMbvjX8uz1X2NVS6pciqFPUxUV9WLGvXv)_ domain:skills#1 · os-project-manager · session_01FEkQ5kKeYvkiYDEFCNhNhU Fixes #32979 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:按裁决 6876330213「脚本模板,内核不动」,在已发布的数据技能 `skills/objectstack-data/references/data-hooks.md` 加了第 5 个模式「同一人的时间段不能重叠」的 hook 模板,文档页 `content/docs/automation/hooks.mdx` 加同一模板和逐行原因。模板同时适用日期时间字段(前闭后开,18:00 结束与 18:00 开始不算重叠)和纯日期字段(作者把模板里的 `DATE_ONLY` 设为 true 后结束日算在内,同一天请两次会被拒;不论日期写成 `2026-11-10`、完整 ISO 时刻还是 `Date` 都一样),并以 `runAs: 'system'` 计数,保存人看不到的记录(如代人提交、私有共享)也算在内。两处都写明已知缺口(并发两次保存可同时通过、回收站恢复不跑插入 hook、关闭自动化的导入跳过 hook、同一批量插入或更新内的行互相看不见、没有开始或结束的行不检查也不计入)。 - 为什么改:平台没有跨记录的重叠校验,裁决定为暂用 hook 脚本;AI 作者此前没有经过验证的写法,容易漏掉更新、漏掉排除自身、或把状态写成 `$in` 白名单。 - 风险与回滚:只改教学文本和一个测试文件,不动 spec、引擎、数据层或运行时;技能文件为腾出 token 删掉了 Key Properties 下五个重复小节(object/events/priority/async/onError)、Hook Context API 下重复的 `previous` 示例和 Cross-Object API 小注,文件净 −45 token、−59 行,未抬天花板。回滚即还原本 PR。 - 先看:① `skills/objectstack-data/references/data-hooks.md` 新增的 pattern 5 一段;② 同文件被删的七处重复(五个小节、`previous` 示例、Cross-Object API 小注);③ `packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts`。 - 两分钟验证:`pnpm --filter @objectstack/runtime exec vitest run --project local src/sandbox/overlap-hook-template.integration.test.ts`,预期 8 个用例全绿(真实 SQLite + QuickJS 沙箱跑模板本身)。 - 需要你做的:受管面 Tier H(`skills/**`):由你合并,或授权账号 APPROVED 后由席位落地。 ## What changes - **`skills/objectstack-data/references/data-hooks.md`** (the file that already teaches data hooks): Common Patterns gains **5. No two of mine overlap (sandboxed `body`)**: one when-to-use line, the template, and one known-limits paragraph. The template is a `beforeInsert` + `beforeUpdate` hook that - merges the stored row under the patch on update (`Object.assign({}, ctx.previous, ctx.input)`), - leaves the record itself out (`id: { $ne: ctx.previous.id }`), - names the ignored statuses with `$nin`, so a status added later, or a row with no status, still counts, and does not check a record saved in an ignored status, - uses half-open ranges for `datetime` fields (`start_at $lt end`, `end_at $gt start`) and, when the author sets the template's `DATE_ONLY` constant for `date` fields, an inclusive end day (`$lte` / `$gte`). The kind is stated, not read off the value: a `before*` hook sees the value as the caller wrote it, and a `date` field also takes a full ISO instant or a `Date`. The template does not cut the values to the day itself; the driver reads each comparand by the field's own storage rule (measured below), - declares `runAs: 'system'`, so the count also sees rows the saver cannot read (a delegate under private sharing, someone else's room booking); only the hook's `ctx.api` is elevated, the write itself runs as the saver, - counts in `ctx.object`, so the body names no object; the lead-in says to rename the hook's `name` (the refusal's translation key follows it), its `object` and its fields, - refuses through a declared `refusals` entry (`OVERLAP`, status 409), so the message is fixed and translatable. The limits stated next to it: the ruling's three (recycle-bin restore runs no insert hook; an import with automations off skips hooks; rows of one bulk insert do not see each other, widened to bulk update), the read-then-write race (two concurrent saves can both pass), which the ruling's own "without a concurrency guarantee" names, and a row with no start or end is neither checked nor counted. - **Paid for in the same file**, no ceiling raise: the `object`, `events`, `priority`, `async` and `onError` subsections under Key Properties are deleted, and so are the `previous` example under Hook Context API (it restated the sandbox `ctx` table's `ctx.previous` row and the `HookContext` interface's `previous` member) and the Cross-Object API note there (it restated the `ctx.api.object(name)` section: the repository bound to the current transaction, and `where` as the query key). Each restated what the file already says one screen up or below: the `defineHook` example's own comments (`// string | string[] | '*'`, the event list, `priority` "lower runs first; System: 0-99, App: 100-999, User: 1000+", `async` "after* events only"), the Before vs After table's Transaction and Error-handling rows (`async: true` runs after commit; `onError` defaults to `'abort'` for every hook, set `'log'` on side-effect hooks), and Best Practices (`object: '*'` sparingly; `async: true` for non-critical work). No link in the repo points at their anchors (`git grep` for each anchor: 0 hits). - **`content/docs/automation/hooks.mdx`** (the record hooks page): a new section **Recipe — refuse overlapping time ranges** before Hook Context, with the same template byte for byte, one bullet per rule saying why it is there (the `runAs` bullet links the page's own Elevation section), and the limits. Room and shift bookings are named as the same rule grouped by the room or shift. - **`packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts`**: the proving test (below). - **`.changeset/32979-skills-overlap-hook-template.md`**: `'@objectstack/skills': patch` (`skills/**` ships in that package). No spec key, no `exclusions` key, no engine, data-layer or runtime change. ## Why each call in the template is the one on `main` Read on `origin/main` d4fbb4d: | Template call | Where the runtime defines it | |---|---| | `events: ['beforeInsert', 'beforeUpdate']` | `packages/spec/src/data/hook.zod.ts` L389-L390 (the event enum) | | `ctx.previous` is the stored row on update, `undefined` on insert | `packages/runtime/src/sandbox/body-runner.ts` L1481-L1483 (`buildSandboxContext`) | | `ctx.input` on update carries only the changed fields | the same snapshot (`unwrapProxyToPlain(engineCtx.input)`, L1411); taught at data-hooks.md's `ctx.input` row | | `runAs: 'system'` elevates only the hook's `ctx.api` (`isSystem: true`, `userId` kept) | `packages/spec/src/data/hook.zod.ts` L720 (`runAs`), `packages/objectql/src/hook-run-as.ts` L24-L28 and `deriveHookApi` L196; pinned for a body by `packages/runtime/src/sandbox/hook-run-as.integration.test.ts` | | `ctx.object` is the object the hook fired on | data-hooks.md's sandbox `ctx` table | | `ctx.api.object(name).count({ where })`, gated by `api.read` | `body-runner.ts` L1167-L1168 (`count`), `packages/runtime/src/sandbox/quickjs-runner.ts` L705 (the read set the gate grants to `api.read`) | | `refusals` + `throw Object.assign(new Error(), { code })` answered with the declared entry | `hook.zod.ts` L665 (`refusals`), `body-runner.ts` L534-L539 (catch hands the throw to `resolveHookRefusal`), `packages/runtime/src/sandbox/hook-refusal-catalogue.ts` L160 | ## Tests `packages/runtime/src/sandbox/overlap-hook-template.integration.test.ts` runs the template's hook in composition (real `ObjectQL`, real SQLite driver, the real `QuickJSScriptRunner`, `bindHooksToEngine`; the harness of `hook-capability-denial-is-a-refusal.integration.test.ts`) on a `leave_request` object with `datetime` fields and, bound unchanged but for `name`, `object` and `DATE_ONLY = true`, on a `leave_day` object with `date` fields, under a middleware that stands in for private sharing (an unelevated read of `leave_request` sees only rows its user filed). It reads every refusal off `mapDataError` (status 409, `declaredCode: 'OVERLAP'`, the declared sentence): 1. overlapping insert refused, nothing written; 2. fail closed: a sibling with no status, or a status the list does not name, still counts; 3. adjacent ranges (half-open), another owner, a rejected sibling and a rejected write all accepted; 4. an update whose patch carries only `start_at` and moves into overlap is refused (stored row merged), and reviving a rejected row into overlap is refused; 5. updating the record itself (other field, or a range that still overlaps only its own stored row) is not refused; 6. `date` fields: the same day twice and a range ending on a booked day are refused, the next day and the day before are accepted, and an update that keeps the stored end and moves the start into another row's days is refused; 7. `date` fields, written the long way: a day written as a full ISO instant, or as a `Date`, over a booked day is refused; the next day written that way is accepted and stored as `2026-11-11`; 8. a delegate whose own read does not see the owner's row (count 0 under the stand-in) is still refused, because the count runs `runAs: 'system'`. On head e417fbf: `Test Files 1 passed (1) · Tests 8 passed (8)`. **The test can fail**: one mutation per rule, each run on e417fbf through `node scripts/ablation-replace.mjs` on the test's copy (the three copies are byte-identical), then restored; the test file's blob matched `HEAD` after every run: | Mutation | Result | |---|---| | pick the arm by spelling again: `start_at: DATE_ONLY ?` to `start_at: String(r.end_at).length === 10 ?` | 1 failed (case 7) | | delete the `DATE_ONLY ?` inclusive arm on `start_at` | 2 failed (cases 6, 7) | | delete the `DATE_ONLY ?` inclusive arm on `end_at` | 2 failed (cases 6, 7) | | drop `where.id = { $ne: ctx.previous.id }` | 2 failed (cases 5, 6) | | `$lt` to `$lte` on the datetime `start_at` arm | 1 failed (case 3) | | `$nin: off` to `$in: ['approved']` | 1 failed (case 2) | | `Object.assign({}, ctx.previous, ctx.input)` to `Object.assign({}, ctx.input)` | 2 failed (cases 4, 6) | | delete the `runAs: 'system'` line | 1 failed (case 8) | Readings taken while writing it: the first two are probes, not kept. A row with a `null` status is counted by `$nin` (the engine does not drop it as SQL `NOT IN` would), and a `+08:00` input is normalised before the comparison (19:00+08:00 to 20:00+08:00 overlaps 10:30Z to 13:30Z and is refused; kept in case 1). The third shaped round 2: a first cut of the template sliced both ends to `YYYY-MM-DD` in the hook, and the mutation removing that slice stayed green (8 passed), because the drivers already read a `date` comparand by the field's storage rule (`temporalStorageForm` in `@objectstack/core`, called from `driver-sql`, `driver-turso`, `driver-memory` and `driver-mongodb`). The slice was dropped: it proved nothing and would have mangled a value that is not a string. `pnpm --filter @objectstack/runtime typecheck` (tsc plus `check:test-typecheck`): exit 0. ## Acceptance notes - **The test holds a copy of the template**, not a read of `skills/`: `@objectstack/runtime`'s suites read nothing outside the package, and the claim's file surface does not include `scripts/cross-package-test-inputs.mjs` or `packages/runtime/vitest.repo-tests.json`, which a read would need. The three copies (skills, docs, test) are byte-identical on this head; the test's header says to edit it with the template. class: observation · reach: none · carrier: none. - **Elevation is measured against a stand-in for sharing**, not `plugin-security` itself: the middleware filters exactly where the security middleware does (`opCtx.context.isSystem`, `hook-run-as.ts` L24-L27 says it short-circuits on that flag before every row-level gate). class: observation · reach: none · carrier: none. - **Docs page budget**: +79 lines (379 to 458) against the order's +80. ## Skills readings Measured with `node scripts/check-skills-token-ratchet.mjs` on `origin/main` d4fbb4d and on head e417fbf: | | before | after | delta | |---|---|---|---| | `skills/objectstack-data/references/data-hooks.md` lines | 943 | 884 | −59 | | same file, tokens (ceiling 10011) | 10007 | 9962 | −45 | | all `SKILL.md` files (lines) | unchanged | unchanged | 0 (no SKILL.md touched) | | bundle total (whole shipped tree, tokens) | 244205 | 244160 | −45 | New text is paid by deleting restatement in the same file; no ceiling moves, so no raise path is used. ## Verification Round 2 answers delta review 6881070935 (PASS on da1e590 with one should-fix and one nit): - **F1r (the date arm picked by spelling).** The template no longer reads the field kind off the value. The author states it: `const DATE_ONLY = false; // true when start_at / end_at are date fields`, and the arm follows the constant. Case 7 writes the day as a full ISO instant and as a `Date` and is still refused; the mutation that puts the old spelling test back turns case 7 red. The normalisation the review offered as part of that option was tried and dropped on measurement: the drivers already read a `date` comparand as the stored day, so a slice in the hook changed nothing a test can see (see Tests). The docs sentence "A `date` value is `YYYY-MM-DD`, ten characters" is gone; the docs bullet now says the flag is needed because a `before*` hook sees the value as written, and that the query reads each value as the day it stores. The changeset's "the same day cannot be booked twice" now reads "for `date` fields the author sets `DATE_ONLY`, which counts the end day as booked". - **N4 (renaming).** Both lead-ins name what to rename: the skill says "renaming its `name`, `object` and fields (`date` fields: set `DATE_ONLY`)"; the docs say "rename its `name` (the refusal's translation key follows it), its `object` and its fields". - N1 and N2 stay as the accepted deviations. - Budgets: the skills file is 9962 / 10011 tokens and −59 lines against main; the extra round-2 cost was paid by deleting the Cross-Object API note (restatement of the `ctx.api.object(name)` section). The docs page is +79 lines (budget +80). The three copies are byte-identical on e417fbf. Checks on e417fbf: - `node scripts/pm/dispatch-gates.mjs --tier`: MANDATORY CONTRACT_REVIEW_TIER (`skills/**`, no one-line exit). - `node scripts/pm/check-governed-merges.mjs --branch claude/project-thread-0sjbar`, exit 3: GOVERNED, landing tier H (人合), `skills/**` ×1 (`skills/objectstack-data/references/data-hooks.md`); the other three paths are not on the register; 479 changed lines (+378 / −101), under the 3000 threshold; head repo NOT MEASURED (`--pr` reads it). - Proving test `Tests 8 passed (8)`; `pnpm --filter @objectstack/runtime typecheck` exit 0 (with `NODE_OPTIONS=--max-old-space-size=4096`; the default heap ran `check:test-typecheck`'s tsc out of memory, no diagnostics); `pnpm check:query-options-erasure` exit 0, test surface 236 (at the ceiling, unchanged). <details><summary>Gate list on e417fbf: 97 derived, 97 exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` at e417fbf derived the same 97 commands as round 1; each was run on that head with its exit code captured before any pipe, after building the `@objectstack/runtime` closure, `@objectstack/client-react...`, formula and lint under `os-verify-lock`. 96 exit 0 on the first pass, including `check:skill-examples` (the `os:check` block type-checks), `check:doc-anchors`, `check:doc-formula-expressions`, the skills token ratchet and `check:query-options-erasure`. `pnpm check:dual-build-cjs-loads` exited 3 (PREREQUISITE NOT MET, packages without `dist/`); after `turbo run build` of the whole tree under the lock (exit 0) it exits 0: 123 require entry points across 72 packages load. `--ran` reconciliation: "97 derived famil(ies) accounted for — 97 run, 0 NOT-MEASURED (a DERIVED zero — all 97 recorded an exit code and none of them is 3)", exit 0. Record: project file `pm-orders/skills/32979-gates-ran-r2.txt`. </details> Signed: domain:skills#1 · os-project-manager · session_01FEkQ5kKeYvkiYDEFCNhNhU --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kKeYvkiYDEFCNhNhU)_ <!-- signed: domain:skills#1 · os-project-manager · session_01FEkQ5pjSPT7ui2EUcunaVb --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7e61983 commit b5f2f51

4 files changed

Lines changed: 378 additions & 101 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
---
2+
'@objectstack/skills': patch
3+
---
4+
5+
docs(skills): a vetted hook template refuses two records of one owner over overlapping time
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
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.
11+
12+
- **`@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.
13+
- The record hooks page (`content/docs/automation/hooks.mdx`) carries the same template with the reason for each line and the same limits.

‎content/docs/automation/hooks.mdx‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,85 @@ would move a handler's own `ctx.api` writes *outside* the transaction the write
327327
ran in, which is a worse guarantee than the one documented here.
328328
</Callout>
329329

330+
## Recipe — refuse overlapping time ranges
331+
332+
Leave and overtime requests share one rule: two live records of the same owner
333+
may not cover the same time (a room or shift booking is the same rule grouped by
334+
the room or the shift). There is no declarative key for it, and a validation
335+
rule cannot see the other records, so write it as a `before*` hook on **both**
336+
insert and update. This is the vetted form; rename its `name` (the refusal's
337+
translation key follows it), its `object` and its fields:
338+
339+
```ts
340+
import { defineHook } from '@objectstack/spec/data';
341+
342+
export default defineHook({
343+
name: 'leave_request_no_overlap',
344+
object: 'leave_request',
345+
events: ['beforeInsert', 'beforeUpdate'],
346+
runAs: 'system', // count the rows the saver cannot read too
347+
refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } },
348+
body: {
349+
language: 'js',
350+
capabilities: ['api.read'],
351+
source: `
352+
const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too
353+
const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch
354+
const off = ['rejected', 'cancelled'];
355+
if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return;
356+
const where = {
357+
owner_id: r.owner_id,
358+
status: { $nin: off }, // fail closed: a new status counts until listed here
359+
start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open:
360+
end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap
361+
};
362+
if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself
363+
if (await ctx.api.object(ctx.object).count({ where }) > 0)
364+
throw Object.assign(new Error(), { code: 'OVERLAP' });
365+
`,
366+
},
367+
});
368+
```
369+
370+
Each line is there for a reason:
371+
372+
- **Merge the stored row under the patch.** On update `ctx.input` carries only
373+
the fields this write changes, so a patch that moves `start_at` alone must be
374+
judged with the stored `end_at`, `owner_id` and `status`.
375+
- **Exclude the record itself** with `id: { $ne: … }`, or every update of a
376+
booking collides with its own stored row.
377+
- **Name the ignored statuses with `$nin` (or `$ne`), never the live ones with
378+
`$in`.** A status added later then counts as live until someone decides
379+
otherwise, and a row with no status counts too. A record saved in an ignored
380+
status is not checked; reviving it into an overlap is refused.
381+
- **Half-open ranges for `datetime`.** `start < other.end && end > other.start`:
382+
a booking ending at 18:00 and one starting at 18:00 do not overlap.
383+
- **Inclusive end days for `date` — set `DATE_ONLY`.** A one-day leave has
384+
`start == end`, so the half-open test would let the same day be booked twice.
385+
With `DATE_ONLY = true` the template compares with `<=` / `>=`. The flag is
386+
needed because a `before*` hook sees the value as it was written: a `date`
387+
field also takes a full ISO instant or a `Date`, so the spelling does not say
388+
which kind the field is. The query reads each value as the day it stores.
389+
- **`runAs: 'system'`.** The count must see rows the saver cannot read: a
390+
delegate filing for someone under private sharing, or a room booked by
391+
others. Without it the hook's `ctx.api` reads as the saver (see
392+
[Elevation](#elevation--runas)) and misses them. The hook only counts; the
393+
write itself still runs as the saver.
394+
- **`ctx.api.object(ctx.object)`** counts in the object the hook fired on, so
395+
the body names no object.
396+
- **A declared refusal.** The body throws the code alone; the saver gets the
397+
catalogue's fixed sentence (translated through the key
398+
`hooks.leave_request_no_overlap.refusals.OVERLAP.message`) and the caller a
399+
`409` whose `declaredCode` is `OVERLAP`.
400+
401+
Known limits — the hook does not cover these, so do not assume it does:
402+
403+
- It reads, then the write happens: two saves at the same moment can both pass.
404+
- A recycle-bin restore runs no insert hook.
405+
- An import run with automations off skips hooks.
406+
- Rows of one bulk insert or bulk update do not see each other.
407+
- A row with no start or no end is neither checked nor counted.
408+
330409
## Hook Context
331410

332411
`handler` receives a `HookContext` with these fields:
Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The overlap-check hook template, run as written.
5+
*
6+
* Ruling 6876330213 keeps "no two of mine overlap" in hook scripts (no
7+
* `exclusions` key, no kernel change) and orders a vetted template into the
8+
* published skill (`skills/objectstack-data/references/data-hooks.md`,
9+
* pattern 5) and the docs (`content/docs/automation/hooks.mdx`). This file is
10+
* the vetting: {@link TEMPLATE} is that template's hook, byte for byte, and
11+
* it runs here in composition — a real `ObjectQL`, a real SQLite driver, the
12+
* real `QuickJSScriptRunner` and hook binder — for the cases the order and
13+
* its contract review name (overlap on insert and update, adjacency, self
14+
* update, ignored statuses, inclusive `date` end days with `DATE_ONLY` set
15+
* however the day is written, a saver who cannot read the overlapping row),
16+
* read off `mapDataError`, the ADR-0112 table every data door answers with.
17+
*
18+
* The copy is held here, not read from `skills/`: this package's suites do
19+
* not read outside it. When you edit the template there, edit it here.
20+
*/
21+
22+
import { describe, it, expect, afterEach } from 'vitest';
23+
import { mkdtempSync, rmSync } from 'node:fs';
24+
import { tmpdir } from 'node:os';
25+
import { join } from 'node:path';
26+
import type { ExecutionContext } from '@objectstack/spec/kernel';
27+
import { mapDataError } from '@objectstack/types';
28+
import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql';
29+
import { SqlDriver } from '@objectstack/driver-sql';
30+
import { hookBodyRunnerFactory } from './body-runner.js';
31+
import { QuickJSScriptRunner } from './quickjs-runner.js';
32+
33+
/** The published template's hook (data-hooks.md pattern 5), byte for byte. */
34+
const TEMPLATE = {
35+
name: 'leave_request_no_overlap',
36+
object: 'leave_request',
37+
events: ['beforeInsert', 'beforeUpdate'],
38+
runAs: 'system', // count the rows the saver cannot read too
39+
refusals: { OVERLAP: { message: 'This overlaps another request of yours.', status: 409 } },
40+
body: {
41+
language: 'js',
42+
capabilities: ['api.read'],
43+
source: `
44+
const DATE_ONLY = false; // true when start_at / end_at are date fields: the end day is booked too
45+
const r = Object.assign({}, ctx.previous, ctx.input); // update: stored row under the patch
46+
const off = ['rejected', 'cancelled'];
47+
if (!r.owner_id || !r.start_at || !r.end_at || off.includes(r.status)) return;
48+
const where = {
49+
owner_id: r.owner_id,
50+
status: { $nin: off }, // fail closed: a new status counts until listed here
51+
start_at: DATE_ONLY ? { $lte: r.end_at } : { $lt: r.end_at }, // datetime is half-open:
52+
end_at: DATE_ONLY ? { $gte: r.start_at } : { $gt: r.start_at }, // 18:00 end, 18:00 start is no overlap
53+
};
54+
if (ctx.previous) where.id = { $ne: ctx.previous.id }; // not the record itself
55+
if (await ctx.api.object(ctx.object).count({ where }) > 0)
56+
throw Object.assign(new Error(), { code: 'OVERLAP' });
57+
`,
58+
},
59+
};
60+
61+
const LEAVE = {
62+
name: 'leave_request',
63+
fields: {
64+
owner_id: { type: 'text', name: 'owner_id' },
65+
start_at: { type: 'datetime', name: 'start_at' },
66+
end_at: { type: 'datetime', name: 'end_at' },
67+
status: { type: 'text', name: 'status' },
68+
note: { type: 'text', name: 'note' },
69+
filed_by: { type: 'text', name: 'filed_by' },
70+
},
71+
};
72+
73+
/** The author's one edit for `date` fields, made exactly once. */
74+
function dateOnly(source: string): string {
75+
const flag = 'const DATE_ONLY = false;';
76+
expect(source.split(flag)).toHaveLength(2);
77+
return source.replace(flag, 'const DATE_ONLY = true;');
78+
}
79+
80+
/** The same template on `date` fields, where the end day is inclusive. */
81+
const LEAVE_DAY = {
82+
name: 'leave_day',
83+
fields: {
84+
owner_id: { type: 'text', name: 'owner_id' },
85+
start_at: { type: 'date', name: 'start_at' },
86+
end_at: { type: 'date', name: 'end_at' },
87+
status: { type: 'text', name: 'status' },
88+
},
89+
};
90+
91+
/**
92+
* A stand-in for private sharing: an unelevated read of `leave_request` sees
93+
* only the rows its user filed. `runAs: 'system'` is what lets the template's
94+
* count see past it.
95+
*/
96+
function filedByOnly(opCtx: any, next: () => Promise<unknown>) {
97+
if (opCtx.object === 'leave_request' && (opCtx.operation === 'count' || opCtx.operation === 'find')
98+
&& opCtx.context && !opCtx.context.isSystem && opCtx.ast) {
99+
const mine = { filed_by: opCtx.context.userId ?? null };
100+
opCtx.ast = { ...opCtx.ast, where: opCtx.ast.where ? { $and: [opCtx.ast.where, mine] } : mine };
101+
}
102+
return next();
103+
}
104+
105+
describe('overlap-check hook template (data-hooks.md pattern 5)', () => {
106+
let engine: ObjectQL | null = null;
107+
let dir: string | null = null;
108+
109+
afterEach(async () => {
110+
try { await engine?.destroy(); } catch { /* noop */ }
111+
engine = null;
112+
if (dir) { rmSync(dir, { recursive: true, force: true }); dir = null; }
113+
});
114+
115+
async function boot(): Promise<ObjectQL> {
116+
dir = mkdtempSync(join(tmpdir(), 'os-overlap-template-'));
117+
const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: join(dir, 'data.sqlite') }, useNullAsDefault: true });
118+
await driver.initObjects([LEAVE, LEAVE_DAY]);
119+
engine = new ObjectQL();
120+
engine.registerDriver(driver as any, true);
121+
await engine.init();
122+
for (const o of [LEAVE, LEAVE_DAY]) engine.registry.registerObject(o as any);
123+
engine.registerMiddleware(filedByOnly as any);
124+
const bodyRunner = hookBodyRunnerFactory(new QuickJSScriptRunner(), { ql: engine, appId: 'overlap' });
125+
// The template as written, and the same hook bound to the `date` object with the
126+
// one edit an author makes for date fields: `DATE_ONLY = true`.
127+
const DAYS = { ...TEMPLATE, name: 'leave_day_no_overlap', object: 'leave_day', body: { ...TEMPLATE.body, source: dateOnly(TEMPLATE.body.source) } };
128+
bindHooksToEngine(engine, [TEMPLATE as any, DAYS as any], { packageId: 'overlap', bodyRunner });
129+
return engine;
130+
}
131+
132+
const day = (from: string, to: string, extra: Record<string, unknown> = {}) => ({
133+
owner_id: 'u1',
134+
start_at: `2026-11-10T${from}:00.000Z`,
135+
end_at: `2026-11-10T${to}:00.000Z`,
136+
status: 'approved',
137+
...extra,
138+
});
139+
140+
async function refusal(p: Promise<unknown>) {
141+
const err = await p.then(() => null, (x) => x);
142+
expect(err, 'the write must be refused').not.toBeNull();
143+
return mapDataError(err);
144+
}
145+
146+
function expectOverlapRefusal(r: ReturnType<typeof mapDataError>) {
147+
expect(r.status).toBe(409);
148+
expect((r.body as any).declaredCode).toBe('OVERLAP');
149+
expect(String(r.body.error)).toContain('This overlaps another request of yours.');
150+
}
151+
152+
it('refuses an insert that overlaps a live row of the same owner, and writes nothing', async () => {
153+
const e = await boot();
154+
await e.insert('leave_request', day('18:30', '21:30'));
155+
expectOverlapRefusal(await refusal(e.insert('leave_request', day('18:30', '21:30', { status: 'draft' }))));
156+
expectOverlapRefusal(await refusal(e.insert('leave_request', day('20:00', '23:00'))));
157+
// The same instant spelled with an offset: 19:00+08:00 is 11:00Z, inside 10:30Z to 13:30Z.
158+
await e.insert('leave_request', day('10:30', '13:30'));
159+
expectOverlapRefusal(await refusal(e.insert('leave_request',
160+
{ owner_id: 'u1', start_at: '2026-11-10T19:00:00+08:00', end_at: '2026-11-10T20:00:00+08:00', status: 'approved' })));
161+
expect(await e.count('leave_request', {})).toBe(2);
162+
}, 30_000);
163+
164+
it('fails closed: a sibling with no status, or in a status the list does not name, still counts', async () => {
165+
const e = await boot();
166+
await e.insert('leave_request', day('08:00', '09:00', { status: null }));
167+
await e.insert('leave_request', day('10:00', '11:00', { status: 'escalated' }));
168+
expectOverlapRefusal(await refusal(e.insert('leave_request', day('08:30', '08:45'))));
169+
expectOverlapRefusal(await refusal(e.insert('leave_request', day('10:30', '10:45'))));
170+
}, 30_000);
171+
172+
it('accepts an adjacent range (half-open), another owner, and a row with an ignored status', async () => {
173+
const e = await boot();
174+
await e.insert('leave_request', day('18:30', '21:30'));
175+
await e.insert('leave_request', day('21:30', '23:00'));
176+
await e.insert('leave_request', day('17:00', '18:30'));
177+
await e.insert('leave_request', day('18:30', '21:30', { owner_id: 'u2' }));
178+
// The rejected row is ignored as a sibling, and a rejected write is not checked.
179+
await e.insert('leave_request', day('19:00', '20:00', { status: 'rejected' }));
180+
await e.insert('leave_request', day('09:00', '10:00', { status: 'rejected' }));
181+
await e.insert('leave_request', day('09:30', '10:30'));
182+
expect(await e.count('leave_request', {})).toBe(7);
183+
}, 30_000);
184+
185+
it('refuses an update that moves a row into overlap, merging the stored row under the patch', async () => {
186+
const e = await boot();
187+
await e.insert('leave_request', day('18:30', '21:30'));
188+
const later = await e.insert('leave_request', day('22:00', '23:00')) as any;
189+
// The patch carries only `start_at`; `end_at`, `owner_id` and `status` come from the stored row.
190+
expectOverlapRefusal(await refusal(e.update('leave_request', { id: later.id, start_at: '2026-11-10T21:00:00.000Z' })));
191+
// Reviving a rejected row into an overlap is refused too.
192+
const dead = await e.insert('leave_request', day('19:00', '20:00', { status: 'rejected' })) as any;
193+
expectOverlapRefusal(await refusal(e.update('leave_request', { id: dead.id, status: 'approved' })));
194+
}, 30_000);
195+
196+
it('does not refuse an update of the record against itself', async () => {
197+
const e = await boot();
198+
const row = await e.insert('leave_request', day('18:30', '21:30')) as any;
199+
await e.update('leave_request', { id: row.id, note: 'renamed' });
200+
await e.update('leave_request', { id: row.id, start_at: '2026-11-10T18:00:00.000Z' });
201+
const got = await e.findOne('leave_request', { where: { id: row.id } }) as any;
202+
expect(got.note).toBe('renamed');
203+
}, 30_000);
204+
205+
it('date fields: the end day is inclusive, so the same day twice is refused and the next day is not', async () => {
206+
const e = await boot();
207+
const d = (from: string, to: string, extra: Record<string, unknown> = {}) =>
208+
({ owner_id: 'u1', start_at: from, end_at: to, status: 'approved', ...extra });
209+
await e.insert('leave_day', d('2026-11-10', '2026-11-10'));
210+
expectOverlapRefusal(await refusal(e.insert('leave_day', d('2026-11-10', '2026-11-10'))));
211+
expectOverlapRefusal(await refusal(e.insert('leave_day', d('2026-11-09', '2026-11-10'))));
212+
await e.insert('leave_day', d('2026-11-11', '2026-11-12'));
213+
await e.insert('leave_day', d('2026-11-09', '2026-11-09'));
214+
// An update that keeps the stored (date) end and moves the start into another row's days.
215+
const later = await e.insert('leave_day', d('2026-11-14', '2026-11-14')) as any;
216+
expectOverlapRefusal(await refusal(e.update('leave_day', { id: later.id, start_at: '2026-11-12' })));
217+
await e.update('leave_day', { id: later.id, start_at: '2026-11-13' });
218+
expect(await e.count('leave_day', {})).toBe(4);
219+
}, 30_000);
220+
221+
it('date fields: a day written as a full ISO instant or as a Date is the day stored, and still refused', async () => {
222+
const e = await boot();
223+
await e.insert('leave_day', { owner_id: 'u1', start_at: '2026-11-10', end_at: '2026-11-10', status: 'approved' });
224+
expectOverlapRefusal(await refusal(e.insert('leave_day',
225+
{ owner_id: 'u1', start_at: '2026-11-10T00:00:00.000Z', end_at: '2026-11-10T00:00:00.000Z', status: 'approved' })));
226+
expectOverlapRefusal(await refusal(e.insert('leave_day',
227+
{ owner_id: 'u1', start_at: new Date('2026-11-10T00:00:00Z'), end_at: new Date('2026-11-10T00:00:00Z'), status: 'approved' })));
228+
// The next day, written the long way, is not a clash; and it is stored as its day.
229+
const next = await e.insert('leave_day',
230+
{ owner_id: 'u1', start_at: new Date('2026-11-11T00:00:00Z'), end_at: '2026-11-11T00:00:00.000Z', status: 'approved' }) as any;
231+
const got = await e.findOne('leave_day', { where: { id: next.id } }) as any;
232+
expect([got.start_at, got.end_at]).toEqual(['2026-11-11', '2026-11-11']);
233+
}, 30_000);
234+
235+
it('runs elevated: a saver who cannot read the overlapping row is still refused', async () => {
236+
const e = await boot();
237+
await e.insert('leave_request', day('18:30', '21:30', { filed_by: 'u1' }));
238+
const delegate: ExecutionContext = { userId: 'd1', tenantId: 'org_1', isSystem: false, positions: [], permissions: [] };
239+
// The delegate's own read does not see u1's row…
240+
expect(await e.count('leave_request', {}, { context: delegate })).toBe(0);
241+
// …and the template's count, declared `runAs: 'system'`, does.
242+
expectOverlapRefusal(await refusal(e.insert('leave_request', day('19:00', '20:00', { filed_by: 'd1' }), { context: delegate })));
243+
}, 30_000);
244+
});

0 commit comments

Comments
 (0)