Skip to content

Commit 5ce459b

Browse files
committed
fix(runtime): a hook body sends no mail; a body's timeline entry commits or rolls back with its write
Co-authored-by: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016WV4cwV8gsjrvCXCqKoaiG
1 parent 8878bc8 commit 5ce459b

17 files changed

Lines changed: 471 additions & 47 deletions

‎.changeset/body-mail-activity-doors.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,9 @@ Metadata-protocol: added
2121
<!-- adr-0087: not-required (no-migration-prescription) no key, export or field is removed and no stored body changes shape; the change is which sender delivers a row an app inserted, and moving that app to the mail door is a code change no conversion can make for it -->
2222

2323
- **`@objectstack/spec`:** two new body capabilities, `email.send` and `activity.append`, and their inputs `BodyMailSendInputSchema` and `BodyActivityAppendInputSchema` (`@objectstack/spec/data`). The sender, the sending user, the organization, the actor and the origin are stamped by the platform and are not inputs: a key outside either shape is refused. Every string either input takes has an upper bound, and the limits that read across fields (`BODY_MAIL_RECIPIENT_LIMIT`, `BODY_MAIL_ADDRESS_LIST_LIMIT`, `BODY_MAIL_ADDRESS_LIMIT`, `BODY_ACTIVITY_METADATA_LIMIT`) are stated in each schema's description. `SYS_ACTIVITY_PLATFORM_TYPES` names the timeline types only the platform records. `SendEmailInput.requireLogRow` (`@objectstack/spec/contracts`) asks the mail service to send a message only if its log records it.
24-
- **`@objectstack/runtime`:** a hook, action or job body that declares the capability calls `ctx.email.send({ to, subject, text })` or `ctx.activity.append({ object, recordId, type, summary })`. A message is sent from the configured sender, as the calling user, under the caller's organization; a timeline entry is written with the calling user as its actor and the package and body as its origin. A record the call points at must be one the caller can read, in the caller's own scope: for a hook, the user of the write that fired it, never the system. A message names at most 50 recipients, each recipient list and `replyTo` fits the mail log as recorded, a message is sent only if the mail log records it, and an organization's mail is held to `OS_EMAIL_APP_SEND_HOURLY_LIMIT` messages an hour (default 200) before the door refuses another. A door call inside `ctx.api.transaction` is refused with `409 RESOURCE_CONFLICT`. An entry's origin names the package that holds the body. A body with no calling user (a job) sends and writes with no user recorded.
24+
- **`@objectstack/runtime`:** an action or a job body that declares the capability calls `ctx.email.send({ to, subject, text })`, and a hook, action or job body `ctx.activity.append({ object, recordId, type, summary })`. A message is sent from the configured sender, as the calling user, under the caller's organization; a timeline entry is written with the calling user as its actor and the package and body as its origin. A record the call points at must be one the caller can read, in the caller's own scope: for a hook, the user of the write that fired it, never the system. A message names at most 50 recipients, each recipient list and `replyTo` fits the mail log as recorded, a message is sent only if the mail log records it, and an organization's mail is held to `OS_EMAIL_APP_SEND_HOURLY_LIMIT` messages an hour (default 200) before the door refuses another. A message cannot be taken back, so a hook body cannot send mail (`403 PERMISSION_DENIED`); an action or a job body sends it, and is refused with `409 RESOURCE_CONFLICT` while it runs inside a transaction. A timeline entry commits or rolls back with the write that runs the body. A door call inside the body's own `ctx.api.transaction` is refused with `409 RESOURCE_CONFLICT`. An entry's origin names the package that holds the body. A body with no calling user (a job) sends and writes with no user recorded.
2525
- **`@objectstack/cli`:** the build infers both capabilities from a handler's calls, under a renamed or destructured context too. `ExtractedBody.capabilities` on `@objectstack/cli/hook-body` may now hold `'email.send'` and `'activity.append'`.
26-
- **`@objectstack/objectql`:** `seedHookUserGrants` and `seedHookUnreadMembership`, the second step of a `runAs: 'user'` derivation and its fail-safe, are exported beside `deriveHookApi`.
26+
- **`@objectstack/objectql`:** `seedHookUserGrants` and `seedHookUnreadMembership`, the second step of a `runAs: 'user'` derivation and its fail-safe, are exported beside `deriveHookApi`. `openTransactionKind` answers whether a write runs inside a transaction that a write beside it joins (`'joined'`), one it cannot reach (`'separate'`), or none.
2727
- **`@objectstack/core`:** the bounds a caller-sent message is held to (the sending user, the organization, the configured sender) are one function, `boundCallerMail`, shared by the REST mail door and the body door.
2828
- **`@objectstack/rest`:** the REST mail door reads its bounds from `boundCallerMail`; its answers are unchanged.
2929
- **`@objectstack/plugin-email`:** a mail-log row the mail service did not write is delivered from the configured sender, with no sender header of its own (see BREAKING above). `send()` honours `requireLogRow`: when the row cannot be written, it refuses with `503 SERVICE_UNAVAILABLE` and delivers nothing.

‎content/docs/automation/hook-bodies.mdx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,8 +105,8 @@ The script sees only what the surrounding `ctx` object exposes:
105105
| `ctx.title('<lookup field>')` | The related record's title, through a lookup / master_detail / user / tree column. Costs one `findOne` (plus the lookups that record's own title reads through). | `api.read` |
106106
| `ctx.crypto.randomUUID()` | UUID generation. | `crypto.uuid` |
107107
| `ctx.log.{info,warn,error}` | Structured logging. | `log` |
108-
| `ctx.email.send({ to, subject, text })` | Sends mail through the mail service, from the configured sender, as the calling user and under the caller's organization. Refused inside `ctx.api.transaction`. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | `email.send` |
109-
| `ctx.activity.append({ object, recordId, type, summary })` | Adds an entry to a record's activity timeline. The platform stamps the calling user as the actor and the package and body as the entry's `origin`. `type` may not be one only the platform records (`SYS_ACTIVITY_PLATFORM_TYPES`), the record must be one the caller can read, and `metadata` takes at most 8,000 characters as JSON. Refused inside `ctx.api.transaction`. | `activity.append` |
108+
| `ctx.email.send({ to, subject, text })` | Sends mail through the mail service, from the configured sender, as the calling user and under the caller's organization. An action or a job body only: a hook body cannot send mail, because a message cannot be taken back if the write that runs the hook rolls back. Send mail on a record change from an action, a job or a flow. See [Email service](/docs/kernel/runtime-services/email-service#from-a-script-body). | `email.send` |
109+
| `ctx.activity.append({ object, recordId, type, summary })` | Adds an entry to a record's activity timeline. The platform stamps the calling user as the actor and the package and body as the entry's `origin`. `type` may not be one only the platform records (`SYS_ACTIVITY_PLATFORM_TYPES`), the record must be one the caller can read, and `metadata` takes at most 8,000 characters as JSON. The entry commits or rolls back with the write that runs the body. Refused inside the body's own `ctx.api.transaction`. | `activity.append` |
110110
| `ctx.connector(name).<method>(...)` _(planned)_ | Outbound HTTP / SaaS calls. **Not yet wired into the sandbox** — ships with the separate Connector spec. | (separate Connector spec) |
111111

112112
### Write provenance — `ctx.provenance`

‎content/docs/kernel/runtime-services/email-service.mdx‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,15 +32,16 @@ services.email.sendTemplate(input: SendTemplateInput): Promise<SendEmailResult>
3232

3333
## From a script body
3434

35-
A hook, action or job body sends mail with `ctx.email.send(input)` when it declares the `email.send` capability (`os build` infers it from the call). The input is `BodyMailSendInputSchema` (`@objectstack/spec/data`): `to`, `cc`, `bcc`, `replyTo`, `subject`, `text` and/or `html`, and `related`, the record the message is about.
35+
An action or a job body sends mail with `ctx.email.send(input)` when it declares the `email.send` capability (`os build` infers it from the call). The input is `BodyMailSendInputSchema` (`@objectstack/spec/data`): `to`, `cc`, `bcc`, `replyTo`, `subject`, `text` and/or `html`, and `related`, the record the message is about.
3636

3737
- The message is sent from the configured sender. Its display name names the calling user beside the organization, for example `Ann Lee via Acme`. Replies go to `replyTo`.
3838
- It is recorded as sent by the calling user and under the caller's organization, with the same bounds as the HTTP door. `from`, `sentBy`, `organizationId`, `headers` and `identityMail` are not inputs, and a call that names one is refused with `400 VALIDATION_ERROR`.
3939
- `related` must be a record the caller can read, in the caller's own scope. Otherwise the call is refused with `404 RECORD_NOT_FOUND` and nothing is sent.
4040
- A message names at most 50 recipients across `to`, `cc` and `bcc`. Each of the three takes at most 4,000 characters as the mail log records it (every recipient as `"Name" <address>`, joined by `, `), and a `replyTo` at most 320. The subject takes at most 998 characters, and `text` and `html` at most 1,000,000 each. A message over any of these is refused with `400 VALIDATION_ERROR`.
4141
- While the organization's mail log records `OS_EMAIL_APP_SEND_HOURLY_LIMIT` messages (default 200) in the last hour, the call is refused with `429 RATE_LIMIT_EXCEEDED`. A caller with no organization is counted against the whole log. The count is read before the send, so two calls racing for the last message of the hour can both be sent.
4242
- The message is sent only if the mail log records it. When the row cannot be written, the call is refused with `503 SERVICE_UNAVAILABLE` and nothing is sent.
43-
- A call made inside `ctx.api.transaction` is refused with `409 RESOURCE_CONFLICT`, because the door acts outside the body's transaction. Call it after the transaction commits.
43+
- A message cannot be taken back, so a hook body cannot send mail: the write that runs the hook may still roll back. A call from a hook body is refused with `403 PERMISSION_DENIED`. Send mail on a record change from an action, a job or a flow.
44+
- A call made while an action or a job runs inside a transaction, or inside the body's own `ctx.api.transaction`, is refused with `409 RESOURCE_CONFLICT`.
4445
- A job body has no calling user, so its message is recorded with no `sentBy`.
4546

4647
The call answers `{ id, status }`. A deployment with no mail service answers `501 NOT_IMPLEMENTED`.

‎content/docs/references/data/hook-body-doors.mdx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ timeline entry and the origin naming the body that wrote it. A key outside
2020
the shape is refused, never dropped, so a body that names one of those is
2121
told at the call.
2222

23+
A message cannot be taken back, so mail is sent from an action or a job
24+
body, never from a hook body; mail on a record change goes through an
25+
action, a job or a flow. A timeline entry is written with the write that
26+
runs the body, and commits or rolls back with it.
27+
2328
<Callout type="info">
2429
**Source:** `packages/spec/src/data/hook-body-doors.zod.ts`
2530
</Callout>
@@ -38,7 +43,7 @@ const result = BodyActivityAppendInputSchema.parse(data);
3843

3944
## BodyActivityAppendInput
4045

41-
ctx.activity.append input: one entry a script body adds to a record timeline. metadata is at most 8000 characters as JSON.
46+
ctx.activity.append input: one entry a script body adds to a record timeline; it commits or rolls back with the write that runs the body. metadata is at most 8000 characters as JSON.
4247

4348
### Properties
4449

@@ -78,7 +83,7 @@ A record the door reads in the caller's scope before it acts
7883

7984
## BodyMailSendInput
8085

81-
ctx.email.send input: a message a script body hands to the mail service. At most 50 recipients across to, cc and bcc together; each of to, cc and bcc at most 4000 characters as recorded ("Name" `<address>`, joined by ", "); a replyTo at most 320 characters as recorded.
86+
ctx.email.send input: a message an action or a job body hands to the mail service; a hook body cannot send mail. At most 50 recipients across to, cc and bcc together; each of to, cc and bcc at most 4000 characters as recorded ("Name" `<address>`, joined by ", "); a replyTo at most 320 characters as recorded.
8287

8388
### Properties
8489

‎packages/objectql/src/hook-run-as.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,11 @@ export function deriveHookApi(api: unknown, runAs: HookRunAs, ref: HookRunAsRef)
212212
* list and email (#24639) onto the api `withRunAs('user')` derived.
213213
*
214214
* A symbol, and ⛔ deliberately NOT re-exported from the package entry, so the
215-
* method is no NAMEABLE member of `ScopedContext`'s published face: only the
216-
* hook wrapper reaches it, through {@link seedHookUserGrants}. A public named
215+
* method is no NAMEABLE member of `ScopedContext`'s published face: it is
216+
* reached only through {@link seedHookUserGrants}, which the entry does export,
217+
* by the hook wrapper and by the runtime's script-body doors (`body-runner.ts`
218+
* `hookDoorCaller`, which reads one record's existence in the hook's calling
219+
* user's scope). A public named
217220
* method would widen the published surface, and it would also be a derivation
218221
* the runtime's stored-metadata seams (`deriveThroughSeam`) do not know, so a
219222
* seam-served host api calling it would get back an unserved context.

‎packages/objectql/src/index.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,10 @@ export {
379379
seedHookUserGrants,
380380
seedHookUnreadMembership,
381381
} from './hook-run-as.js';
382+
// Whether a write runs inside a transaction a write beside it joins, or one it
383+
// cannot reach: read by the runtime's script-body doors.
384+
export { openTransactionKind } from './open-transaction.js';
385+
export type { OpenTransactionKind } from './open-transaction.js';
382386
export type { HookRunAs, HookRunAsRef, RunAsDerivableApi } from './hook-run-as.js';
383387
// Boot guard: thrown by `ObjectQL.init()` when a registered driver's connect()
384388
// fails (framework#3741). Hosts that boot the engine themselves can catch it to
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import { describe, it, expect } from 'vitest';
4+
import { openTransactionKind } from './open-transaction.js';
5+
6+
function engineWith(ambient: unknown, closed: unknown[] = []) {
7+
return {
8+
txStore: { getStore: () => (ambient === undefined ? undefined : { transaction: ambient }) },
9+
isClosedUnitHandle: (h: unknown) => closed.includes(h),
10+
};
11+
}
12+
13+
describe('where a write stands with respect to a transaction', () => {
14+
const a = { tx: 'ambient' };
15+
const t = { tx: 'threaded' };
16+
17+
it('answers none with no open transaction', () => {
18+
expect(openTransactionKind(engineWith(undefined))).toBe('none');
19+
expect(openTransactionKind(engineWith(a, [a]), a)).toBe('none');
20+
});
21+
22+
it('answers joined for the ambient transaction, carried or not', () => {
23+
expect(openTransactionKind(engineWith(a))).toBe('joined');
24+
expect(openTransactionKind(engineWith(a), a)).toBe('joined');
25+
});
26+
27+
it('answers separate for a carried handle the ambient store does not hold', () => {
28+
expect(openTransactionKind(engineWith(undefined), t)).toBe('separate');
29+
expect(openTransactionKind(engineWith(a), t)).toBe('separate');
30+
});
31+
32+
it('reads an engine double from the carried handle alone', () => {
33+
expect(openTransactionKind({}, undefined)).toBe('none');
34+
expect(openTransactionKind({}, t)).toBe('separate');
35+
});
36+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Where a write stands with respect to a transaction, for code that acts
5+
* BESIDE that write through the engine (the runtime's script-body doors) and
6+
* must know whether what it writes will commit or roll back with it.
7+
*
8+
* - `'none'`: no transaction is open; a write through the engine stands alone.
9+
* - `'joined'`: the engine's ambient transaction is open (ADR-0034), and a
10+
* write through the engine joins it: it commits or rolls back with the
11+
* write that is running.
12+
* - `'separate'`: the running write carries a transaction handle the ambient
13+
* store does not hold (a sandboxed body's `ctx.api.transaction`, threaded
14+
* explicitly, ADR-0067). A write through the engine would take another
15+
* connection, outside it.
16+
*
17+
* A handle whose unit has already closed counts as no transaction. Read
18+
* through the engine's own ambient store and unit ledger, so the answer is the
19+
* one the engine's write path acts on.
20+
*/
21+
export type OpenTransactionKind = 'none' | 'joined' | 'separate';
22+
23+
interface TransactionReadableEngine {
24+
txStore?: { getStore(): { transaction?: unknown } | undefined };
25+
isClosedUnitHandle?: (handle: unknown) => boolean;
26+
}
27+
28+
/**
29+
* Answer {@link OpenTransactionKind} for a write running on `engine` whose
30+
* execution context carries `threaded` as its transaction handle (or none).
31+
* An engine that exposes neither the ambient store nor the unit ledger (a
32+
* double) is read from `threaded` alone.
33+
*/
34+
export function openTransactionKind(engine: unknown, threaded?: unknown): OpenTransactionKind {
35+
const e = engine as TransactionReadableEngine | undefined;
36+
const closed = (handle: unknown): boolean => {
37+
try {
38+
return typeof e?.isClosedUnitHandle === 'function' && e.isClosedUnitHandle(handle) === true;
39+
} catch {
40+
return false;
41+
}
42+
};
43+
let ambient: unknown;
44+
try {
45+
ambient = e?.txStore?.getStore()?.transaction;
46+
} catch {
47+
ambient = undefined;
48+
}
49+
const ambientOpen = ambient != null && !closed(ambient);
50+
const threadedOpen = threaded != null && !closed(threaded);
51+
if (threadedOpen && (!ambientOpen || threaded !== ambient)) return 'separate';
52+
return ambientOpen || threadedOpen ? 'joined' : 'none';
53+
}

‎packages/plugins/plugin-audit/src/app-activity-door.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,25 @@ describe('the activity door writes the actor, organization and origin the platfo
8787
expect(options.context).toEqual({ isSystem: true, tenantId: 'org_acme' });
8888
});
8989

90+
it('writes the entry, and reads its actor, under the transaction handle it is given', async () => {
91+
const { engine, inserts } = fakeEngine(columns);
92+
const read: unknown[] = [];
93+
const writer = createAppActivityWriter({
94+
getEngine: () => engine as any,
95+
getActorSnapshot: () => async (scope: any) => {
96+
read.push(scope.context);
97+
return { name: 'Ann Lee', avatarUrl: null };
98+
},
99+
});
100+
await writer.appendAppActivity(
101+
entry,
102+
{ actorId: 'usr_ann', organizationId: 'org_acme', origin: 'p/hook:h' },
103+
{ transaction: 'trx_1' },
104+
);
105+
expect(inserts[0].options.context).toEqual({ isSystem: true, tenantId: 'org_acme', transaction: 'trx_1' });
106+
expect(read).toEqual([{ isSystem: true, tenantId: 'org_acme', transaction: 'trx_1' }]);
107+
});
108+
90109
it('writes an entry with no user with an empty actor', async () => {
91110
const { engine, inserts } = fakeEngine(columns);
92111
const writer = createAppActivityWriter({ getEngine: () => engine as any, getActorSnapshot: () => snapshot });

0 commit comments

Comments
 (0)