Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/owner-writes-collections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@flow-state-dev/core": patch
"@flow-state-dev/engine": patch
---

`defineResourceCollection` accepts `ownerWrites: { param }`: every reader the collection's scope serves reads each row, and only the user the row's owner segment names writes it. Key rows with `ownerSegment(userId)` at that parameter, as for `ownerPrivate`, and the same pattern rules apply (the parameter appears once, no `**`); a browser read is allowed. A create, update or delete by anyone else, through the collection handle, a ref obtained by reading, or the browser update and delete routes, throws `A row of an owner-writes collection is written only by the user it belongs to.` and changes nothing. The startup fence covers these collections too: a wider collection in the same scope that can reach their keys, or the same pattern declared `ownerPrivate`, stops the app from starting. A collection can't declare both modes, and an owner-writes collection can't declare an `eviction` policy other than `"none"` (FIX-1793).
10 changes: 10 additions & 0 deletions docs/architecture/resources-and-client-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,16 @@ A collection declaring `ownerPrivate: { param }` owns every key whose first segm

Workforce's private roster collection is the first consumer. Engine knows it only as an owner-private collection.

#### Owner-writes collections

A collection declaring `ownerWrites: { param }` takes the same key shape, the same definition checks except the browser-read one, and both fences. It differs in one rule: **every reader the scope serves reads the row, and only its owner writes it.**

- **Reads.** The key fence admits the row to every read path listed above, for any caller, as long as its first `~` segment sits at the owner parameter. The request-start seed cache admits it too, judged against the run's declared collections, since those collections serve it from that cache.
- **Writes.** A create, update or delete is refused with its own message (`A row of an owner-writes collection is written only by the user it belongs to.`) unless the session's user is the one the key's owner segment encodes. A reader holds refs it could write through, so the scope resource registry judges this where every write it makes meets the store (state mutate, state delete, content write, content delete), whichever handle, ref or eviction asked. The browser update and delete routes ask the same question before writing.
- **The startup fence** arms for either mode. An owner-private and an owner-writes declaration of one pattern are two declarations, and the second is refused.

It reads only the key and the declaring collection, so a second process declaring the same collection over one store refuses the same writes. A flow that declares the pattern without the mode gets the key fence's plain-collection answer: absent, and refused on write.

### Block-Level Resource Declarations

Blocks declare resource dependencies via a single `resources` field:
Expand Down
2 changes: 1 addition & 1 deletion docs/contributing/architecture-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ Purposes and default models live in the catalog — don't restate them here.
- `defineFlow` merges block-declared resources into the flow's `resources` map; flow-level wins over block-level
- Same `defineResource()` reference across blocks = no conflict; different references for same name = build-time error
- Collection snapshots emit `count` always and `prefetched` when `prefetchWindow > 0`; per-item `clientData` is gated by `client.state.read`. Lazy reads via `GET /sessions/:id/resources/:ref` and a flow-static manifest at `GET /sessions/:id/manifest` (FIX-427).
- A key segment beginning `~` belongs to an owner-private collection (`ownerPrivate: { param }`), in every app: no other collection reads or writes it, and a key's first one names its owner. A registry that has held one refuses, for good, any flow whose collection in the same scope can reach its keys, and every registry refuses a single resource whose key has a segment beginning `~` → [Resources and client data](../architecture/resources-and-client-data.md#owner-private-collections)
- A key segment beginning `~` belongs to an owner-keyed collection, in every app: no other collection reads or writes it, and a key's first one names its owner. An owner-private collection (`ownerPrivate: { param }`) serves the row only to that owner; an owner-writes collection (`ownerWrites: { param }`) serves it to every reader the scope serves and lets only that owner write it, judged where the run's writes meet the store. A registry that has held either refuses, for good, any flow whose collection in the same scope can reach its keys, and every registry refuses a single resource whose key has a segment beginning `~` → [Resources and client data](../architecture/resources-and-client-data.md#owner-private-collections)

→ [Resources and Client Data](../architecture/resources-and-client-data.md)

Expand Down
5 changes: 3 additions & 2 deletions packages/core/src/types/collection-patterns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,9 @@ export function encodeUserSegment(userId: string): string {
* The key segment that marks a row as `userId`'s: `~` plus
* {@link encodeUserSegment}.
*
* An owner-private collection (`ownerPrivate: { param }`) keys each row with
* this at its owner parameter, and serves the row only to that user. A key's
* An owner-keyed collection (`ownerPrivate: { param }` or `ownerWrites: { param }`)
* keys each row with this at its owner parameter: an owner-private one serves
* the row only to that user, an owner-writes one lets only that user write it. A key's
* first segment beginning `~` is its owner in every app, so no other
* collection reads or writes a key carrying one. The escaped id holds no `~`
* and no `/`, so the segment is one segment with one marker.
Expand Down
33 changes: 32 additions & 1 deletion packages/core/src/types/resource-collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,17 @@ export type ResourceCollectionConfig<TState extends JsonObject = JsonObject> = {
* has no browser read.
*/
ownerPrivate?: { param: string };
/**
* Make each row readable by everyone the scope serves and writable only by
* the user it belongs to. `param` names the pattern parameter that holds the
* owner; key it with `ownerSegment(userId)`. Every read path serves the row,
* the browser routes included. A create, update or delete is refused unless
* the session's user is the one the owner segment names, and no other
* collection in the app reads or writes the rows. The pattern must declare
* `param` exactly once and must not use `**`. Not with `ownerPrivate`, and
* not with an `eviction` policy other than `"none"`.
*/
ownerWrites?: { param: string };
/**
* Intrinsic scope this collection lives in. Required for new collections —
* mirrors `defineResource({ scope })`.
Expand Down Expand Up @@ -336,7 +347,19 @@ export function defineResourceCollection<
ProjectedClient<AsStateObject<StateOf<TConfig>>, TConfig["client"]>
> {
validatePattern(config.pattern);
if (config.ownerPrivate !== undefined && config.ownerWrites !== undefined) {
throw new Error(`Collection "${config.pattern}" declares both ownerPrivate and ownerWrites; choose one.`);
}
if (config.ownerPrivate !== undefined) assertOwnerPrivateShape(config);
if (config.ownerWrites !== undefined) {
const named = `Owner-writes collection "${config.pattern}"`;
assertOwnerKeyShape(config.pattern, config.ownerWrites.param, named);
// Every user's create sees every owner's rows, so its eviction would pick

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Eviction guard. You only reject explicit eviction !== "none". That matches defineResourceCollection (eviction requires maxInstances). Worth a quick sanity check that maxInstances without eviction can’t still evict another user’s row at runtime for owner-writes collections — I didn’t find a hole, but it’s the one place a stricter maxInstances ban might belong if defaults ever change.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

No change. defineResourceCollection only evicts when an eviction policy is set, and this PR refuses any policy other than "none" on owner-writes collections, so maxInstances alone can't evict another user's row. You reached the same conclusion. If eviction defaults ever change, that change has to revisit this guard.


Generated by Claude Code

// a row its caller may not delete.
if (config.eviction !== undefined && config.eviction !== "none") {
throw new Error(`${named} must not evict: an eviction would delete another user's row.`);
}
}

if (config.contentTemplate !== undefined && config.contentTemplateRef !== undefined) {
throw new Error(
Expand Down Expand Up @@ -458,7 +481,6 @@ function assertOwnerPrivateShape(
}
): void {
const { pattern, client } = config;
const param = config.ownerPrivate?.param;
const named = `Owner-private collection "${pattern}"`;
if (
client?.state?.read === true ||
Expand All @@ -467,6 +489,15 @@ function assertOwnerPrivateShape(
) {
throw new Error(`${named} must not enable a browser read.`);
}
assertOwnerKeyShape(pattern, config.ownerPrivate?.param, named);
}

/**
* The key shape both owner modes (`ownerPrivate`, `ownerWrites`) need: the
* owner sits at one known segment, so the pattern names the parameter exactly
* once, as a whole segment, and has no `**`. `named` opens each refusal.
*/
function assertOwnerKeyShape(pattern: string, param: unknown, named: string): void {
const segments = pattern.split("/");
if (
typeof param !== "string" ||
Expand Down
53 changes: 53 additions & 0 deletions packages/core/test/resource-collection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -719,6 +719,59 @@ describe("defineResourceCollection · ownerPrivate", () => {
});
});

// ---------------------------------------------------------------------------
// Owner-writes collections: the scope reads every row, only its owner writes it
// ---------------------------------------------------------------------------

describe("defineResourceCollection · ownerWrites", () => {
const entries = (overrides: Record<string, unknown> = {}) =>
defineResourceCollection({
pattern: "entries/[project]/[owner]/[entry]",
ownerWrites: { param: "owner" },
scope: "org",
stateSchema: z.object({}).passthrough(),
...overrides,
} as Parameters<typeof defineResourceCollection>[0]);

it("defines a collection that names its owner parameter once", () => {
const collection = entries();
expect(collection.ownerWrites).toEqual({ param: "owner" });
expect({ ...collection }.ownerWrites).toEqual({ param: "owner" });
});

it("allows a browser read, since every row is readable by the whole scope", () => {
expect(() => entries({ client: { state: { read: true }, content: { read: true, prefetch: true } } })).not.toThrow();
});

it("refuses a parameter the pattern lacks, or declares more than once", () => {
expect(() => entries({ ownerWrites: { param: "author" } })).toThrow(
'Owner-writes collection "entries/[project]/[owner]/[entry]" must declare parameter "author" exactly once.'
);
expect(() => entries({ pattern: "entries/[owner]/[owner]" })).toThrow(
'Owner-writes collection "entries/[owner]/[owner]" must declare parameter "owner" exactly once.'
);
});

it('refuses "**", because the owner has to sit at one known segment', () => {
expect(() => entries({ pattern: "entries/[owner]/**" })).toThrow(
'Owner-writes collection "entries/[owner]/**" must not use "**": its owner sits at one segment.'
);
});

it("refuses an eviction policy, which would delete another user's row on a create", () => {
expect(() => entries({ maxInstances: 5, eviction: "lru" })).toThrow(
'Owner-writes collection "entries/[project]/[owner]/[entry]" must not evict: an eviction would delete another user\'s row.'
);
expect(() => entries({ maxInstances: 5, eviction: "none" })).not.toThrow();
});

it("refuses ownerPrivate beside it: a row has one owner rule", () => {
expect(() => entries({ ownerPrivate: { param: "owner" } })).toThrow(
'Collection "entries/[project]/[owner]/[entry]" declares both ownerPrivate and ownerWrites; choose one.'
);
});
});

describe("ownerSegment", () => {
it("is ~ plus the escaped user id, one segment whatever the id holds", () => {
expect(ownerSegment("alice")).toBe("~alice");
Expand Down
8 changes: 6 additions & 2 deletions packages/engine/src/context/createExecutionContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1271,15 +1271,19 @@ export async function createExecutionContext<
// copy depends on which collection was declared first.
//
// Every prefix load passes through here, so it is also where another user's
// owner-private row is kept out of the run's cache (`ownerKeyMaySeed`).
// owner-private row is kept out of the run's cache (`ownerKeyMaySeed`). An
// owner-writes row is everyone's to read, so the scope's collections decide.
const retainOwnedKeys = <T>(
scope: ContentScopeType,
scopeId: string,
rows: Record<string, T>
): Record<string, T> => {
const owned = ownKeyRecord<T>();
const scopeConfigs = Object.values(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor perf note (probably fine for P1): Object.values(...) runs on every retainOwnedKeys invocation, and each foreign ~ key scans all scope configs via ownerKeyMaySeed → ownerWritesCollectionFor. If org-wide prefix loads get large, hoisting scopeConfigs once per context build and/or skipping the scan when no ownerWrites collection is declared would be a small win.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

This stays for P1 and gets tracked only if a measured prefix load shows it is slow.


Generated by Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Performance / simplify (optional). Object.values(session|user|org configs) runs on every retainOwnedKeys call (prefix loads, lazy waves, adoption). Config maps are fixed for the context lifetime — consider hoisting three cached arrays when the context is built, and passing a precomputed “has any ownerWrites” flag into ownerKeyMaySeed so flows without owner-writes keep the pre-PR O(1) reject for another user’s ~ keys.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

Same call as on the earlier thread: this stays for P1, and it gets tracked only if a measured prefix load shows the cost.


Generated by Claude Code

scope === "session" ? sessionResourceConfigs : scope === "user" ? userResourceConfigs : orgResourceConfigs
);
for (const [key, value] of Object.entries(rows)) {
if (!ownerKeyMaySeed(key, userId)) continue;
if (!ownerKeyMaySeed(key, userId, scopeConfigs)) continue;
if (resolveResourceStorageScopeId(scope, key) === scopeId) owned[key] = value;
}
return owned;
Expand Down
51 changes: 41 additions & 10 deletions packages/engine/src/context/resource-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ import {
searchProjectedRecords,
} from "@flow-state-dev/core/types";
import type { ResourceLoadRecord } from "@flow-state-dev/core/items";
import { OWNER_ROW_REFUSAL, ownerKeyAdmits } from "../resources/owner-private";
import { OWNER_ROW_REFUSAL, ownerKeyAdmits, ownerWritesRefusalForKey } from "../resources/owner-private";
import { cloneValue, resolveClientProjection } from "@flow-state-dev/core/helpers";
import { applyGetOrPatchState, isTraceObservabilityEnabled } from "@flow-state-dev/core";
import { createResourceEdgeApi } from "@flow-state-dev/core/graph";
Expand Down Expand Up @@ -754,13 +754,15 @@ export function filterFlowLevelEager(
/**
* Fence owner keys on a collection handle.
*
* An owner-private collection sees only the session user's own rows. Every
* other collection sees none of any owner's rows, whatever this process
* registered. A fenced key is absent for list, count and `getOptional`, and
* refused for `get` and every write; the message does not say whether the row
* exists. The decision is {@link ownerKeyAdmits}. Every collection pattern has
* a wildcard or parameter segment, and so can resolve onto a key with a
* segment beginning `~`, so every handle is wrapped.
* An owner-private collection sees only the session user's own rows, and an
* owner-writes collection sees every owner's. Every other collection sees
* none of any owner's rows, whatever this process registered. A fenced key is
* absent for list, count and `getOptional`, and refused for `get` and every
* write; the message does not say whether the row exists. The decision is
* {@link ownerKeyAdmits}. Who may write an owner-writes row is judged where
* the registry's writes meet the store, since a reader holds refs to it.
* Every collection pattern has a wildcard or parameter segment, and so can
* resolve onto a key with a segment beginning `~`, so every handle is wrapped.
*/
function fenceOwnerKeys(
handle: ResourceCollectionRef<JsonObject>,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplify / clarity: For ownerWrites, own(key) is true for every reader, so these mutation methods only enforce read admission. Cross-user writes are blocked later in refuseOwnerWrite (required for ref paths anyway).

Consider gating mutations with ownerWriteRefusal(handle.config, resolveCollectionKey(handle.pattern, key), userId) so handle-level failures use OWNER_WRITE_REFUSAL at the same layer as HTTP routes. Not required for correctness — just easier to reason about than a two-hop failure.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

This stays as is. A blast-radius run on this PR showed that a handle-level write check added no coverage over the store guard, so it was removed on purpose. The store guard already throws OWNER_WRITE_REFUSAL, so the message is the same at both layers.


Generated by Claude Code

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two-layer write enforcement (FYI). Handle mutators still gate on ownerKeyAdmits, so a non-owner passes create/delete on an owner-writes row and fails at refuseOwnerWrite below. That’s correct for refs, but surprising when debugging handle-only paths. If you want clearer errors without duplicating logic, mutating methods could call ownerWriteRefusal before delegate — registry wrap would still be required for ref/eviction paths.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

This stays as is. A blast-radius run showed the handle-level check added no coverage over the store guard, which throws the same OWNER_WRITE_REFUSAL.


Generated by Claude Code

Expand Down Expand Up @@ -810,7 +812,7 @@ function fenceOwnerKeys(
}

export function createScopeResourceRegistry<TResources extends Record<string, ResourceRef<any>>>(
options: {
unfencedOptions: {
scope: ScopeType;
/**
* Identifier of the concrete scope instance — `userId` for `"user"`,
Expand Down Expand Up @@ -939,11 +941,40 @@ export function createScopeResourceRegistry<TResources extends Record<string, Re
orgId: string;
/**
* The session's user, when this registry is built for a run. The
* owner-private key fence uses it to serve each caller only their own rows.
* owner-key fence uses it to serve each caller only their own owner-private
* rows, and to let only the owner write an owner-writes row.
*/
actorUserId?: string;
}
): ResourceRegistry<TResources> {
// An owner-writes row is readable by anyone the scope serves, so a reader
// can hold a ref to another user's row and write through it. Every write
// this registry makes meets the store through these four callbacks, so the
// owner rule is judged here, whichever handle, ref or eviction asked.
const declaredConfigs = Object.values(unfencedOptions.configs ?? {});
const refuseOwnerWrite = (key: string): void => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This store-seam wrap is the right choke point: refs obtained via get() bypass fenceOwnerKeys mutations. Worth keeping even if handle mutations start calling ownerWriteRefusal — don't delete this layer in a “simplify” pass.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

from: fsd-head-of-engineering / session: em-fix-1786 / kind: triage

Agreed. It stays.


Generated by Claude Code

const refusal = ownerWritesRefusalForKey(declaredConfigs, key, unfencedOptions.actorUserId);
if (refusal !== undefined) throw new Error(refusal);
};
const options: typeof unfencedOptions = {
...unfencedOptions,
mutateResourceKey: async (key, mutator, opts) => {
refuseOwnerWrite(key);
return unfencedOptions.mutateResourceKey(key, mutator, opts);
},
deleteResourceKey: async (key) => {
refuseOwnerWrite(key);
return unfencedOptions.deleteResourceKey(key);
},
persistResourceContentKey: async (key, content) => {
refuseOwnerWrite(key);
return unfencedOptions.persistResourceContentKey(key, content);
},
deleteResourceContentKey: async (key) => {
refuseOwnerWrite(key);
return unfencedOptions.deleteResourceContentKey(key);
},
};
// Null-prototype: keyed by author-supplied accessor names, and this is the
// map `get()` below reads. On a plain `{}` an accessor of `__proto__` would
// replace the map's prototype rather than add a key, and an accessor sharing
Expand Down
6 changes: 3 additions & 3 deletions packages/engine/src/registry/flow-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
* scope, so its `stateSchema` drops out under the flow-level flag, while each
* resource carries its own `flowIsolation` override and drops out on that.
*
* The registry also keeps the owner-private startup fence
* The registry also keeps the owner-key startup fence
* (`admitOwnerPrivateCollections` in `resources/owner-private.ts`). It arms
* when a flow declaring an owner-private collection is admitted, checks every
* when a flow declaring an owner-keyed (owner-private or owner-writes) collection is admitted, checks every
* held flow against each declaration as it arrives, checks every later flow,
* and never disarms. A registry that never holds one refuses nothing on that
* account. Every registry, armed or not, refuses a single resource whose
Expand Down Expand Up @@ -157,7 +157,7 @@ export class InMemoryFlowRegistry implements FlowRegistry {
};

/**
* Every owner-private declaration this registry has admitted. Never
* Every owner-keyed declaration this registry has admitted. Never
* cleared, even across unregister, for the reason the participants map
* above is kept: the rows outlive the registration, so the constraint has
* to as well. Non-empty means the startup fence is armed.
Expand Down
Loading
Loading