Collaboration Projects
Status: Phases 1 and 2 shipped (per-entity overrides via nullable entity_permissions flags, tri-state Inherit/Yes/No in the share modal). Since then: the Tester role (use-only) and a read-only Workbench for Viewers (411433aa, 2026-09-01); viewer guardrails, "Invite people" entry points, Projects chips and the All Items Unassigned/Everything scope (7801724d, 2026-08-31); the "Shared with me" scope (4098d8ea, 2026-08-31). Phase 3 has shipped — project profile pages, project link sharing, the Recent Activity feed, and Ask to Join (c3a902e9e, 2026-11-07: a reader asks from a world's page, and its owner or a manager approves or declines). Its operational spec is docs-internal/architecture/profile/PROJECT_JOIN_REQUESTS.md.
Multi-user collaboration on projects. Teams co-create characters, modes, lorebooks, and packages within a shared project workspace.
Problem
Projects are single-owner. A creator can share individual entities with granular permissions, but there's no way to collaborate on a project as a whole. This creates friction for teams:
- No shared workspace -- Collaborators see individual shared entities but have no unified view of the project and everything in it
- No project-level access -- Sharing must be done entity-by-entity; there's no way to say "give this person access to everything in this project"
- No role clarity -- The existing permission flags (Use/View/Contribute/Edit/Manage) apply to individual entities, not to a project scope
- No project identity -- Projects have no public-facing profile; there's no way for a team to present their project to collaborators or users
Design Decision: Project Role + Entity-Permission Overrides
Project collaboration uses Option A from the original brainstorm: a project-level role sets default permissions on every item in the project, and any exceptions are expressed as rows in the existing entity_permissions table with nullable flags. A NULL flag means "fall through to the project role"; a non-NULL flag overrides the role (and can subtract as well as add).
Why this model:
- Most teams have clear roles. One person writes lorebooks, another designs modes. A single project role covers the common case.
- Exceptions live in the same table used for direct sharing. There is no separate override table — a "project member override" is just an entity_permissions row that happens to belong to someone who is also a project member, and the resolver composes them automatically.
- The existing 5-flag permission system (Use/View/Contribute/Edit/Manage) composes naturally: the project role is the base, the entity_permissions row is the override layer.
- One storage surface, one resolver path, one UI (the existing
SharePermissionsModal). - The
project_itemstable already binds entities to projects, so the project-role base is a join away.
Existing Infrastructure
The permission and project systems provide a foundation. The current sharing implementation has technical debt that should be resolved before or alongside this work.
What's solid:
- Entity permissions (
entity_permissionstable) -- granular flags with user-specific and unlisted grants - Permission presets -- Tester, Contributor, Editor, Reviewer, Full Access
- Permission audit (
entity_permission_audittable) -- records every permission change - Entity changelog (
entity_changelogtable, partitioned by month) -- tracks all entity changes with user attribution - Projects (
projects,project_items,project_deliverables) -- workspace grouping with item binding, CRUD endpoints, changelog endpoint. Projects have aslugcolumn (format:{user_slug}-{project_slug}, globally unique) generated byfn_generate_unique_project_slugon creation. - DB constraints -- permission dependencies enforced at the database level
What needs fixing first:
Duplicated CRUD endpointsResolved -- The entity sharing rewrite (Steps 5-8) retired the parallel CRUD tree inShareEndpoints.cs. Collaborators use creator endpoints directly, authenticated viaX-Share-Token. No third copy needed.Magic entity type integersResolved --EntityTypeenum +EntityRegistryinCore/Entities/EntityRegistry.csis the canonical backend definition. Frontend shared definition atshared/src/utils/entityTypes.ts. Scattered local copies inclientConsolestill need migrating.- No FK constraints --
entity_permissionsdoesn't reference entity tables. Project-level cascade (deleting a project removes its permissions) needs this. See Add FK Constraints. - No "Shared with me" view -- collaborators can see shared entities in the Creator Hub Collaborations tab, but there's no filterable dedicated page. See Shared With Me.
Broken collaboration endpointResolved --CreatorCollaborationEndpointsnow derives labels from actual permission flags (can_use/can_view/can_contribute/can_edit/can_manage) viaEntityPermissionFlags.ToLabel().
Permission Flags in Project Context
Project collaboration uses the same 5 orthogonal permission flags as entity sharing, but each flag has a specific meaning in the project context. Every UI action checks specific flags — buttons are hidden or disabled when the required flags are not present, the same pattern used in the admin console.
What Each Flag Controls
| Flag | What it grants in a project |
|---|---|
can_use |
Can use project entities in chats (characters, lorebooks, modes). Cannot see source content. |
can_view |
Can see the entity list, open entities to read source content, view the About tab (read-only), open the workbench in read-only mode. |
can_contribute |
Can propose adding their own entities to the project, and propose changes to existing ones. Requires can_view. |
can_edit |
Can directly edit entity content via the workbench. Can add (their own entities), remove, and reorder project items. Requires can_view. |
can_manage |
Can run the Team tab (invite, change roles, remove members, see a member's exceptions on entities they own; every member reads the roster), review the whole proposal queue (approve/reject), edit project About (name, slug, description). Also carries project composition — approving an add is adding. Requires can_view. |
Capability Matrix (Flag-Based)
Each row shows what's required. Flags compose — a member with can_view + can_edit gets everything in both columns.
| Capability | Required flags |
|---|---|
| See project in member list | Any flag (membership exists) |
| Use entities in chats | can_use |
| See entity list | can_view |
| Open entity details (read-only) | can_view |
| Open workbench (read-only) | can_view |
| See About tab (read-only) | can_view |
| Propose new entities to project | can_contribute |
| Propose changes to existing entities | can_contribute + can_view |
| Edit entity content directly | can_edit (implies can_view) |
| Propose adding entity to project | can_contribute and you created the entity |
| Add entity to project (direct) | can_edit or can_manage, and you created the entity |
| Remove entity from project | can_edit or can_manage (curation), or you created the entity and can see the project (creative authority) |
| Reorder project items | can_edit or can_manage |
| See Team tab (the roster, read-only) | Any flag (membership exists) — project members aren't secret |
| See Reviews tab | can_contribute (your own submissions) · can_manage (the whole queue) |
| Manage members and roles | can_manage |
| Edit About (name, slug, description) | can_manage |
Custom Flag Combinations
The PermissionFlagEditor with the "Custom" tab allows any combination of flags that satisfies the
dependency rule (contribute / edit / manage each require view). Some useful combinations beyond the
standard roles:
| Combination | Use case |
|---|---|
can_view + can_manage |
Reviewer — sees everything and runs team/approvals. Also carries project composition, since approving an add IS adding. |
can_view + can_edit + can_manage |
Full admin without proposals — direct edits + team management |
can_view only |
Observer — read-only access to everything, no chat usage |
can_use + can_contribute ("blind contributor") was listed here and is not storable — see
the dependency warning above.
Project Roles (Presets)
Roles are visual descriptors — convenience labels shown in the UI that indicate what a member can do. They are not the source of truth for access control. Permission flags are always authoritative; the role column is a display label that gets set when flags change.
When an admin picks a role preset, the corresponding flags are written. When they use the "Custom" tab to set arbitrary flags, the role is set to custom. The role never gates access — only flags do.
| Role | can_use |
can_view |
can_contribute |
can_edit |
can_manage |
Use case |
|---|---|---|---|---|---|---|
| Tester | yes | Playtesters — chat with the project's content; prompts and source stay hidden (added 2026-08-31) | ||||
| Viewer | yes | yes | Beta readers, consultants reviewing the work — can_view is the source tier: viewers read full prompts/entries in the read-only Workbench and may export |
|||
| Contributor | yes | yes | yes | Writers proposing new content or changes | ||
| Editor | yes | yes | yes | Core team members who edit directly | ||
| Admin | yes | yes | yes | yes | yes | Co-leads with full access |
| Custom | (any) | (any) | (any) | (any) | (any) | Arbitrary flag combination via the Custom tab |
How permissions resolve:
- The project owner always has full access to everything in the project
- A member's flags (not role name) determine access
- Per-entity overrides can adjust flags for specific entities within the project
- If a member also has a direct entity permission grant (outside the project context), the union of both applies — consistent with existing permission merge behavior
Member Management Rules (the bounds on can_manage)
can_manage opens the Team tab. It is deliberately not unbounded: without the four rules below,
"manage the team" and "become the team" are the same permission, and the can_edit / can_manage
split stops being a security boundary at all. Any Admin could write can_manage onto their own row,
demote or evict every peer Admin, and finish as the sole administrator of someone else's project.
The model is the role-hierarchy shape Discord and GitHub both use: you may grant up to what you hold, and you may not act on an equal.
| Rule | Applies to | Refusal code |
|---|---|---|
| No self-mutation of your own authority. A member cannot change their own role or flags. | Everyone, owner included | cannot_change_own_role |
You cannot grant what you don't hold. A non-owner may only set a flag TRUE if they hold that flag themselves — on a role change and on an invite. |
Non-owners | cannot_grant_unheld_permission |
Peer protection. Only the project owner may change or remove a member who holds can_manage. Managers manage non-managers. |
Non-owners | manager_requires_owner |
| The owner's row is untouchable. The project owner cannot be demoted or removed through member management by anyone, including themselves. | Everyone | cannot_modify_owner |
The refusals above are written 403s carrying a code, not a bare Forbid — the caller has
can_manage, so "you lack the permission" would be a lie, and the client cannot gray a control it
cannot name. A caller who simply lacks can_manage still gets the same opaque 403 every other
project gate returns.
Deliberate carve-outs, both of which the rules must not eat:
- Self-removal is allowed. Leaving a project is de-escalation — you gain nothing by resigning —
and it is the only "leave" this endpoint has ever offered. Peer protection is checked after the
self case for
DELETE, and only the role change treats self as a refusal. - A manager may invite or promote another manager. Granting an authority you already hold
escalates nobody, and growing the team is the job
can_manageexists for. The price is a peer they cannot later demote — that undo belongs to the owner, who always exists (projects.owner_idisNOT NULL) and is the recovery path peer protection depends on.
These rules live in one place: ProjectCapabilities.AuthorizeMemberRoleChange /
AuthorizeMemberRemoval / AuthorizeMemberInvite (see One capability
policy). The project_members writes carry a narrower last-line
backstop — the UPDATE refuses the acting user's own row and any row matching projects.owner_id —
which can catch a forgotten gate but never contradict one.
Entity Ownership Within Projects
The Problem
When an entity (character, mode, lorebook) is added to a project, project permissions automatically apply to it. All project members with can_view can see its source, members with can_edit can modify it. This is the point of project collaboration — but it has a consequence the entity owner needs to understand.
The entity's creator remains the owner, but project permissions grant access to everyone in the project regardless of what the entity owner intended. If a creator adds their character to a shared project with editors, those editors can now edit the character's prompts — even if the creator never explicitly shared it with them.
Warning on Add to Project
When an entity is added to a project — either by creating a new entity within a project, or by adding an existing entity to one — the UI shows a confirmation modal:
This entity will be part of "{Project Name}"
Project permissions will apply to this entity. All project members will have access based on their role — viewers can see source content, editors can modify it.
If you want specific members to have different access to this entity, set up per-entity permissions that override the project defaults.
The modal has:
- Add to Project button (confirms)
- Cancel button
- A link to the entity's share settings for setting per-entity overrides
Entity Ownership Rules
| Action | Who can do it |
|---|---|
| Propose adding entity to project | The entity owner, when they are a project member with can_contribute (requires owner/admin approval) |
| Add entity to project (direct) | The entity owner, when they are a project member with can_edit or can_manage |
| Remove entity from project | Entity owner (always, from any project they can see), or a project member with can_edit / can_manage (always) |
| Edit entity content | Entity owner (always), or project member with can_edit — subject to per-entity overrides |
Set per-entity overrides (write entity_permissions rows) |
Entity owner only |
| Delete entity | Entity owner only (regardless of project membership) |
Per-Entity Overrides
Per-entity overrides let the entity owner adjust permissions for specific members on a specific entity. An override is just an entity_permissions row for that user, with some flags explicitly set and others left NULL to fall through to the project role.
Example: A character is in a project where Alice is an Editor. The character's owner opens the character's share modal and adds Alice with can_edit = FALSE (all other flags NULL). Alice's effective access on this character becomes: can_use / can_view / can_contribute / can_manage from her Editor role, and can_edit = FALSE from the override. She can still edit other entities in the project, but not this character.
Overrides are managed exclusively via the existing SharePermissionsModal, which is the single surface for everything entity-scoped: unlisted link sharing, direct user grants, and project-member exceptions. The modal's "People with Access" list labels project members as via {Project Name} and shows their effective flags (project role merged with any override row), with a flag picker that writes the override. Clearing a flag writes NULL (fall through to the project role); explicitly setting a flag writes TRUE/FALSE.
The Team tab's member detail does not host any override editing UI. It can show a read-only list of "entities this member has exceptions on" for context (for entities the viewer owns) — but all writes flow through the entity's share modal.
Permission Revocation on Entity Removal
When an entity is removed from a project, all project-derived permissions for that entity cease immediately. There is no separate revocation step — the permission resolution query joins through project_items, so if the entity is no longer in the project, the join produces no rows and project permissions don't apply.
What happens:
- Project members lose any access they had via their project role. The resolver's project-role base collapses to
FALSEfor them on this entity because theproject_itemsjoin no longer matches. - Any
entity_permissionsrows those members had on the entity still apply. If a row had partialNULLflags (it was an override on top of a project role), theNULLflags now fall through to aFALSEbase instead of a project-role value — effective access on those flags drops toFALSE. A member who hadcan_edit = FALSEand everything elseNULLnow has no access at all. - Direct
entity_permissionsrows with all flags set (traditional direct shares) are unaffected and continue to grant exactly what they say. - The entity owner retains full access regardless.
Example: Alice is an Editor in the project and has been editing a character. The character's owner removes it from the project. Alice immediately loses edit access to that character — unless she also has a direct entity_permissions grant.
Database Design
project_members Table
Stores who has access to a project and at what role level.
CREATE TABLE IF NOT EXISTS project_members (
id SERIAL PRIMARY KEY,
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role VARCHAR(20) NOT NULL DEFAULT 'viewer',
-- Orthogonal permission flags (source of truth)
can_use BOOLEAN NOT NULL DEFAULT TRUE,
can_view BOOLEAN NOT NULL DEFAULT FALSE,
can_contribute BOOLEAN NOT NULL DEFAULT FALSE,
can_edit BOOLEAN NOT NULL DEFAULT FALSE,
can_manage BOOLEAN NOT NULL DEFAULT FALSE,
-- Invitation metadata
invited_by INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
invited_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
joined_at TIMESTAMPTZ, -- NULL = pending invitation
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT chk_project_member_role CHECK (role IN ('viewer', 'contributor', 'editor', 'admin', 'custom')),
CONSTRAINT chk_member_permission_dependencies CHECK (
(NOT can_contribute OR can_view) AND
(NOT can_edit OR can_view) AND
(NOT can_manage OR can_view)
)
);
-- One membership per user per project
CREATE UNIQUE INDEX ON project_members(project_id, user_id);
CREATE INDEX ON project_members(user_id) WHERE joined_at IS NOT NULL;
Key decisions:
- Flags are the source of truth, role is a display label. The
rolecolumn is set when flags change — picking a preset writes the role name, using Custom writes'custom'. Access checks always read flags, never the role string. This means a future "Custom" role (arbitrary flags) needs no storage model change — it already works. joined_atNULL = pending invitation. The row exists from the moment someone is invited, butjoined_atis set when they accept. Queries for active members filter onjoined_at IS NOT NULL.- Permission dependencies enforced at DB level.
can_contribute,can_edit, andcan_manageall requirecan_viewto be true. - CASCADE on project delete. Deleting a project removes all memberships automatically.
No Separate Overrides Table
Earlier drafts of this design introduced a project_member_overrides table. That table has been removed. What it was meant to store — per-member, per-entity exceptions to a project role — is now stored directly in entity_permissions with nullable flag columns.
What changed in entity_permissions:
can_use,can_view,can_contribute,can_edit,can_manageare all nullable.- On a user-specific row (
granted_to_user_id IS NOT NULL), aNULLflag means "fall through to whatever the user's project-role base says". A non-NULLflag explicitly sets that flag, and can subtract as well as add. - On an unlisted row (
granted_to_user_id IS NULL), flags are still expected to be non-NULL— there is no base to fall through to for a link grant. - The dependency CHECK still enforces the rule that a dependent flag cannot be explicitly
TRUEwhilecan_viewis explicitlyFALSEon the same row.NULLcan_viewis allowed, because the effective view comes from the project-role base.
Why one table is better than two:
- The
SharePermissionsModalis already the mental home for "who has access to this entity". Splitting overrides into a separate table would create a second surface that the entity owner has to reason about. - The resolver collapses from three OR-merged paths to two (project base + entity_permissions overlay), which is simpler to read and simpler to test.
- A "project override" and a "direct share with a project member" are the same concept — both are "the owner of this entity decided this user gets these specific flags on this specific entity". Giving them one table names that correctly.
- Removing a member from a project cascades automatically: the
project_itemsjoin disappears, the base flips toFALSE, and anyNULL-flagged override rows degrade gracefully.
Permission Resolution
When a user accesses an entity:
1. Is the user the entity owner?
→ Full access, and can_manage_sharing = TRUE.
2. Project-role base:
OR-merge can_use/can_view/can_contribute/can_edit/can_manage across every
project that contains this entity AND has this user as an accepted member.
If none, the base is all FALSE.
3. User-specific entity_permissions row (at most one, by unique index):
For each flag, COALESCE(ep_user.flag, base.flag).
NULL falls through, non-NULL wins — including explicit FALSE, which can
subtract what the project role granted.
can_manage_sharing is TRUE only if ep_user.can_manage IS TRUE explicitly.
4. Unlisted entity_permissions rows (granted_to_user_id IS NULL):
OR-merged additively on top. Never contribute sharing authority.
This replaces the three-path OR-merge used before Phase 2. Direct grants and project overrides are now the same path (step 3), and the nullable-flag semantics handle both additive grants and subtractive overrides uniformly.
Implementation: fn_get_entity_access + RequireEntityAccess
All access paths are resolved in a single DB call via a SQL function. The function checks ownership, project membership, and direct grants, then OR-merges the flags. The C# side wraps this in a helper that mirrors the existing RequireProjectAccess pattern.
SQL function (fn_get_entity_access, see database/v1/functions/67_entity_access_functions.sql for the authoritative version):
CREATE OR REPLACE FUNCTION fn_get_entity_access(
p_entity_type INTEGER, p_entity_id INTEGER, p_user_id INTEGER
) RETURNS TABLE (
is_owner BOOLEAN, can_use BOOLEAN, can_view BOOLEAN,
can_contribute BOOLEAN, can_edit BOOLEAN, can_manage BOOLEAN,
can_manage_sharing BOOLEAN
) AS $$
DECLARE
v_owner_id INTEGER;
v_base_use BOOLEAN; v_base_view BOOLEAN; v_base_contribute BOOLEAN;
v_base_edit BOOLEAN; v_base_manage BOOLEAN;
BEGIN
-- Resolve owner and validate entity exists (CASE by entity_type)
v_owner_id := /* ... */;
IF v_owner_id IS NULL THEN RETURN; END IF;
-- Owner short-circuit
IF v_owner_id = p_user_id THEN
RETURN QUERY SELECT TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE;
RETURN;
END IF;
-- Step 2: project-role base (OR-merged across memberships)
SELECT COALESCE(bool_or(pm.can_use), FALSE),
COALESCE(bool_or(pm.can_view), FALSE),
COALESCE(bool_or(pm.can_contribute), FALSE),
COALESCE(bool_or(pm.can_edit), FALSE),
COALESCE(bool_or(pm.can_manage), FALSE)
INTO v_base_use, v_base_view, v_base_contribute, v_base_edit, v_base_manage
FROM project_items pi
JOIN project_members pm
ON pm.project_id = pi.project_id
AND pm.user_id = p_user_id
AND pm.joined_at IS NOT NULL
WHERE pi.item_type = /* mapped from p_entity_type */
AND pi.item_id = p_entity_id;
-- Step 3: apply entity_permissions on top of the base
RETURN QUERY
SELECT FALSE,
COALESCE(bool_or(s.can_use), FALSE),
COALESCE(bool_or(s.can_view), FALSE),
COALESCE(bool_or(s.can_contribute), FALSE),
COALESCE(bool_or(s.can_edit), FALSE),
COALESCE(bool_or(s.can_manage), FALSE),
COALESCE(bool_or(s.can_manage_sharing), FALSE)
FROM (
-- Layer A: project base + user-specific override row (nullable flags)
SELECT COALESCE(ep_user.can_use, v_base_use),
COALESCE(ep_user.can_view, v_base_view),
COALESCE(ep_user.can_contribute, v_base_contribute),
COALESCE(ep_user.can_edit, v_base_edit),
COALESCE(ep_user.can_manage, v_base_manage),
(ep_user.can_manage IS TRUE) -- sharing authority: explicit only
FROM (SELECT 1) _
LEFT JOIN entity_permissions ep_user
ON ep_user.entity_type = p_entity_type
AND ep_user.entity_id = p_entity_id
AND ep_user.granted_to_user_id = p_user_id
UNION ALL
-- Layer B: unlisted link grants (purely additive)
SELECT ep.can_use, ep.can_view, ep.can_contribute, ep.can_edit, ep.can_manage, FALSE
FROM entity_permissions ep
WHERE ep.entity_type = p_entity_type
AND ep.entity_id = p_entity_id
AND ep.granted_to_user_id IS NULL
) s;
END;
$$ LANGUAGE plpgsql STABLE;
The COALESCE in Layer A is what makes overrides work: non-NULL flags win over the project base (including explicit FALSE), and NULL flags fall through. bool_or in the outer aggregate then additively merges Layer B's unlisted grants on top.
C# helper (RequireEntityAccess in CreatorEndpointHelpers):
internal static async Task<(EntityAccessResult? access, int entityId, IResult? error)> RequireEntityAccess(
HttpContext context,
string entityName,
Guid entityUuid,
Func<EntityAccessResult, bool> check,
IEntityUuidRepository uuidRepo,
IEntityPermissionRepository permRepo)
{
var userId = context.GetUserId();
var tokenCtx = context.GetShareTokenContext();
// Fast-path: no session and no share token — reject before hitting the DB.
if (userId == null && tokenCtx == null)
return (null, 0, Results.Unauthorized());
var resolvedId = await uuidRepo.ResolveIdAsync(entityName, entityUuid);
if (resolvedId == null) return (null, 0, Results.NotFound());
if (!EntityRegistry.ByName.TryGetValue(entityName, out var def))
return (null, 0, Results.NotFound());
// Anonymous token holder path — token must be scoped to this exact entity.
// A token for character A does not unlock character B or any of its children.
if (userId == null)
{
if (!tokenCtx!.MatchesEntity(def.Type, resolvedId.Value))
return (null, 0, Results.Unauthorized()); // scope mismatch — 401, not 403
var tokenAccess = new EntityAccessResult {
is_owner = false,
can_use = tokenCtx.CanUse, can_view = tokenCtx.CanView,
can_contribute = tokenCtx.CanContribute, can_edit = tokenCtx.CanEdit,
can_manage = tokenCtx.CanManage, can_manage_sharing = false,
};
if (!check(tokenAccess)) return (null, 0, Results.Forbid());
return (tokenAccess, resolvedId.Value, null);
}
// Authenticated path — fn_get_entity_access already OR-merges unlisted
// (share token) rows as Layer B, so authenticated token holders get those
// flags automatically without extra work here.
var access = await permRepo.GetEntityAccessAsync(def.Type, resolvedId.Value, userId.Value);
if (access == null) return (null, 0, Results.NotFound());
if (!check(access)) return (null, 0, Results.Forbid());
return (access, resolvedId.Value, null);
}
Endpoint usage (replaces GetOwnerIdAsync + ownership check):
// Before:
var ownerId = await characterRepo.GetOwnerIdAsync(characterIdInt.Value);
if (ownerId != userId) return Results.Forbid();
// After:
var (access, entityId, error) = await RequireEntityAccess(
context, "character", characterId, a => a.CanEdit, uuidRepo, permRepo);
if (error != null) return error;
Migration strategy: Migrate one entity type at a time — characters first, then modes, then lorebooks. Each is self-contained. The GetOwnerIdAsync pattern remains valid for owner-only operations (delete entity) that should never be project-gated.
API Endpoints
Project Membership Management
All under /api/creator/projects/{projectId}/members. Members are identified by their user slug -- no internal IDs are exposed to the frontend. Require project owner or Admin role, bounded by the member management rules — can_manage opens these routes, it does not make every target reachable.
| Method | Path | Description | Auth |
|---|---|---|---|
GET |
/members |
List all members with roles and status | Owner or Admin |
POST |
/members |
Invite a user (by slug) with a role | Owner or Admin, capped at the inviter's own flags |
PUT |
/members/{memberSlug}/role |
Change a member's role | Owner, or Admin acting on a non-manager who is not themselves; capped at their own flags |
DELETE |
/members/{memberSlug} |
Remove a member | Owner, Admin acting on a non-manager, or self (leave) |
POST |
/members/accept |
Accept a pending invitation | Invited user |
POST |
/members/decline |
Decline a pending invitation | Invited user |
A refused write returns 403 with a body of { error, code } where code is one of
cannot_change_own_role · cannot_grant_unheld_permission · manager_requires_owner ·
cannot_modify_owner. A caller with no can_manage at all still gets a bare 403.
Invite request:
{
"slug": "alice-writes",
"role": "editor"
}
Member response:
{
"username": "alice_writes",
"slug": "alice-writes",
"displayName": "Alice",
"avatarUrl": "...",
"role": "editor",
"status": "active",
"joinedAt": "2026-04-10T12:05:00Z",
"invitedAt": "2026-04-10T12:00:00Z",
"invitedByUsername": "creator",
"invitedByDisplayName": "You"
}
Per-Entity Overrides
No new endpoints. Overrides are just entity_permissions rows, so they go through the existing entity permission endpoints that SharePermissionsModal already calls:
| Method | Path | Description |
|---|---|---|
GET |
/api/creator/{entityType}s/{entityId}/permissions |
List all permission rows (unlisted + user grants, with nullable flags) |
POST |
/api/creator/{entityType}s/{entityId}/permissions/user |
Add or update a user-specific row. Request accepts nullable flags; null = "don't set this flag, fall through". |
DELETE |
/api/creator/{entityType}s/{entityId}/permissions/{permissionId} |
Remove a user's override entirely (revert to their project role) |
The Team tab's "what exceptions does this member have on entities I own" read-only view can reuse GET /api/creator/{entityType}s/{entityId}/permissions filtered by user, or be served by a convenience list endpoint under /api/creator/projects/{projectId}/members/{memberSlug}/exceptions if it turns out to be awkward to fetch across entity types. That decision is deferred to the Phase 2 UI work — no new write path either way.
Collaborator-Facing Endpoints
| Method | Path | Description |
|---|---|---|
GET |
/api/collaborations/projects |
List projects the user is a member of |
GET |
/api/collaborations/projects/{projectId} |
Project details + items with effective permissions |
GET |
/api/collaborations/invitations |
List pending invitations |
Project Access for Members
Existing project endpoints (/api/creator/projects/{id}, /api/creator/projects/{id}/items, etc.) expand access from owner-only to owner + members with appropriate role checks:
| Endpoint | Owner | Admin | Editor | Contributor | Viewer |
|---|---|---|---|---|---|
| Get project | Yes | Yes | Yes | Yes | Yes |
| List items | Yes | Yes | Yes | Yes | Yes |
| Update project | Yes | Yes | No | No | No |
| Delete project | Yes | No | No | No | No |
| Add items (direct) | Yes | Yes | No | No | No |
| Propose adding items | Yes | Yes | Yes | Yes | No |
| Remove items | Yes | Yes | No | No | No |
| Reorder items | Yes | Yes | Yes | No | No |
| Changelog | Yes | Yes | Yes | Yes | Yes |
Frontend
Projects Page: New "Team" Tab
The Projects page (/creator/projects) uses a three-panel layout: project list (left), entity list (center), project detail (right drawer). The right drawer currently shows project name, actions, and changelog via ProjectDetailPanel.
Tabs in the header switch the center panel content -- the same pattern the workbench uses for Editor / Map / Sandbox. Only visible for real projects (not the "All Items" virtual project). The header shows a static project title (no inline editing -- name editing lives in the About tab).
Tab bar in the header, content in the center panel:
| Tab | Center Panel Content | Status |
|---|---|---|
| About | Project metadata form (name, slug, description, visibility) | Built |
| Entities | Entity list with filter tabs, Add Item button in toolbar | Built |
| Team | Member management (two-column on desktop) | Built (connected to API) |
| Reviews | Proposal diffs and approval workflow across three proposal flavours in one queue: entity field updates, entity-relationship bindings (link/unlink greetings + lorebooks to characters), and CRUD on sub-entity child rows (lorebook entries + mode sub-prompts). Managers see all pending + history; contributors see their own drafts and submissions. A count badge on the tab sums actionable work across all three flavours. | Built |
The right drawer is simplified to actions (Open in Workbench) and the changelog activity feed. Project metadata editing moved entirely to the About tab.
URL deep-linking: The Projects page supports ?project={uuid|slug}&tab={tab} query parameters for external navigation. Projects can be referenced by UUID or slug. Parameters are consumed on load and cleared from the URL to prevent stale state on refresh. Used by the SharePermissionsModal's project warning link.
Team view layout:
Desktop (two columns):
- Left column -- member list (always visible). Owner pinned at top, then active members, then pending invitations. Invite/add button at the top.
- Right column -- context-sensitive:
- No member selected → global project sharing settings (share link, default role for link invites)
- Member selected → member detail form (role picker, read-only list of exceptions on entities the viewer owns, activity feed, remove button). Exception rows link out to the entity's share modal, which is where all override writes happen. Role and activity changes save inline; selecting another member or deselecting switches back.
Mobile (single column):
- Top section: global project sharing settings (share link)
- Below: member list with invite/add button
- Tapping a member replaces the entire view with the member detail form + back button. Saving or pressing back returns to the list.
Member list contents:
- "Invite Member" primary button (toggles to "Cancel" when form is open) with
?info button for the Permissions Guide Modal - Invite flow:
UserSearchDropdown→RichSelectwith role descriptions → "Send Invite" button, with info note about adjusting permissions later - Owner pinned at top, active members, then pending invitations
- Avatar, display name, role badge, last activity
Member detail panel contents:
- Permission editor --
PermissionFlagEditorwith project role presets (Viewer / Contributor / Editor / Admin / Custom). Visible for both active and pending members so roles can be set before acceptance. Explicit Save button (disabled when clean). - Exceptions on entities you own -- read-only list of entities in the project where the current viewer owns the entity AND has written an
entity_permissionsrow for this member. Each row shows the overridden flags and links out to the entity'sSharePermissionsModal, which is where all override writes happen. Non-owners see nothing here. - Member activity feed -- compact changelog of this member's recent changes within the project
- Show Profile button (navigates to
/creator/{slug}) - Remove/Cancel invitation button (danger variant with confirmation)
Link sharing settings (no member selected):
- Toggle with description: "Share access without making the project public. Ideal for private collaboration with people outside your team."
LinkCopyInput-- read-only URL with integrated copy and regenerate (confirmation modal)PermissionFlagEditor-- base permissions for link visitors, with explicit "Save Permissions" button (always visible, disabled when clean)
Permissions Guide Modal (PermissionsGuideModal) -- reusable modal accessible via the ? button, explaining project roles, per-entity permissions, share link vs. members, and when to use what. Full-screen on mobile.
Project List: Ownership Badges
The project list in the left drawer (ProjectListPanel) currently only shows projects the user owns. With collaboration, the list also includes projects shared with the user and pending invitations. Each project card needs a badge below the stats row to communicate the user's relationship to the project:
| Badge | Meaning | Visual |
|---|---|---|
| Owner | User owns this project, no collaborators | No badge (solo project, current behavior) |
| Owner · Shared | User owns this project and has shared it with others | Shared badge with member count, e.g. Shared · 3 members |
| Editor / Viewer / etc. | User is an active member with this role | Role name badge, e.g. Editor · shared by Alice |
| Invited | User has a pending invitation | Invited badge in accent/primary color |
The distinction between a solo owner project and a shared owner project matters — it tells the creator at a glance which projects have active collaborators who may be working on them.
Card layout examples:
Owned, solo (no change from today):
┌──────────────────────────────────────────┐
│ My Character Project [⚙] [🗑] │
│ 2 hours ago │
│ 🧊 3 entities 📦 1 package │
└──────────────────────────────────────────┘
Owned, shared with others:
┌──────────────────────────────────────────┐
│ Team Lore Project [⚙] [🗑] │
│ 2 hours ago │
│ 🧊 5 entities 📦 2 packages │
│ 👥 Shared · 3 members │ ← collaboration indicator
└──────────────────────────────────────────┘
Member (collaborator):
┌──────────────────────────────────────────┐
│ Alice's World [⚙] │
│ 2 hours ago │
│ 🧊 8 entities 📦 1 package │
│ 👤 Editor · shared by Alice │ ← role + sharer
└──────────────────────────────────────────┘
Pending invitation:
┌──────────────────────────────────────────┐
│ Bob's Campaign [✓] [✗] │
│ │
│ 👤 Invited as Editor · by Bob │ ← accept/decline buttons
└──────────────────────────────────────────┘
Behavior per badge type:
- Owner (solo) -- no badge, current behavior unchanged
- Owner (shared) --
Sharedbadge with member count. Clicking the badge or selecting the project shows the Team tab. Signals that other people may be actively working in this project. - Member projects -- role badge with sharer name. No delete button (only owner can delete). Workbench button respects role permissions.
- Invited projects -- invitation badge with inline accept/decline buttons replacing the workbench/delete buttons. Accepting moves the project into the member list with the assigned role badge. Declining removes it from the list.
Sorting: Invited projects appear at the top of the list (above owned projects) to surface pending actions. Owned and member projects are mixed and sorted by last activity.
Workbench Awareness
The workbench doesn't get its own collaboration tab. Instead, it shows lightweight context:
- Team strip -- avatars of current project members shown in the project context drawer (left side), below the entity list
- Your role indicator -- if the current user is a collaborator (not owner), a subtle role badge appears in the workbench header
- Permission-gated controls -- edit forms, delete buttons, and sharing settings respect the user's effective permissions. Read-only collaborators see the entity detail view but cannot enter edit mode.
"My Collaborations" Page
A new page at /collaborations (or integrated into Creator's Forge navigation) replaces the dead CreatorCollaborationEndpoints:
Sections:
- Pending Invitations -- projects the user has been invited to but hasn't accepted, with accept/decline buttons
- My Projects -- projects where the user is an active member, showing project name, cover, owner, member count, role, last activity
- Shared Entities -- individual entities shared with the user outside of any project context, using actual permission flags instead of the broken
permission_level
Permission-Aware UI
Every UI control checks the member's specific permission flags, not their role name. This is the same pattern used in the admin console — each button/tab/action has a required flag, and the UI hides or disables it when the flag is absent.
Projects page — tab visibility:
| Tab | Required flag | Behavior without flag |
|---|---|---|
| About | can_view (read-only), can_manage (editable) |
Hidden for Use-only members |
| Entities | can_view (read-only list), can_edit (full list) |
Use-only members see a card linking to the project share page instead |
| Team | Any flag (read-only roster), can_manage (invite, roles, removal, exceptions) |
Hidden only from non-members |
| Reviews | can_manage |
Hidden |
Projects page — entity list actions:
| Action | Required flag |
|---|---|
| Open entity in workbench (read-only) | can_view |
| Open entity in workbench (edit mode) | can_edit |
| Propose adding item to project | can_contribute |
| Add item to project (direct) | can_manage (or entity owner) |
| Remove item from project | can_manage (or entity owner) |
| Reorder items | can_edit |
| Propose new entity | can_contribute |
| Use entity in chat | can_use |
Use-only access (can_use without can_view):
Members with only can_use see a simplified view when they open the project — instead of the entity list, they see a card explaining they have use-only access with a link to the project share page (via share token). They can use project entities in chats but cannot browse the entity list or see source content.
Notifications
| Event | Who Gets Notified | Notification Type |
|---|---|---|
| Invited to project | Invited user | ProjectInvitation |
| Invitation accepted | Project owner + admins | ProjectMemberJoined |
| Role changed | Affected member | ProjectRoleChanged |
| Removed from project | Removed member | ProjectMemberRemoved |
| Member left | Project owner + admins | ProjectMemberLeft |
| New item added to project | All members (configurable) | ProjectItemAdded |
| Someone asked to join | Project owner + admins | ProjectJoinRequested |
| Join request approved | The requester (and the other admins hear a member joined) | ProjectJoinRequestApproved |
| Join request declined | The requester, with the reason when one was given | ProjectJoinRequestDeclined |
Implementation Phases
Phase 0: Prerequisites
Resolve architectural debt that blocks clean project collaboration:
FixDone -- Rewritten to use actual permission flags (CreatorCollaborationEndpointscan_use/can_view/can_contribute/can_edit/can_manage) viaEntityPermissionFlags.ToLabel(). See Phase 1 item 10.Add entity type enumDone --EntityTypeenum andEntityRegistryexist inserver/EchoOfDreams.Core/Entities/EntityRegistry.cs(single source of truth for all entity type IDs, table names, route segments). Frontend equivalent atshared/src/utils/entityTypes.tsmirrors the backend definitions. Remaining work: migrate scattered local definitions inclientConsole(reports.tsentityTypeMap, projects.tsENTITY_TYPE_ROUTE_MAP, galleryENTITY_TYPE_ICONS, commentsENTITY_TYPE_LABELS) to import from the shared module.Extract shared CRUD logicDone -- The entity sharing rewrite retiredShareEndpoints.csCRUD entirely. Collaborators authenticate viaX-Share-Tokenand call creator endpoints directly — no shared service extraction needed; the creator endpoints are the single implementation.
Phase 1: Project Membership (Minimum Viable Collaboration)
The smallest useful increment. After this, teams can work together on a project.
Frontend UI shell -- Team tab with member list, invite (real user search), permission editor, link sharing, and Reviews tab placeholderDoneDoneproject_memberstable + migration -- schema, view (vw_project_members), indexesMembership endpoints -- invite (by slug), change role (by slug), remove (by slug), listDoneConnect Team tab to backend -- real API calls for list, invite, role change, removeDoneAbout tab -- project metadata form (name, slug, description), save button, visibility + profile placeholdersDoneProject slugs -- auto-generated from name viaDonefn_generate_project_slug, added to projects table, view, API responseExpand entity endpoint access --Done --fn_get_entity_accessSQL function +RequireEntityAccessC# helper replacesGetOwnerIdAsyncownership checks. Single DB call resolves owner/project member/direct grant. Migrate per entity type: characters → modes → lorebooks. See Implementation: fn_get_entity_access.fn_get_entity_accesscreated with CASE-based entity type mapping (no entity_registry table needed).RequireEntityAccesshelper inCreatorEndpointHelpers. Characters (12 checks), modes (9 checks), lorebooks (7 checks) migrated. (Phase 2 subsequently rewrote the resolver to use nullableentity_permissionsflags and dropped the separate overrides table.)Invitation notifications -- notify on invite, accept, role change, removalDone -- 5 notification types (18-22) with best-effort dispatch (try/catch). Accept fans out to owner + admin members.Accept/decline invitation endpoints --Done -- Custom auth pattern (pending members not inPOST /members/accept,POST /members/declinevw_user_projects). Frontend: invitation cards inProjectListPanelwith accept/decline buttons,GET /invitationsendpoint, toast feedback."My Collaborations" page -- list projects the user is a member of + pending invitationsDone -- Fixed the existing Collaborations tab inCreatorHubPage(extracted to its own fileCollaborationsTab.tsx). Three sections: pending invitations (with accept/decline), member projects (filtered fromgetProjects()), and shared entities (with correct permission flags derived viaEntityPermissionFlags.ToLabel()instead of the broken legacypermission_level).
What this delivers: A creator invites collaborators to their project via the Team tab. Collaborators see the project in their collaborations page, can view project items, and (if Editor+) can edit them through the existing creator endpoints.
Shared components built for this phase:
PermissionFlagEditor-- preset tabs + custom flag checkboxes, used by entity sharing modal, team link sharing, and member detailMemberRow-- lightweight card with Avatar, Badge, and action slot, used by entity sharing modal and team member listLinkCopyInput-- read-only URL input with copy + regenerate (with confirmation), reusable for any share link UIUserSearchDropdown-- debounced user search with dropdown results, click-outside dismiss, used by entity sharing modal and team invitePermissionsGuideModal-- reusable modal explaining project roles, entity permissions, share link vs. members, and when to use whatInputprefix prop -- non-editable text prefix inside the input (used for slug with user prefix)shared/src/utils/permissions.ts-- canonical permission types, presets, role resolution, helpers
Cross-feature integration built for this phase:
Entity → project awareness --DoneGET /api/creator/projects/for-entityendpoint returns projects containing an entity.SharePermissionsModalfetches this on open and shows a warning when the entity belongs to a project, with a link to the project's Team tab.URL deep-linking -- Projects page readsDone?project={uuid}&tab={tab}query parameters, enabling external links to open a specific project tab directly.
Phase 2: Per-Entity Overrides
The separate project_member_overrides table has been dropped. Phase 2 is now a schema simplification plus UI work on the existing share modal — no new endpoints, no new table.
DropDone -- Replaced with a tombstoneproject_member_overridestableDROP TABLE IF EXISTSindatabase/v1/24b_tables_project_member_overrides.sql.MakeDone --entity_permissionsflag columns nullablecan_use/can_view/can_contribute/can_edit/can_managedroppedNOT NULLand defaults. CHECK constraint updated to allowNULLcan_viewwhen dependent flags are explicitlyTRUE(the effective view comes from the project base).RewriteDone -- Two-layer resolver: project-role base, thenfn_get_entity_accessentity_permissionsoverlay viaCOALESCEfor the user row plus additivebool_orfor unlisted rows.can_manage_sharingis granted only by an explicit non-NULLep_user.can_manage = TRUE.- C# DTOs / repository reads -- update entity permission DTOs to
bool?for the 5 flag columns. Existing rows are all non-NULL, so no immediate behavior change, but the write path and read path need to handleNULLbefore the UI can produce them. Request models for the permission endpoints already allow omitted fields; verify the repository does not coerce missing flags toFALSEon insert. - Share modal UI for project-member exceptions -- in
SharePermissionsModal:- The "People with Access" list labels project members as
via {Project Name}with their effective flags (project role merged with any override row). - The flag picker on a project-member row lets the owner set flags to
TRUE,FALSE, or "inherit" (writesNULL). - Unlisted grants and pure direct grants behave exactly as today —
NULLis only meaningful on user-specific rows and the UI only exposes the tristate for project members. - The "Grant additional permissions" section auto-suggests project members who don't yet have an override, so the entity owner can create one without typing.
- The "People with Access" list labels project members as
- Team tab read-only exceptions list -- the member detail panel gains a "Exceptions on entities you own" section listing each entity in the project where the current viewer owns the entity AND has written an
entity_permissionsrow for this member. Each row links to the entity's share modal. Read-only here by design — all writes go through the modal. - Tests --
fn_get_entity_accessblackbox tests covering: project base only, base + user override (additive), base + user override (subtractive explicitFALSE), base + unlisted (additive), project base withNULLfall-through on a dependent flag, sharing authority granted only by explicitep_user.can_manage = TRUE, owner short-circuit, unsupported entity type returns zero rows.
What this delivers: Fine-grained control. An Editor on the project can be restricted to View-only on a specific character, or a Viewer can be elevated to Editor on one lorebook — all controlled exclusively by the character's creator, through the same share modal they already use for direct shares.
Authority model: Owner-only by default. See Per-Entity Overrides for the full rationale and the future opt-in delegation path.
Phase 3: Project Profile + Discovery + Ask to Join
- Project profile page -- public/unlisted page showing project info, team, published content
- Project link sharing -- unlisted link to invite collaborators before the project is public
- Activity feed -- project-wide changelog drawing from
entity_changelog - Ask to Join -- ✅ shipped: a reader can ask to join a world they find on its page
Ask to Join (shipped)
A world that is open to the public — listed on Discover, or open to anyone with its link — can be asked to join by anyone signed in who isn't on its team yet.
Asking. On the world's page, Ask to join sits in the bar next to Share and Report. It opens a short form with an optional note to the team ("I'd love to help map the ports"). Once sent, the button reads Request sent; opening it shows the note and lets the reader withdraw the request. A visitor who isn't signed in is asked to sign in first and comes back to the same world.
When the button is disabled, it says why. Already invited to the world, asked too many worlds at once, recently declined, or a world with too many requests waiting: the button stays visible and names the reason. A world that isn't open to the public shows no Ask to join to people outside its team.
Answering. The world's owner and its managers get a notification for each request. They answer from the world's page (Manage → Join requests, open to every manager) or from the Forge's Team page. Approving lets them pick the role the new member joins at — only roles they hold themselves — and the person joins straight away. Declining can carry a short reason, which the person sees. Either way the person is told.
From a connected agent. An assistant connected to the account over MCP can do the same through a pack it loads on request: list its own requests, ask to join, withdraw, and, for a world it manages, list, approve and decline.
Keeping it calm. One open request per person per world. After a decline, the same person can ask that world again in 30 days; after withdrawing, in a day. A person has a limited number of open requests across all worlds at once, and a world holds a limited number waiting, so nobody's inbox floods.
Not included (for now): a block list (the 30-day wait after a decline covers it), and automatic approval for open worlds.
Future Phases
These depend on other planned features being built first:
- Comments on project items -- depends on Comments
- Permission audit UI -- depends on Creator Audit Trail
Open Questions
Ownership
- Should project ownership be transferable?
- Can a project have co-owners, or is the Admin role sufficient?
Multi-Project Entities
- If an entity belongs to multiple projects, do permissions stack or stay isolated per-project?
- Current design: permissions from all sources (owner, project role, project override, direct grant) are OR-merged. This means more projects = more access, never less. Is that acceptable?
Scope Boundaries
- Real-time collaboration (multiple editors at once) is out of scope for the initial version
One capability policy (WP-11)
Every question on this page — "may this member add an item", "may they remove one", "may they see
Team" — is answered in exactly one place: ProjectCapabilities
(server/EchoOfDreams.Core/Authorization/ProjectCapabilities.cs), built from the five flags plus
project ownership, with the entity-dependent half in
ProjectItemCapabilityResolver (server/EchoOfDreams.Database/Authorization/).
- Endpoints gate through
CreatorProjectEndpoints.RequireProjectAccess, which is now a thin HTTP adapter over that policy (it keeps the project share-token merge, which never grantscan_manage). - Non-HTTP callers — the agent lane's staging gates and
ProjectGate— call the same record, so an agent and the REST API cannot answer differently. - The client is told, not asked to derive.
ProjectResponse.capabilities,ProjectItemsResponse.capabilities, and per-itemcanRemove/canEditEntitycarry the server's answer to the UI. The client must gate affordances on those and never on arithmetic overcanEdit/canManage— every place it did, it disagreed with the server in one direction or the other.
Adding a capability means adding a property to the record and a field to the projection. It does
not mean writing access.can_edit somewhere new.
Acceptance Criteria
The feature is not done until every box below is verified ✅ against the running product.
User use cases — satisfiable + accessible (verify by driving the UI, not the code):
- As a project Editor, I can add my own character to the project, reorder the item list, and remove any item — from the Projects page entity list, without insider knowledge.
- As a project Contributor, I can submit my own character for review, and see my submission in the Reviews tab. The project appears as a valid drop target while I drag.
- As a project Admin/Owner, I can approve or reject that submission from the Reviews tab.
- As an entity creator who is only a viewer on a project my character was added to, I can remove my character from that project — the per-item action is present and it succeeds.
- As a Viewer, the Projects page offers me no add, remove, reorder, or Team affordance at all — not a disabled one and not one that 403s.
Behavior:
- Adding an entity to a project requires being that entity's creator, on both the direct lane
(
POST /items,POST /items/transfer) and the proposal lane (POST /item-proposals). A non-creator gets403 not_entity_ownernaming the reason. - Approving a proposal re-checks that the SUBMITTER still owns the target entity, at both
layers — the endpoint (
409 not_entity_owner, before any write) andfn_apply_project_item_proposal(refusal row, under its own lock). The create gate alone is not enough: a project owner holds bothCanProposeAddandCanApproveProposal, so self-submit-then-self-approve was a one-request bypass of it. - Ownership is re-read at approve time, not trusted from submission time: an entity that changed hands after submission is refused while still live.
-
GET /api/creator/projectsandGET .../itemsreturn acapabilitiesobject; the item rows carrycanRemove,canEditEntity, andisEntityOwner. -
canEditEntityreflects a per-entityentity_permissionsoverride that revokes edit, not just the project role. -
projects.items_versionmoves on add, on remove, on proposal approval, and on every agent-proposal apply that writesproject_items(pool add/remove and each create-and-pool) — not only on reorder and transfer — so an order token built before any of those is rejected as stale. -
POST /items/removereturns a per-item envelope ({ removed, results[] }) with a code on each item that did not move (not_removable/not_pooled/item_not_found), not a flat count that hides a partially-refused batch. - An Editor (
can_edit,can_contribute = FALSE) is accepted by the transfer, item-proposal, and package-save endpoints — includingfn_save_package_full's own SQL gate, which had kept the narrowercan_contributepredicate and 403'd the Editor from Postgres after the C# gate passed them. - A non-owner Admin cannot write
can_manage(or any flag) onto their own membership row:PUT /members/{self}/rolereturns403 cannot_change_own_roleand persists nothing. - A non-owner Admin cannot set a flag they do not hold themselves — a
can_view + can_manageReviewer promoting someone to Editor gets403 cannot_grant_unheld_permission, on the invite route as well as the role-change route. - A non-owner Admin cannot demote or remove a member who holds
can_manage:403 manager_requires_owneron both verbs, nothing written. - The invite route is bounded identically, because it upserts:
POST /membersnaming an existing peer manager at a lower role returns403 manager_requires_ownerrather than quietly demoting them. Every rule that guardsPUT .../roleguardsPOST /memberstoo. - The project owner is bounded by none of it — they can demote and remove a manager, so a team that deadlocks has a recovery path.
-
fn_grant_project_item_proposal_review_accessrefuses on its own, called directly in SQL with no C# in the path: a grantor who does not own the live target entity, or a grantee who is not the target project's owner, writes noentity_permissionsrow and no provenance row.
Invariants that must stay true (carve-outs — the spec'd-free/exempt paths):
- A
can_use-only member (nocan_view) can still see the project in their list and pin/unpin it, and still cannot read the item list or any entity source. Reads are not one tier. - The Editor preset keeps composition:
can_editalone is sufficient to add (own entities), remove, and reorder. Composition is nevercan_manage-only. - A project share token never grants
can_manage, ownership, or entity sharing authority, and an out-of-scope token grants nothing. - Approving/rejecting someone else's proposal stays
can_manage— it is not unified with "may this member add an item". Reviewer authority is over the PROJECT: a reviewer who owns the entity does NOT thereby rescue a proposal from a submitter who doesn't. - Removing an item requires no entity ownership for a project editor (curation survives), and an Editor's removal costs no per-entity lookup.
- The entity-owner detach carve-out is reachable, not just advertised. Every capability the
item projection renders is one the endpoint honours, in both directions: an entity creator
with only
can_viewcan remove their own item (projection says yes → endpoint says yes), and no operation the endpoint allows is hidden by the projection (the bulk "Remove from project" action and the drag-to-pool path both offer it to that same creator). - The carve-out is scoped to ownership, not membership: the same
can_view-only member is refused (not_removable) on an item they did not create, and a non-member is refused outright — it is never a way INTO a project. - A manager still manages. The bounds on
can_managemust not disable it: an Admin can still invite, re-role, and remove non-manager members, and can still invite AT the admin preset. A rule that closes the escalation by closing the feature is a failure, not a fix. - Self-removal survives. A manager can still remove their own membership row (leave). Peer
protection is checked after the self case on
DELETE, never before it. - The project owner's row is untouchable by rule, not by accident. Targeting the owner with
PUT .../roleorDELETEreturns403 cannot_modify_owner— not the404 "member not found"that the absentproject_membersrow used to produce.
Edges:
- Unknown project UUID → 404 before any permission is evaluated; no access → 404, never a "you may not" that confirms existence.
- A batch add/transfer containing one non-owned entity refuses the WHOLE batch and writes nothing (default, non-partial semantics).
- A duplicate add (item already pooled) reports
duplicateand does NOT moveitems_version. Same for an agent-proposal pool add that hitsalreadyPresent, and a pool remove of something that was never there (notPooled) — a no-op must not hand every open workbench a spurious 409. - A bulk remove of a mix of own and foreign items removes only the own ones and reports each item's fate; the foreign ones are never deleted.
- The unclaimed "All Items" pseudo-project offers no remove/reorder affordance and reports closed capabilities.
- Any pending proposal that predates the ownership gate — a
status = 0row whose submitter does not own the target — is rejected by the one-shot remediation (database/v1/91_project_item_proposal_ownership_remediation.sql), with an audit row and the leaked proposal-scoped review grant revoked. Re-running the migration is a no-op.