Skip to content

Commit ecd10e9

Browse files
feat(runtime): createInProcessAuthoringRegistry, the light authoring door in process as the signed-in user (#37968)
<!-- claude-projects-attribution: {"github_login":"os-tesla"} --> _Requested by **Tesla** · [project thread](https://claude.ai/code/project/chan_01AXsQkLFKRdQCqQ3RTr6Jao?thread=cmsg_01AXsQkLFKRdQCqQ3RTr6JaoS1QowAYaTNxdd2oGhyXWGh)_ Fixes #37944 Clause-②: no Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:用户无感;云端问 AI 的管理员技能今后可以在服务器进程内、以当前登录用户身份调用框架的五个搭建工具(读元数据、存草稿、删草稿),不需要 OAuth 授权。 - 为什么做:云端问 AI 管理员技能(云端 M2 第一项)要用框架这套工具,否则云端得再抄一份约七百行、会和框架走样的副本。 - 出错会怎样:只影响管理员在应用内让 AI 存草稿;准入仍是本人的元数据管理权限,草稿照旧要人在 Studio 审阅后发布,合入后可直接回退。 - 要你做什么:无。 ## What changes - **Docs**: `packages/runtime/README.md` gains an *In-process authoring tools* section under API Reference (the package's published record of its API). `content/docs/permissions/system-context.mdx` gains row **61c** (the entry admits a system context nothing) with its regenerated register line, because the entry's fail-closed guard reads `isSystem`. - **New public entry** `createInProcessAuthoringRegistry(kernel, { executionContext, environmentId })` from `@objectstack/runtime` (`packages/runtime/src/in-process-authoring.ts`, beside `action-dispatch.ts`). It returns `{ admitted, getAll(), execute(toolCall) }`: the five tools of the MCP draft door (`list_metadata_items`, `get_metadata_item`, `list_drafts`, `save_metadata_draft`, `delete_metadata_draft`), bound to one signed-in person for one turn. Exported types: `InProcessAuthoringRequest`, `InProcessAuthoringRegistry`, `OpenAuthoringToolCall`, `OpenAuthoringToolResult`. - **One implementation.** The MCP door's assembly is factored out as `buildOpenAuthoringRegistry(deps, context, principal)` in `mcp-authoring.ts`; `resolveOpenAuthoringInjection` (the MCP door) and the new entry both call it. The private builders (`resolveHumanReader`, `openWriter`, `openReadGateSources`) are unchanged in body and still take `DomainHandlerDeps` + `HttpProtocolContext`; no second copy exists. - **Placement, as `dispatchAction`.** The entry takes the host kernel and runs on the same shared per-kernel `HttpDispatcher` as `dispatchAction` (`hostDispatcherFor(kernel)`, extracted in `action-dispatch.ts`; `dispatchAction` and `dispatchActionResume` bodies untouched). `HttpDispatcher.hostAuthoringRegistry(request)` places the request with the same `placeHostActionRequest` step a host action call uses, so the tools read the environment's services exactly as the MCP door reads them, including the classified `tenancy` and knowledge lookups. A resolver that refuses to place the request rejects the call. - **Admission** is the human half only: the person's own `manage_metadata`, decided by `resolveHumanReader` exactly as for the MCP door. A person without it is listed no tool and every call is refused `403 PERMISSION_DENIED` (the MCP door's shape; the sentence drops the `metadata:write` half, which does not exist here). Fail closed: an envelope with no `userId`, an `isSystem` envelope, or a grant read that throws admits nothing. - **Provenance**: saves through the entry state `surface: 'copilot'` and no `client`. The MCP door keeps `surface: 'mcp'` with the token's client. - No publish tool. The MCP door's behaviour is unchanged (its whole test file is green unmodified above the new group). ### Why `copilot`, not the card's example `in_app` (seat ruling, claim amendment 7219051191) The card asks for a value "other than `'mcp'`" so Studio and the host's caps can tell the in-app path from MCP. `MetadataAuthoringSurfaceSchema` already has that value: `copilot`, whose published meaning is "an AI assistant's tool writing on a person's behalf", which only an in-process caller may state (every HTTP door refuses `?surface=copilot`). Studio already renders it as an AI draft mark. Adding `in_app` would widen a published accept set (Clause-② yes) and touch `packages/spec` and Studio's rendering for no new distinction, so this PR adds no enum member and does not touch `packages/spec`. ## Tests New top-level group in the door's shared harness `packages/runtime/src/domains/mcp-authoring.test.ts`, through the real entry on a host kernel (the `dispatchAction` pins' kernel shape): - the entry is the package's public export; - an admitted person is listed exactly the MCP door's five tool definitions (deep-equal to the MCP door's `getAll()`), with no publish tool, and a read is served; - a person without `manage_metadata` is listed nothing, and every one of the five tools is refused with the MCP door's `code`/`status`, before any protocol read; - a draft save stamps `surface: 'copilot'`, no `client`, `actor` = the person, and answers the publish verdict and Studio routes; the MCP door's save in the same test still stamps `mcp` + `client`; - the writer is the MCP door's: a walled tenancy posture refuses the save `403` before any write; - fail closed: no user, `isSystem`, a throwing grant read; - placement: a named environment scopes every service lookup; a refusing `kernel-resolver` rejects with no grant read. Ablations (on the committed tree, restored with `git checkout HEAD --`): hard-coding the save's surface to `'mcp'` reds the provenance test; dropping the `isSystem` guard reds the fail-closed test. ## Acceptance notes - File surface beyond the original claim (`http-dispatcher.ts`, `action-dispatch.ts`, the new `in-process-authoring.ts`) was confirmed by the seat before push (claim amendment 7219051191). The entry file sits in `src/`, not `src/domains/`: every file under `domains/` must declare an HTTP route envelope (`check:route-envelope`), and this one serves no route; the seat recorded the move in claim amendment 2 (7219506629), and `check-route-envelope.mjs` is unchanged. `content/docs/permissions/system-context.mdx` (row 61c) is the census page `check:system-context-census` requires for the new `isSystem` read. `overlap-check.mjs --pr=37896` (the open PR that also edits `action-dispatch.ts`): `VERDICT clean exit 0`, both merge cleanly. - The first commit on the branch (`1c78bfc0`, a WIP push) carries no trailer pair; the second carries the model-free pair. - Public API record: the runtime package has no generated API report (`api-surface/` is `packages/spec` only); the export is recorded in `src/index.ts` with its comment and in the changeset. ## Verification <details><summary>Local runs and CI (head 7fea375, merge base bc17334)</summary> - `pnpm --filter @objectstack/runtime exec vitest run --maxWorkers=2 src/domains/mcp-authoring.test.ts src/action-dispatch.test.ts src/action-confirmation-handoff-33690.test.ts` (under `os-verify-lock.sh`, head 7fea375): Test Files 3 passed, Tests 172 passed, `VERDICT command-exit 0`. - `pnpm --filter @objectstack/runtime typecheck`: `tsc --noEmit` clean; `check:test-typecheck` reports 3 files that import `@objectstack/driver-turso`, which this container did not build (TS2307, none touched here). CI's `Type Check · workspace` and `TypeScript Type Check` are green. - Derived gates (`dispatch-gates.mjs --commands`, 73 commands): 70 exit 0. `check:plugin-teardown-shape --self-test` and `check:dual-build-cjs-loads` exit 3 (prerequisite dist not built here; CI green). `check:query-options-erasure` exited 1 only because the file moved mid-run (ENOENT on the old path) and exits 0 when re-run on the final tree. `check:route-envelope`, `check:system-context-census` and `check:doc-anchors` exit 0. `check:published-readme-exports` answers NOT MEASURED (exit 3) locally; CI is its verdict. - CI at 7fea375: 55 check runs, 40 success, 15 skipped (UI, opt-in and queue lanes), 0 failed; including `Lint & Repo Gates`, `TypeScript Type Check`, `Test Core` (10/10 shards), `Build Core`, `Build Docs`, `Check Changeset`, `PR-body guards`. </details> Two-minute check: `pnpm --filter @objectstack/runtime exec vitest run src/domains/mcp-authoring.test.ts -t 37944` shows 7 passing cases. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L9qibyo6pEabiVD1KUoeEJ --- _Generated by [Claude Code](https://claude.ai/code/session_01L9qibyo6pEabiVD1KUoeEJ)_ <!-- signed: repo:objectstack#3 · os-tesla · session_01L9qibyo6pEabiVD1KUoeEJ --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 6b11d13 commit ecd10e9

9 files changed

Lines changed: 489 additions & 17 deletions

File tree

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@objectstack/runtime': patch
3+
---
4+
5+
feat(runtime): an in-process entry to the light authoring door, for a host's own AI assistant
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`createInProcessAuthoringRegistry(kernel, { executionContext, environmentId })` returns the five tools the MCP draft door serves (`list_metadata_items`, `get_metadata_item`, `list_drafts`, `save_metadata_draft`, `delete_metadata_draft`) for an AI assistant that runs in the server process and acts as the signed-in person, such as a host's in-app ask turn. It is built by the MCP door's own assembly, over a request placed the way `dispatchAction` places a host's action call, so the tool definitions, the read gates, the writer and the publish verdicts are the MCP door's, with no second copy.
11+
12+
- **Admission** is the person's own `manage_metadata`, read from their grants exactly as the MCP door reads the human half. There is no OAuth scope to hold: the host's authenticated session takes its place. A person without the capability is listed no tool and every call is refused `403 PERMISSION_DENIED`, the MCP door's shape. An envelope with no user, a system envelope, or a grant read that fails admits nothing.
13+
- **Saves state `surface: 'copilot'`** (an AI assistant's tool writing on a person's behalf), never `mcp`, and no OAuth `client`, so Studio's draft marks and per-key provenance tell an in-app save from an MCP one.
14+
- **No publish tool**: drafts stay for a person to review and publish in Studio.
15+
- **The MCP door is unchanged**: same tools, same admission, same `surface: 'mcp'` saves with the token's client.
16+
17+
The host keeps the same jobs `dispatchAction` leaves it: authenticating the person, the authentication-policy gate and the environment-membership gate. A `kernel-resolver` that refuses to place the request rejects the call.

‎content/docs/permissions/system-context.mdx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,7 @@ One of the largest consumers of the flag;
222222
| 60 | **Automation flow data nodes re-add the `owner_id` stamp** (the one place row 2's gap is compensated inline) | service-automation | Get: a flow-authored INSERT under system elevation still lands owned, when the run resolved a user. Fill-only — flow-authored values win | `stampSystemInsertOwner`, called from `packages/services/service-automation/src/builtin/crud-nodes.ts#registerCrudNodes` |
223223
| 61 | Inbox caller refusal names `isSystem` as what was carried | service-messaging | Get: nothing — the refusal still fires. The flag only shapes the diagnostic, because privilege is not an authorization subject | `resolveInboxRecipient` |
224224
| 61b | **The principal-session mint refuses a system context** | plugin-auth | Get: nothing — `mintPrincipalSession` answers `PERMISSION_DENIED` / `403` before anything is minted. A principal session acts as the requesting user and never as the system, so a render or any other in-process act that needs a session must carry the user's own context | `refuseUpFront` |
225+
| 61c | **The in-process authoring entry admits a system context nothing** | runtime | Get: nothing — `createInProcessAuthoringRegistry` lists no tool and refuses every call `403 PERMISSION_DENIED`, before any grant is read or the request is placed. The entry acts as a signed-in person, and a system context is no person; carried into the draft writer, its flag would also pass the walled environment-metadata refusal | `inProcessAuthoringRegistryRequest` |
225226
| 62 | **`organization_id` is not auto-stamped on INSERT** — the organization-axis twin of the `owner_id` gap above | organizations | Get: an elevated write may name another organization deliberately, which is what the per-organization seed replay, the orphan-row claim, imports and migrations all rely on. Lose: the fill-only stamp, so an elevated insert that names no organization lands `organization_id = NULL` and the wall hides it. ⛔ Neither path rewrites a supplied `organization_id`: the non-elevated path fills only an absent one, and a supplied value meets the Layer 0 write wall, which refuses a forged one `403 PERMISSION_DENIED` exactly as it refuses an update re-pointing a row. Elevation skips the stamp and the wall alike, which is why it is the seam the legitimate cross-organization writers use | `packages/plugins/organizations/src/organizations-plugin.ts#start` |
226227
| 62b | **MCP `list_actions` asks no membership-grade mark of a system caller** — an organization action whose endpoint (`/organization/...`) the caller's membership grade does not reach is listed without `unavailable` | runtime | Get: nothing a run would not give. The mark is a courtesy reading of the caller's own `positions` (ruling record 6812625052, letter E: list and mark, do not hide), and a system context carries no person's grades, so it is left unmarked, as a delegated agent's envelope is. Every other caller whose positions name none of the grades the `MEMBERSHIP_REACH` rows for that endpoint list sees the row marked `PERMISSION_DENIED`. Lose: nothing — neither run door reads the mark, and the organization endpoint still judges the call | `membershipReachRefusal` |
227228

@@ -702,6 +703,7 @@ and CI refuses one that differs from what the tree produces.
702703
| `packages/runtime/src/domains/permission-set-clone.ts#handlePermissionSetCloneWrite` | 2 | 50 |
703704
| `packages/runtime/src/domains/security.ts#handleSecurityRequest` | 1 | 52 |
704705
| `packages/runtime/src/flow-start-admission.ts#flowStartRefusal` | 1 | 57 |
706+
| `packages/runtime/src/in-process-authoring.ts#inProcessAuthoringRegistryRequest` | 1 | 61c |
705707
| `packages/runtime/src/sandbox/body-doors.ts#callerScopeOf` | 1 | 65b |
706708
| `packages/runtime/src/sandbox/body-runner.ts#executionContextFromHook` | 1 | 65 |
707709
| `packages/services/service-automation/src/runtime-identity.ts#stampSystemInsertOwner` | 1 | 60 |

‎packages/runtime/README.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,28 @@ interface PluginContext {
261261
}
262262
```
263263

264+
### In-process authoring tools
265+
266+
A host's own AI assistant that runs in the server process (an in-app ask turn)
267+
calls the MCP draft door's five tools as the signed-in person, with no OAuth
268+
grant, through `createInProcessAuthoringRegistry`. The tools, read gates and
269+
publish verdicts are the MCP door's own; admission is the person's own
270+
`manage_metadata`; saves are recorded as `surface: 'copilot'`; no tool
271+
publishes, so a person reviews and publishes the drafts in Studio.
272+
273+
```typescript
274+
import { createInProcessAuthoringRegistry } from '@objectstack/runtime';
275+
276+
// Once per turn, as the person your door authenticated.
277+
const authoring = await createInProcessAuthoringRegistry(kernel, { executionContext, environmentId });
278+
const tools = authoring.getAll(); // [] when the person lacks manage_metadata
279+
const result = await authoring.execute({ toolCallId, toolName: 'list_drafts', input: {} });
280+
```
281+
282+
`kernel` and the placement are `dispatchAction`'s; as there, authenticating
283+
the person, the authentication-policy gate and environment membership stay the
284+
host's job.
285+
264286
## Examples
265287

266288
Complete, CI-exercised examples live in the repo's [`examples/`](../../examples)

‎packages/runtime/src/action-dispatch.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1318,6 +1318,21 @@ export async function dispatchActionRequest(
13181318
/** One dispatcher per kernel: its deps are the REST door's. */
13191319
const hostDispatchers = new WeakMap<object, HttpDispatcher>();
13201320

1321+
/**
1322+
* The one dispatcher a host's in-process doors run on for `kernel`, from the
1323+
* map {@link dispatchAction} and {@link dispatchActionResume} fill: the
1324+
* in-process authoring entry (`./in-process-authoring.ts`) runs on the
1325+
* same dispatcher, and so on the same placement, as a host's action call.
1326+
*/
1327+
export function hostDispatcherFor(kernel: ObjectKernel): HttpDispatcher {
1328+
let dispatcher = hostDispatchers.get(kernel);
1329+
if (!dispatcher) {
1330+
dispatcher = new HttpDispatcher(kernel);
1331+
hostDispatchers.set(kernel, dispatcher);
1332+
}
1333+
return dispatcher;
1334+
}
1335+
13211336
/**
13221337
* Run one business action from a host's own door — the REST `/actions`
13231338
* door's admission and dispatch, as a function. A host that runs actions

‎packages/runtime/src/domains/mcp-authoring.test.ts‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@
1818
*
1919
* Fail closed: an envelope with no user is injected nothing, and a grant
2020
* resolution that throws admits nothing.
21+
*
22+
* [#37944] The last group pins the in-process entry
23+
* (`createInProcessAuthoringRegistry`) against this door: the same five tool
24+
* definitions, the same refusal shape for a person without `manage_metadata`,
25+
* the same writer, and saves stamped `copilot` where this door stamps `mcp`.
2126
*/
2227

2328
import { describe, it, expect, afterEach, vi } from 'vitest';
@@ -53,6 +58,7 @@ import {
5358
type OpenAuthoringProtocol,
5459
type OpenAuthoringReadGateSources,
5560
} from './mcp-authoring.js';
61+
import { createInProcessAuthoringRegistry } from '../in-process-authoring.js';
5662
import { resolveExecutionContext } from '../security/resolve-execution-context.js';
5763
import { bindCatalogFromTables } from '../security/security-catalog.testkit.js';
5864

@@ -1404,3 +1410,162 @@ describe('done when: an OAuth author saves an app-crm flow draft with no routabl
14041410
expect((await call(authoring, 'list_drafts', {})).body.drafts).toEqual([]);
14051411
});
14061412
});
1413+
1414+
// ---------------------------------------------------------------------------
1415+
// [#37944] The in-process entry: the same five tools, as the signed-in person
1416+
// ---------------------------------------------------------------------------
1417+
1418+
/**
1419+
* One host kernel serving the door's services, as `dispatchAction`'s pins
1420+
* build one: the recording protocol, the human's grant engine, the security
1421+
* service, and `tenancy` / `kernel-resolver` when given. `scopes` records the
1422+
* environment each scoped lookup was asked under.
1423+
*/
1424+
function inProcessHost(opts: {
1425+
systemPermissions?: string[]; protocol?: OpenAuthoringProtocol; tenancy?: { posture: string };
1426+
qlThrows?: boolean; resolveKernel?: (ctx: any) => unknown;
1427+
} = {}) {
1428+
const { ql, reads } = userQl(opts.systemPermissions ?? ADMIN);
1429+
const fake = fakeProtocol();
1430+
const protocol = opts.protocol ?? fake.protocol;
1431+
const security = { resolvePermissionSetNames: async (ctx: any) => (Array.isArray(ctx?.permissions) ? ctx.permissions : []) };
1432+
const warnings: unknown[][] = [];
1433+
const services: Record<string, unknown> = {
1434+
protocol,
1435+
security,
1436+
...(opts.tenancy ? { tenancy: opts.tenancy } : {}),
1437+
...(opts.resolveKernel ? { 'kernel-resolver': { resolveKernel: opts.resolveKernel } } : {}),
1438+
logger: { warn: (...args: unknown[]) => { warnings.push(args); }, debug: () => {}, info: () => {}, error: () => {} },
1439+
};
1440+
const resolve = (name: string): any => {
1441+
if (name === 'objectql') {
1442+
if (opts.qlThrows) throw new Error('engine lookup failed');
1443+
return ql;
1444+
}
1445+
return services[name] ?? null;
1446+
};
1447+
const scopes: string[] = [];
1448+
const kernel: any = {
1449+
getService: resolve,
1450+
getServiceAsync: async (name: string, scopeId?: string) => {
1451+
if (scopeId !== undefined) scopes.push(scopeId);
1452+
return resolve(name);
1453+
},
1454+
context: { getService: resolve },
1455+
};
1456+
return { kernel, grantReads: reads, protocolCalls: fake.calls, scopes, warnings };
1457+
}
1458+
1459+
/** A signed-in person's session envelope, as a host's session door resolves it: no OAuth grant. */
1460+
const SESSION_EC = { userId: 'u1', isSystem: false, roles: [], permissions: [], systemPermissions: [] } as any;
1461+
1462+
async function inProcessCall(authoring: { execute: (call: any) => Promise<any> }, toolName: string, input: unknown) {
1463+
const result = await authoring.execute({ toolCallId: `t-${toolName}`, toolName, input });
1464+
return { isError: result.isError === true, body: JSON.parse(result.output.value) };
1465+
}
1466+
1467+
describe('[#37944] createInProcessAuthoringRegistry serves the MCP door\'s five tools in process, as the signed-in person', () => {
1468+
it('is the runtime package\'s public entry', async () => {
1469+
const runtime = await import('../index.js');
1470+
expect(runtime.createInProcessAuthoringRegistry).toBe(createInProcessAuthoringRegistry);
1471+
});
1472+
1473+
it('a person holding manage_metadata is listed the same five tool definitions the MCP door lists, with no OAuth grant', async () => {
1474+
const host = inProcessHost();
1475+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC });
1476+
expect(authoring.admitted).toBe(true);
1477+
// The admission read the person's own grants: the session envelope carries no capability.
1478+
expect(host.grantReads.length).toBeGreaterThan(0);
1479+
1480+
const { authoring: mcpDoor } = await authorThroughDomain();
1481+
expect(authoring.getAll()).toEqual(mcpDoor.registry.getAll());
1482+
expect(authoring.getAll().map((tool) => tool.name)).toEqual([...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]);
1483+
// No publish tool rides in.
1484+
expect(authoring.getAll().map((tool) => tool.name).some((name) => /publish/.test(name))).toBe(false);
1485+
1486+
const listed = await inProcessCall(authoring, 'list_metadata_items', { type: 'flow' });
1487+
expect(listed.isError).toBe(false);
1488+
expect(listed.body.items.map((item: any) => item.name)).toEqual(['lead_intake', 'close_won']);
1489+
});
1490+
1491+
it('a person without manage_metadata is listed no tool and a call is refused 403, the MCP door\'s refusal shape, before any read', async () => {
1492+
const host = inProcessHost({ systemPermissions: NOT_AN_AUTHOR });
1493+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC });
1494+
expect(authoring.admitted).toBe(false);
1495+
expect(authoring.getAll()).toEqual([]);
1496+
1497+
const mcpEc = await oauthEnvelope(['metadata:write'], NOT_AN_AUTHOR);
1498+
const mcpRefusal = await call((await serve(mcpEc, { systemPermissions: NOT_AN_AUTHOR })).authoring!, 'save_metadata_draft', {});
1499+
for (const tool of [...OPEN_AUTHORING_READ_TOOL_NAMES, ...OPEN_AUTHORING_WRITE_TOOL_NAMES]) {
1500+
const refused = await inProcessCall(authoring, tool, { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' });
1501+
expect(refused.isError, tool).toBe(true);
1502+
expect(refused.body.error, tool).toMatchObject({ code: mcpRefusal.body.error.code, status: mcpRefusal.body.error.status });
1503+
expect(refused.body.error, tool).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
1504+
// No OAuth half to name: the sentence names only the capability.
1505+
expect(refused.body.error.message, tool).not.toContain('metadata:write');
1506+
}
1507+
expect(host.protocolCalls).toEqual([]);
1508+
});
1509+
1510+
it('a draft save stamps surface copilot, not mcp, with no client, as the person, and answers the publish verdict', async () => {
1511+
const host = inProcessHost();
1512+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC });
1513+
const saved = await inProcessCall(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm', ifMatch: 'v7' });
1514+
1515+
expect(saved.isError).toBe(false);
1516+
const save = host.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[];
1517+
expect(save[1]).toMatchObject({
1518+
type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, packageId: 'com.acme.crm',
1519+
mode: 'draft', surface: 'copilot', writeFace: 'meta-dispatch', parentVersion: 'v7', actor: 'u1',
1520+
});
1521+
expect(save[1]).not.toHaveProperty('client');
1522+
expect(saved.body).toMatchObject({
1523+
saved: { type: 'flow', name: 'lead_intake', package: 'com.acme.crm', state: 'draft', version: 'v8' },
1524+
verdict: { publishable: false, refusals: [UNROUTABLE_ISSUE], advisories: [] },
1525+
review: { changes: '/studio/com.acme.crm/data?changes=review', item: '/studio/com.acme.crm/metadata/flow/lead_intake?review=1' },
1526+
});
1527+
1528+
// The MCP door's save, unchanged: `mcp` and the token's client.
1529+
const { authoring: mcpDoor, served } = await authorThroughDomain();
1530+
await call(mcpDoor, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' });
1531+
expect((served.protocolCalls.find((c: any) => c[0] === 'saveMetaItem') as any[])[1]).toMatchObject({ surface: 'mcp', client: { id: 'c1' } });
1532+
});
1533+
1534+
it('the writer is the MCP door\'s: under a walled tenancy posture the save is refused 403 before anything is written', async () => {
1535+
const host = inProcessHost({ tenancy: { posture: 'isolated' } });
1536+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: { ...SESSION_EC, posture: 'TENANT_ADMIN' } });
1537+
const refused = await inProcessCall(authoring, 'save_metadata_draft', { type: 'flow', name: 'lead_intake', item: FLOW_DRAFT, package: 'com.acme.crm' });
1538+
expect(refused.body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
1539+
expect(host.protocolCalls.filter((c: any) => c[0] === 'saveMetaItem')).toEqual([]);
1540+
});
1541+
1542+
it('fails closed: no person, a system envelope, or a grant read that throws admits nothing', async () => {
1543+
for (const executionContext of [{ isSystem: false } as any, { ...SESSION_EC, isSystem: true }]) {
1544+
const host = inProcessHost();
1545+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext });
1546+
expect(authoring.admitted).toBe(false);
1547+
expect(authoring.getAll()).toEqual([]);
1548+
expect((await inProcessCall(authoring, 'list_drafts', {})).body.error).toMatchObject({ code: 'PERMISSION_DENIED', status: 403 });
1549+
// No grant is read for it.
1550+
expect(host.grantReads).toEqual([]);
1551+
expect(host.protocolCalls).toEqual([]);
1552+
}
1553+
const throwing = inProcessHost({ qlThrows: true });
1554+
const authoring = await createInProcessAuthoringRegistry(throwing.kernel, { executionContext: SESSION_EC });
1555+
expect(authoring.admitted).toBe(false);
1556+
expect(authoring.getAll()).toEqual([]);
1557+
});
1558+
1559+
it('is placed as dispatchAction places a host call: the named environment scopes the lookups, and a resolver that refuses rejects', async () => {
1560+
const host = inProcessHost();
1561+
const authoring = await createInProcessAuthoringRegistry(host.kernel, { executionContext: SESSION_EC, environmentId: 'env_named' });
1562+
await inProcessCall(authoring, 'list_drafts', {});
1563+
expect(host.scopes.length).toBeGreaterThan(0);
1564+
expect(new Set(host.scopes)).toEqual(new Set(['env_named']));
1565+
1566+
const refusing = inProcessHost({ resolveKernel: async () => { throw Object.assign(new Error('not a member of env_named'), { status: 403 }); } });
1567+
await expect(createInProcessAuthoringRegistry(refusing.kernel, { executionContext: SESSION_EC, environmentId: 'env_named' }))
1568+
.rejects.toThrow('not a member of env_named');
1569+
expect(refusing.grantReads).toEqual([]);
1570+
});
1571+
});

0 commit comments

Comments
 (0)