Manage Folder Permissions & Sharing

Author: James Derick Billate
Updated by: Christian Denzon
Reviewer: Patrick Babala, Clyde Ador
Creation Date: July 2, 2026
Status: Approved and Merged
References:


INTRODUCTION AND GOALS

Problem Summary: This feature is related to folder structures that consist of projects, quests, and adventures. Manage Folder Permissions & Sharing (MFPS) allows various individuals to collaborate within a folder without exposing too much information. It supports controlled folder access through permission levels assigned to existing WyzQuests accounts.

Since the August 2026 core-logic overhaul (PR #745), permissions are no longer evaluated per folder in isolation: every folder's effective role is resolved by walking the folder hierarchy, so ancestor authority (owner/admin), ancestor view caps, and creator ownership are all applied consistently across reads and writes.

Goals and Non-Goals:

  • All created folders start in Private mode (unless shared); other accounts cannot access them.

  • Assignment of folder access is limited to view, edit, and admin for invited users, with owner reserved for the folder owner. The root tree owner is the absolute owner of the entire folder tree.

  • Email can be used to invite existing accounts.

  • Agency Admin does not automatically have the ability to access other folders created by members unless ownership or permission rules allow it.

  • Hierarchy inheritance is implemented: an owner/admin of any ancestor folder keeps authority over every nested subfolder, and a user demoted to Viewer on an ancestor is capped to Viewer for the whole subtree (see the Permission Model section for the exact exceptions).

  • Only the folder owner/Admin may manage permissions. Edit and View collaborators cannot manage permissions; nobody can change their own role; only the root tree owner can grant the Admin role.

  • Collaborators with view-or-higher access can preview shared content and create their own independent copy via "Use as Template" (MFPS Phase 2).

  • Non-goals: pending invites for users without a WyzQuests account; per-quest/per-adventure sharing outside a folder (creator share links are a separate feature); organization-wide automatic access.


HIGH-LEVEL ARCHITECTURE

System Diagram:

Frontend: Next.js (App Router), React, Tailwind CSS, Shadcn/UI components, @dnd-kit drag-and-drop, Sonner toast notifications.

Backend: RESTful API routes, TypeScript, Zod validation, Supabase Auth, agency ownership helpers, folder hierarchy resolvers and access guards (lib/folder/folderAccess.ts, lib/folder/folderListEnrichment.ts, lib/folder/sharedContentAccess.ts), Supabase.

Database: Supabase Postgres with folder_permissions, project_folders, quest_folders, adventure_folders, and app_users.

Email: EmailService and renderShareFolderEmail (the ShareFolderEmail React Email template), sent asynchronously via after() when a permission is granted.

Authentication note: The platform migrated from Clerk to Supabase Auth in September 2026. folder_permissions.user_id and all folder creator_id columns reference app_users.id — the internal user UUID linked to Supabase Auth. Legacy clerk_id / user_clerk_id column names still exist on older tables and store Supabase Auth UUIDs; they are naming artifacts only. MFPS code must never treat them as Clerk IDs.


DETAILED DESIGN & IMPLEMENTATION

Database Schema

Final effective structure of folder_permissions (after the May, July, and August 2026 migrations):

folder_permissions (
id uuid primary key default gen_random_uuid(),
folder_id uuid not null, -- polymorphic: project_folders | quest_folders | adventure_folders
user_id uuid not null, -- app_users.id (internal Supabase Auth user UUID)
permission_level text not null default 'view'
check (permission_level in ('view', 'edit', 'admin', 'owner')),
created_at timestamptz default current_timestamp,
updated_at timestamptz default current_timestamp,
 
constraint folder_permissions_folder_id_exists_check
check (folder_permissions_folder_exists(folder_id)),
constraint folder_permissions_user_id_fkey
foreign key (user_id) references app_users (id)
);
 
-- Added August 2026 (PR #782): requires the pair to be unique for the owner-row upsert
create unique index idx_folder_permissions_folder_user_unique
on folder_permissions (folder_id, user_id);
 
create index idx_folder_id on folder_permissions (folder_id);
create index idx_folder_permissions_user_id on folder_permissions (user_id);

Implementation Notes:

  • folder_id can reference a folder in project_folders, quest_folders, or adventure_folders.

  • folder_permissions_folder_exists(folder_id) validates that the folder exists in at least one supported folder table.

  • permission_level supports view, edit, admin, and owner.

  • folder_id + user_id is unique (dedup migration kept the strongest level before adding the index) — this is required by the owner-seeding upsert.

  • assignOwnerPermission(folder_id, owner_id) upserts the creator's owner row when a folder is created. Since PR #782 it returns { error }, and the quest-folder route rolls the folder back if seeding fails, so owner-less folders are never persisted silently.

  • Delete triggers (cleanup_folder_permissions_on_folder_delete) clean up permission rows when a project, quest, or adventure folder is deleted.

  • An updated_at trigger (folder_permissions_updated_at_trigger) maintains the timestamp on updates.

Ancestor-chain RPC (PR #782): get_folder_ancestors(p_folder_id uuid, p_table text) is a SECURITY DEFINER function that returns the folder's full ancestor chain (the folder itself first, then its parent, grandparent, … up to the root, ORDER BY depth, walk capped at 100 levels) in a single recursive-CTE round trip. It replaced per-level ancestor queries (N+1). The function accepts only project_folders, quest_folders, or adventure_folders as p_table; EXECUTE is revoked from PUBLIC and granted only to authenticated and service_role.

Row Level Security (final): RLS is enabled on folder_permissions. Policies:

Policy

Command

Rule

All can view the members

SELECT

Any authenticated user who has a permission row on the same folder

Owner and Admin insert Permission

INSERT

Requester holds an owner/admin row on the folder or is the literal folder creator; the new level must be view, edit, or admin (owner rows cannot be created via PostgREST)

Owner and Admin update Permission

UPDATE

Same gate as INSERT; owner-level rows are immutable by anyone except their owner

Owner and Admin delete Permission

DELETE

Same gate as INSERT; an owner-level row can only be deleted by its own holder (which the API blocks anyway)

Important: The server routes use the service-role client (lib/supabase.ts, SUPABASE_SERVICE_ROLE_KEY), which bypasses RLS. Route-handler authorization (the helpers below) is the enforcement point; RLS is defense-in-depth for direct PostgREST access. Both layers implement the same owner/admin-only matrix and must be kept in sync.

MFPS-related migrations (apply in order where not already deployed):

Migration

Purpose

20260521025258_add_folder_permissions.sql

Initial table + RLS

20260525071402_fix_folder_permissions_migration.sql

timestamptz, NOT NULL level, check constraint, folder_permissions_folder_exists, cleanup triggers, per-level RLS, updated_at trigger

20260701_rpc_create_project_folder.sql, 20260701_rpc_project_folders.sql, 20260701_rpc_adventure_folders.sql, 20260702_fix_quest_folder_rls.sql

Folder CRUD RPCs and folder RLS fixes (pre-MFPS-core)

20260731_fix_folder_permissions_delete_rls.sql

DELETE hardened to owner/admin; owner-row protection

20260819_add_template_source_to_quests_adventures.sql

template_source_id attribution columns (Phase 2)

20260819_add_missing_adventures_columns.sql

learning_objectives, background_img_url, background_audio_url on adventures

20260821_add_folder_permissions_unique.sql

Dedup + UNIQUE (folder_id, user_id)

20260821_harden_folder_permissions_write_rls.sql

INSERT/UPDATE hardened to owner/admin-only; owner-row immutability

20260821_add_get_folder_ancestors_fn.sql

Recursive-CTE ancestor RPC + grants

20260822_fix_get_folder_ancestors_fn.sql

ORDER BY depth enforcement + grants (environments where the first version was already applied)

Permission Model

Role definitions:

Level

Meaning

owner

The folder creator (auto-seeded owner row) or an explicit owner grant. The creator of the root folder is the root tree owner — the absolute owner of the entire tree.

admin

Trusted manager: may rename/manage the folder and manage permissions (but cannot modify other admins or the owner, and cannot delete the folder itself unless the admin authority is inherited from an ancestor). Only the root tree owner can grant this role.

edit

Collaborator: may create subfolders, move their own content in, and manage (edit/move/archive/delete) only the content items they created inside the folder. Cannot manage permissions.

view

Read-only collaborator. Sees folder information and content but no management actions.

Hierarchy rules (canonical resolver: resolveRoleInHierarchy in lib/folder/folderAccess.ts):

  1. Strongest ancestor authority is inherited down. An OWNER or ADMIN role on any ancestor folder applies to every nested subfolder (owner beats admin). A collaborator creating a subfolder can never lock the tree owner out of it.

  2. A VIEW ancestor caps the subtree. A user demoted to Viewer on an ancestor is capped to Viewer for the whole subtree — including folders they created. The cap is applied after the full ancestor walk, so no earlier return can skip it.

  3. Creator-ownership exception. A folder's creator keeps OWNER status when the folder's direct parent granted them a management role (owner/admin/edit). This lets an Edit/Admin collaborator manage and delete the subfolder chain they build inside a shared tree, even under a distant VIEW ancestor.

  4. Explicit grants are authoritative on their folder. An explicit admin or edit row on a folder is respected even inside a viewer-capped subtree (deliberate per-folder promotion). A folder's own VIEW row is a direct demotion on that folder — unless an ancestor OWNER has absolute authority.

  5. Agency fallback. When the requesting user has no permission row at all (role === null) and the folder's creator belongs to the same agency, the effective role for content management resolves to owner. An explicit VIEW cap is never bypassed by agency membership. The fallback is intentionally NOT applied to folder move or Manage Permissions — those require the pure hierarchy role (see the split below).

Effective role vs. hierarchy role (PR #763): Folder list/detail payloads expose two server-resolved roles:

  • currentUserRole — effective role including the agency write-model fallback. Gates content-card actions (move/archive/delete) and, on the folder detail view, create-folder and bulk selection.

  • hierarchyRole — pure hierarchy role without the agency fallback. Gates folder MOVE and Manage Permissions, which the server deliberately does not grant to agency members. Child folder cards use the parent's pure hierarchy role so they never resolve to "owner" for actions the server denies.

Permission management matrix (API-enforced):

  • Only the folder owner or an ADMIN (hierarchy-aware) may add, change, or remove permissions. EDIT and VIEW collaborators are denied.

  • Nobody may change their own role ("You cannot change your own permission").

  • The root tree owner cannot be modified, demoted, or removed ("The folder owner cannot be modified").

  • An owner-level permission row cannot be modified by anyone except its holder ("The folder owner row cannot be modified").

  • Admins cannot modify other admins ("Admins cannot modify other admins"). Admins may only assign View or Edit.

  • The Admin role can only be assigned by the root tree owner ("Only the folder owner can assign the Admin role"). A literal subfolder creator (shown as "Creator") cannot assign it.

  • The permission list surfaces the root tree owner as Owner, relabels the literal folder creator as Creator, and merges hierarchy-inherited roles (with an "Inherit from Parent (<Role>)" override dropdown for the owner).

API Specification:

GET /api/folder/permissions/[folder_id]
Fetches the member list for a folder. Allowed for any collaborator with a permission row, a hierarchy-resolved owner/admin, or agency ownership fallback. Returns data: { members, requesterRole }, where each member row includes user_id, permission_level, email, name, and the flags tree_owner, creator, is_self, inherited, inheritedRole.

Status

Return

401

Unauthorized Access

403

User Not Permitted

500

Internal Server Error / Failed to validate folder access

200 OK

Member list plus requesterRole; tree owner surfaced as Owner, literal creator as Creator, inherited ancestor roles merged in

POST /api/folder/permissions/[folder_id]
Adds a permission for an existing account. Email notification is queued via after() using EmailService (renderShareFolderEmail → ShareFolderEmail).

URL Params: [folder_id]
Body: { email: string, permission_level: "view" | "edit" | "admin", folder_type: "project_folders" | "adventure_folders" | "quest_folders" }

Status

Return

401

Unauthorized Access / Invalid Permission Edit (folder not found)

400

Invalid permissions data

403

User Not Permitted (not owner/admin) or Only the folder owner can assign the Admin role

404

User Not Found

409

Permission already exists for this user in the folder

500

Failed to validate existing permission / Failed to add Permissions

200 OK

Permission added! (invitation email sent asynchronously)

PATCH /api/folder/permissions/[folder_id]
Changes a member's permission level.

URL Params: [folder_id]
Body: { permission_level: "view" | "edit" | "admin", user_id_permission: string }

Status

Return

401

Unauthorized Access

400

Invalid permissions data

403

User Not Permitted / You cannot change your own permission / The folder owner cannot be modified / The folder owner row cannot be modified / Admins cannot modify other admins / Only the folder owner can assign the Admin role

404

Permission row not found

500

Permission Not Updated

200 OK

Permission Updated

DELETE /api/folder/permissions/[folder_id]
Removes a member's local permission (they fall back to inherited parent-folder permissions, if any).

URL Params: [folder_id]
Body: { user_id_permission: string }

Status

Return

401

Unauthorized Access

400

Invalid permissions data

403

User Not Permitted / You cannot change your own permission / The folder owner cannot be modified / The folder owner row cannot be modified / Admins cannot modify other admins

404

Permission row not found

500

Permission Not Revoked

200 OK

Permission Revoked

Folder management APIs (per folder type — quest / project / adventure routes are structurally identical):

Endpoint

Purpose

Authorization

GET /api/folder/{type}-folders

List root folders or children of parentFolderId (treeView=true returns the full tree)

folderAccessFilter reachable set (own + shared + descendants + ancestor path)

POST /api/folder/{type}-folders

Create a folder (or assign content when contentId is present)

canCreateInsideFolder (owner/admin/edit, or agency fallback when role is null); title de-duplicated per parent (resolveFolderTitle); owner row seeded on creation (assignOwnerPermission in the quest route — folder rolled back on failure; project/adventure creation RPCs seed it atomically)

GET /api/folder/{type}-folders/[folderId]

Folder detail: meta (roles, counts, breadcrumbs) + content + child folders

folderAccessFilter; content exposure gated by hierarchy role; agency-only viewers see agency-authored content

PUT /api/folder/{type}-folders/[folderId]

Rename / edit / move a folder

canManageFolder; moves additionally require canCreateInsideFolder on the destination and canMoveFolder on the source; cannot move into itself or a descendant

DELETE /api/folder/{type}-folders/[folderId]

Permanently delete a folder

canDeleteFolder (owner, or ADMIN inherited from an ancestor — a folder's own admin row cannot delete it); child folders cascade; contained content moves to root (ON DELETE SET NULL)

POST /api/folder/{type}-folders/move-{content}

Move content item(s) into a folder

canMoveContentIntoFolder on the target (owner/admin/edit, or agency fallback when role is null)

POST /api/folder/{type}-folders/reorder

Reorder folders within a parent

Folder access filter + role gates

Shared-content APIs (Phase 2, PR #774):

Endpoint

Purpose

Authorization

GET /api/creator/get-quest?quest_id&preview=true

Preview a quest the user does not own

Folder view+ on the quest's or project folder, ownership/agency fallback, or membership in an accessible shared adventure. Unauthorized → clean 404

GET /api/creator/get-adventure?adventure_id&preview=true

Preview an adventure

Folder view+ on the adventure's or project folder, or ownership/agency fallback. Unauthorized → 404

GET /api/creator/adventure-sequence?adventure_id&preview=true

Fetch the adventure's member quest sequence for preview

Same policy as adventure preview

POST /api/creator/copy-content

"Use as Template": deep-copy a shared quest/adventure into the user's own library

View+ on the source (or creator/agency); destination (optional) requires canCreateInsideFolder. Denied sources return 404 (no existence leak)

Preview pages: /quests/{id}?preview=true&returnTo=... (learner player in read-only mode, no progress saved) and /adventures/{id}?preview=true. Editor routes render 404 for users without access. Copy-content body: { content_type: "quest" | "adventure", source_id, title?, destination?: { folder_id, folder_type } | null }; returns { id, content_type, title, destination }.

API Helpers

  • resolveUserFolderRole(folder_id, folder_creator_id, authContext) — direct role only: creator match → owner; otherwise the user's folder_permissions row.

  • resolveRoleInHierarchy(folder_id, folder_type, resolveNodeRole) — canonical ancestor walk (strongest owner/admin inheritance, VIEW cap applied after the walk, creator-ownership exception; see Permission Model).

  • resolveUserFolderRoleInHierarchy(folder_id, folder_type, authContext) — auth-context flavour of the canonical walk.

  • resolveFolderHierarchyRole(folder, folder_type, currentUserId) — user-id flavour used by list/detail payload enrichment.

  • resolveEffectiveFolderRole(folder, folder_type, authContext) — returns { currentUserRole, hierarchyRole } including the agency fallback split.

  • enrichFoldersWithSharing(folders, currentUserId, ancestorRole?, agencyUserIds?) / enrichFolderTreeWithSharing(folders, currentUserId) — inject creatorName, sharedCount (excludes only the owner row; admins count as collaborators), currentUserRole, and hierarchyRole into folder payloads.

  • folderAccessFilter(context, folderTable?) — read-model reachable-set filter: seeds from the user's permission rows and their own folders, expands descendants (depth 100, same as the write-model walk), includes the ancestor path for navigation, and is memoized per request via a WeakMap keyed by the request auth context.

  • canManageFolder(folder, folder_type, authContext) — owner/admin, or agency fallback when role is null.

  • canDeleteFolder(folder, folder_type, authContext) — owner; admin only when inherited from an ancestor; agency fallback when role is null.

  • canCreateInsideFolder(folder_id, folder_creator_id, authContext, folder_type) — owner/admin/edit, or agency fallback when role is null.

  • canMoveFolder(folder, folder_type, authContext, newParentFolderId, canPlaceInNewParent) — must be owner/admin; must manage the current parent or own the folder; detaching to root requires managing the current parent; destination placement must pass canCreateInsideFolder.

  • canManageItemsInFolders(folders, authContext) / canManageContentItem(item, content_type, authContext) — creator/agency OR folder owner/admin (including inherited) of any containing folder.

  • canMoveContentIntoFolder(folder_id, folder_creator_id, authContext, folder_type) — owner/admin/edit on the target, or agency fallback when role is null.

  • assignOwnerPermission(folder_id, owner_id) — upserts the owner row; returns { error } so callers can roll back.

  • getContentItemFolderRole / canPreviewContentItem / canAccessContentForPreview / canAccessQuestThroughAdventure / canCopyContentItem (lib/folder/sharedContentAccess.ts) — shared-content authorization (view+ policy; adventure-membership fallback for member quests).

  • copyQuestToUser(source_id, authContext, options, sharedState?) / copyAdventureForUser(source_id, authContext, options) (lib/content/templateCopy.ts) — the deep-copy engine used by "Use as Template".

  • Route-local helpers in the permissions API: resolveTreeOwner(folder_id, folder_type) (root owner + literal creator via the ancestor RPC), isPrimaryFolderOwner(...) (root tree owner only), collectInheritedRoles(...) (per-user inherited role with the same strongest/cap semantics as the resolver).

Core Logic and Workflow

Permission management flow:

  1. User signs in (Supabase Auth) as Creator or Agency Admin.

  2. User opens Content Library (creator) or Library (agency).

  3. User creates or selects a project, quest, or adventure folder. Creating a folder seeds the creator's owner permission row; if seeding fails the folder creation is rolled back.

  4. User opens the folder menu and clicks Permissions.

  5. FolderPermissionsModal fetches current permissions using GET; the list shows Owner / Creator / collaborative roles and merges hierarchy-inherited roles.

  6. User enters an existing WyzQuests account email and selects a permission level (View / Edit / Admin). Admin is only accepted from the root tree owner.

  7. POST validates payload, folder access (owner/ADMIN hierarchy gate), and target user.

  8. POST prevents duplicate permissions (unique folder_id + user_id, 409 on conflict).

  9. Permission row is inserted.

  10. Email notification is queued with after() using EmailService and renderShareFolderEmail.

  11. The owner or an admin can PATCH a role or DELETE a permission, subject to the management matrix. Removing a local override falls back to inherited parent permissions.

  12. Every subsequent permission check (folder detail/list, folder CRUD/move/delete, content move and bulk actions, permissions API) resolves the effective role through the same hierarchy walk, so reads, writes, and UI agree.

Shared content flow (Phase 2):

  1. A collaborator with view-or-higher access sees the folder in their library (badge "Shared with you").

  2. Clicking a shared quest/adventure card opens a read-only preview (learner player for quests, adventure preview page with its member quests). No progress is saved; exit returns "Back to the folder" or the library.

  3. The kebab menu on non-owned content offers Preview and Use as Template (own content is excluded).

  4. "Use as Template" opens the copy modal: editable title (≤ 100 chars, defaults to "<Title> (Copy)") and a destination picker limited to the user's own folders they can create in.

  5. POST /api/creator/copy-content creates a fully independent copy: fresh UUIDs, draft status, duplicated content cards and referenced hub activities/questions, canvas reference remap, best-effort storage-media copy with path remap, deep-copied adventure member quests with preserved sequences, and template_source_id attribution.

  6. On any failure, the engine rolls back every created row and copied storage object (reverse order).


INFRASTRUCTURE & OPERATIONS

Dependencies: This feature is primarily dependent on the folder structure of Quests, Adventures, and Projects. It is also connected with the Agency Admin workflow and member collaboration. Zod validation is used for data integrity. Supabase Auth provides the user identity; the server uses the service-role Supabase client, so route-level authorization is the enforcement point (RLS is defense-in-depth).

Monitoring and Alerting:

  • No major monitoring is needed because most functionality is CRUD of permissions to accounts being invited or revoked.

  • Most errors are displayed via toast notifications.

  • Monitor failed folder permission API calls (especially 403s — they usually indicate hierarchy/cap confusion or an undeployed RLS/migration set).

  • Monitor get_folder_ancestors RPC failures (missing function/grants break tree-owner resolution and inherited-role display).

  • Monitor email delivery failures for folder share notifications.

  • Monitor duplicate permission conflicts and user-not-found rates to improve UX.

  • Monitor template-copy failures (storage copy is best-effort and can leave source URLs in place).

Deployment Plan:

  • Migrate the tables of project_folders, adventure_folders, and quest_folders.

  • Ensure that CRUD APIs for all folder structures are implemented and work as intended.

  • Migrate folder_permissions, including: the unique (folder_id, user_id) index, the hardened INSERT/UPDATE/DELETE RLS policies, and the get_folder_ancestors RPC with its grants (both the base and follow-up migration).

  • Apply 20260819_add_template_source_to_quests_adventures.sql and 20260819_add_missing_adventures_columns.sql for the preview/template feature.

  • Ensure folder permission cleanup triggers and the updated_at trigger are deployed.

  • Ensure email service configuration is available.

  • Verify hierarchy behavior on a seeded tree (owner inherits into collaborator-created subfolders; viewer cap applies; explicit grants override).

  • Apply UI/UX testing to ensure endpoints are called with intended functions.


TESTING AND QUALITY ASSURANCE

Testing Strategy:

  • Sign in as a Creator or Agency Admin.

  • Navigate through the unified sidebar and choose Content Library for Creators or Library for Agency Admin.

  • Generate a folder for projects, quests, or adventures.

  • Click the kebab icon beside the folder name.

  • Click Permissions and input an email, then submit.

  • Do all CRUD functionalities to ensure API endpoints work accurately.

  • Verify GET returns the current permission list (including inherited roles and the Owner/Creator labels).

  • Verify POST adds view, edit, and admin permissions (admin only from the root tree owner).

  • Verify PATCH changes permission levels; verify DELETE revokes access (falling back to inherited permissions when applicable).

  • Verify duplicate permission returns conflict; verify nonexistent email returns user not found.

  • Verify view-only users cannot manage permissions, cannot change their own role, and see only Information in the folder menu.

  • Verify email notification is sent after adding a permission.

Hierarchy inheritance matrix (manual):

Scenario

Expected

Root owner opens a subfolder created by an external collaborator

Resolves as Owner; can rename, move, delete, and manage permissions

Edit/Admin collaborator creates a subfolder inside a shared folder

The collaborator keeps management over the subfolder chain they created

User demoted to Viewer on the root

Viewer for the whole subtree; loses delete/move on every nested folder, including folders they created; view-only content

Tree owner grants Admin on a subfolder inside a viewer-capped tree

Explicit Admin applies on that subfolder (authoritative grant)

Admin tries to modify another admin

403 "Admins cannot modify other admins"

Any user tries to change their own role

403 "You cannot change your own permission"

Non-root admin tries to assign Admin

403 "Only the folder owner can assign the Admin role"

Anyone tries to edit/remove the owner

403 "The folder owner cannot be modified" / "The folder owner row cannot be modified"

Agency member opens a colleague's folder (no permission row)

Content management allowed via agency fallback; folder Move and Manage Permissions remain hidden/denied

Agency member demoted to Viewer via an explicit row

VIEW cap is not bypassed by agency membership

Folder deleted with subfolders + content

Subfolders cascade-delete; contained quests/adventures move to root (not deleted)

Shared preview & template scenarios (from the Phase 2 test plan, docs/MFPS_SHARED_PREVIEW_TEMPLATE_TESTING.md):

  • View-level collaborator can preview a shared quest in learner mode; no progress is saved; exit returns to the folder/library; the editor route 404s.

  • Adventure preview lists member quests; member quest preview works with "Back to the folder" navigation.

  • "Use as Template" produces a draft copy owned by the collaborator with content cards/canvas intact and template_source_id set.

  • Adventure copies deep-copy every member quest with sequence order preserved; editing copies does not affect originals.

  • Non-shared users get 404 (no existence leak); archived content 404s; destinations the user cannot create in are hidden (direct API call → 403); owned items show no Preview/Use as Template actions.

Automated coverage (Jest):

File

Covers

tests/folder/folderRole.test.ts

Direct role resolution (getUserFolderRole)

tests/folder/folderHierarchyRole.test.ts

resolveFolderHierarchyRole and resolveEffectiveFolderRole (agency fallback, viewer cap, promotion)

tests/folder/folderHierarchyAccess.test.ts

Canonical walk + canMoveContentIntoFolder, canCreateInsideFolder, canDeleteFolder, canMoveFolder source-tree authorization

tests/folder/folderTreeEnrichment.test.ts

enrichFolderTreeWithSharing top-down role propagation

tests/folder/folderSharingEnrichment.test.ts

enrichFoldersWithSharing agency-fallback split

tests/api/project-folders.test.ts, tests/api/adventure-folders.test.ts

Folder API backend tests

Run with npx jest tests/folder and npx jest tests/api.

Known Limitations:

  • Pending invites for users who do not yet have WyzQuests accounts are not implemented; the invitee must already have an account.

  • Sharing is folder-level only. Individual quests/adventures cannot be shared directly through MFPS.

  • Agency fallback is intentionally split: agency members manage content in colleague folders but cannot move folders or manage permissions; child folder cards on colleague trees intentionally stay at their hierarchy-resolved role (tracked follow-up).

  • Adventures have no (creator_id, title) unique constraint, so a concurrent template copy could theoretically produce duplicate titles (cosmetic; quests retry on unique-conflict).

  • Folder deletion is permanent: child folders are removed and contained content is moved to the root of the library.

  • Media copy during "Use as Template" is best-effort; files that fail to copy keep pointing at the source URLs.


MAINTENANCE AND SUPPORT

Troubleshooting:

  • Re-migrate the folder_permissions table if permission rows, the unique index, or constraints are missing.

  • Ensure that all APIs related to folder permissions are implemented accurately.

  • Check if the target email belongs to an existing app_users record (invites require an existing account).

  • Check whether the requester has owner or admin rights — hierarchy-aware. Remember that EDIT/VIEW cannot manage permissions and that the agency fallback applies only when no permission row exists.

  • 403s for the tree owner: verify get_folder_ancestors is deployed with its grants; tree-owner resolution and inherited-role display depend on it.

  • Unexpected owner-less folders: check assignOwnerPermission results — folder creation rolls back on seeding failure; the unique index is required for the upsert.

  • Viewer unexpectedly has no actions: intended behavior (VIEW caps apply to the whole subtree and VIEW users see only Information in the folder menu).

  • Move Folder denied: canMoveFolder requires managing the current parent (or owning the folder); detaching to root always requires managing the current parent.

  • Check folder type matches project_folders, quest_folders, or adventure_folders.

  • Check email service if the account invite was sent successfully; if not, check Emailit/email provider limits.

  • Template copy issues: verify the source is not archived (404s by design), the destination folder allows creation for the requester, and treat storage copy failures as non-fatal (source URLs are kept).


DOCUMENT VERSION

1.0 - Documentation draft, feature is merged, 07/02/2026

1.2 - Documentation draft, feature is merged, added documentation information 07/03/2026

1.3 - Enhanced documentation of MFPS, 07/10/2026

2.0 - Core-logic overhaul documented: hierarchy inheritance (owner/admin inheritance, VIEW caps, creator-ownership exception), permission management matrix, RLS hardening (unique constraint, owner/admin-only writes, owner-row protection, get_folder_ancestors RPC), shared-content preview and Use as Template, agency library unification, Supabase Auth wording. Updated by Christian Denzon, 09/30/2026. PRs: #745, #763, #774, #782.


Was this article helpful?