/vivreal-knowledge:vivreal-cms-api-knowledgefrom vivreal-knowledge
Use when working in VR_CMS_API, Vivreal's Content Management System backend (NEXT_PUBLIC_CMS_URL): its API Lambdas and workers, the /tenant/* routes, dbKey-via-`key` routing, the 8-step add-a-route checklist (every route declared in the base.yaml API route list, 403 if missed), webhook receivers, image derivatives, audit logging and versioning, sync adapters, go-live scheduling, and the arm64 layer gotcha (the full social sync is `vivreal-social-sync`). Triggers on: VR_CMS_API, CMS API, collection objects, collection groups, /tenant route, integration sync, content versioning, audit log, presignUpload, dbKey key param, Square webhook, Meta webhook, Shopify webhook, Instagram DM, instagram comments, image derivatives, media usage metering, tier quota gating, GroupFrozen, GroupPaused, content go-live, order fulfillment, dashboard insights, scheduled social sync, media export, approval gate. Source of truth: `VR_CMS_API` `CLAUDE.md` (and the docs it links) at `origin/stable`.
Trending skills
7-day visitors to each skill page
Ships in vivreal-knowledge. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Cross-repo flows, decisions and maps: the vivreal-hq dev docs under ${VIVREAL_REPOS}/vivreal-hq/docs/dev-docs/, starting at 03-use-cases/U18-creating-and-editing-content.md, 03-use-cases/U4-integrations.md, 03-use-cases/U23-inbound-webhooks.md; npm run docs:route -- "cms" from vivreal-hq names the rest. This skill and the repo's CLAUDE.md own the repo's internals.
Using this skill. It is loaded into the caller's own context; there is no expert agent to dispatch. Cite file:line at the deploy line's SHA for anything you act on, and re-derive any count or roster from source before you rely on it.
Source of truth: VR_CMS_API CLAUDE.md (and the docs it links) at origin/stable.
Last synced: 2026-10-28 against origin/stable at 37a7e71 (tag v2.17.2; read the tag; per-skill baseline in vivreal-skills scripts/skill-sources.json)
The CMS backend: collections, collection objects, integrations, media uploads, inbound platform webhooks, audit logging, content versioning, content go-live scheduling. Maps to NEXT_PUBLIC_CMS_URL. Express + serverless-express on Lambda (Node 22 on every function since 2026-10-02, CMS CLAUDE.md:41; arm64), JavaScript, MongoDB/Mongoose, Cognito JWT via API Gateway, SAM. CLAUDE.md at origin/stable (git show origin/stable:CLAUDE.md) is the first read; source wins wherever the two disagree.
getCollectionInfo (read-only + dashboard + audit + versions reads), createAndUpdateColObjects (object CRUD + revert + bulk), createAndUpdateColGroups (schema CRUD), handleMedia (S3 presign + derivatives), createAndUpdateIntegrations (integration CRUD + sync + payouts + inbound webhooks; TRI-mode: HTTP + inbound webhooks + SQS events for BOTH scheduled social posts AND content go-live, the dead publish-collection-object SQS handler was DELETED: it wrote published/publishedAt, absent from the strict collectionObjectSchema, so writes were silently dropped and no producers existed). FFmpeg layer on several Lambdas (ColGroups, HandleMedia, Integrations), removed from ColObjects. Memory and timeout values: read the fragment in cloudformation/, never a copy.
Beyond the five: MediaExportWorkerFunction (cloudformation/media-export-worker.yaml, own DLQ, a MEDIA_EXPORT_MAX_BYTES cap) behind POST /tenant/media-export and GET /tenant/media-export/status on handleMedia (src/handleMedia/api/index.js; grep the route, line numbers drift), PaymentsMoveWorkerFunction (cloudformation/payments-move-worker.yaml, invoke only, fixed name VR-CMS-API-PaymentsMoveWorker because VR_Secure_API invokes it by name; see "Changing payment provider" below), and the commerce snapshot function on its own stack (cloudformation-snapshots/template.yaml, deployed by snapshot-stack.yml). Adding a function takes FOUR lists, not one: the template CodeUri, the webpack entry, build-lambdas.js functions, and scripts/copy-externals.js FUNCTIONS. #224 missed the last two, so the v2.14.0 deploy failed at package and a bundle without the copy-externals entry throws MODULE_NOT_FOUND on cold start (vivreal-hq docs/projects/shipped-ledger.md, 2026-10-04 03:12Z); test/unit/build-lambdas-parity.test.js now cross-checks all four.
Per-Lambda layout: lambda.js → app.js → api/{index,handlers,controllers} → services/ → models/. Shared logic in src/shared/ via the @shared webpack alias (auditLog.js, contentVersion.js, generateImageDerivatives.js, createApp/createHandler, quota middleware).
dbKey via the key paramAll routes are under /tenant/. CMS reads the tenant DB key from req.query.key (Secure API uses dbKey, don't confuse; a request sending dbKey here gets a 400 that says so). handleTenantRoutes gates the value with isRoutablePlacement before any connect (Mongo creates a database on first write, so a junk key such as the string undefined would otherwise manufacture its own destination), then refuses with 403 a key that is not the requesting group's own placement (isKnownPlacement).
mainDb lookups: never { groupName }. active_ctx has only groupID + dbKey. Use { _id: ObjectId(groupID) } (shell form; in Node write new ObjectId(groupID), bson 6 throws without new). { key } takes the group's slug, never dbKey: dbKey is the tenant database name (pod_01, pod_02), no group's key equals it, so { key: dbKey } returns null (walk 5 B8: every list delete answered 500 after deleting). Webhook paths have no key param, they tenant-route by a provider identifier and then read the STORED placement with resolvePlacement(group), never group.key. Check whether that identifier is inside the signature before calling it verified: on the Shopify receiver it is a header, and the HMAC covers only the body.
scripts/validators.js (Joi) → 2. services/myFeature.js → 3. services/index.js → 4. api/controllers/myFeature.js (set req.resData = {status, response}) → 5. api/controllers/index.js → 6. api/index.js (router.{method} via handleTenantRoutes) → 7. cloudformation/base.yaml, ExpressApi.DefinitionBody.paths (the API's route list) → 8. tests (100% coverage gate).Step 7 is the most-missed, and it's a hard rule. Since CMS #266 (shipped in v2.19.2), every CMS route is declared in ONE place, the route list in cloudformation/base.yaml under ExpressApi.DefinitionBody.paths, and never as a SAM Type: Api event on a function. There is no catch-all {proxy+}. To add a route:
DefinitionBody.paths: path keys quoted ('/tenant/foo/{id}'), methods lower case (x-amazon-apigateway-any-method for ANY).security: MyCognitoAuthorizer (the normal case), NONE (deliberately public, the webhooks), or MyCustomerOrAdminCognitoAuthorizer (GET /tenant/auditLog only).x-amazon-apigateway-integration block from a sibling route; its uri names the owning function's live alias, ${<Function>.Alias}.<Function>ApiInvokePermission in its fragment, scoped to this API and its prod stage (${ExpressApi}/${ExpressApi.Stage}/*/*) and covering every route. A route on a NEW function copies that one permission from a sibling fragment.Type: Api event. SAM writes one AWS::Lambda::Permission per event (about 440 bytes each) and Lambda caps a function's resource policy at 20,480 bytes; CreateAndUpdateIntegrations reached 46 events and the v2.19.1 deploy rolled back on it (2026-10-30). Non-API events (SQS, Schedule) stay in the fragments.allRoutes.yaml, scripts/merge-template.js regenerates it on every build.A route missing from the list never reaches Express: API Gateway answers 403 (the gateway default, not your Cognito authorizer). Two tests hold the shape: test/unit/route-parity.test.js compares the Express route set against the DefinitionBody route set in both directions and checks each uri names the function whose router registers it (written after POST /tenant/syncProductFilterField was found 403ing in prod), and test/unit/lambda-permission-policy.test.js refuses any Type: Api event, requires exactly one API Gateway permission per function, checks every route is covered by it, and fails a function whose estimated policy passes 18,000 bytes.
Console "Test Invoke" is refused. API Gateway's console test invokes with the stage test-invoke-stage, which the prod-pinned permission does not cover, so a console test of any CMS route fails at the permission check while live traffic is fine. Test a route with a real request instead.
Invoke-only routes are the deliberate exception: POST /tenant/integrations/purgeAccount (src/createAndUpdateIntegrations/api/index.js, grep the route) is in no route list on purpose, and route-parity names it as an allowed exception, because lambda:InvokeFunction from VR_Main_API and VR_Secure_API IS its authorization. (Source: CMS CLAUDE.md "Adding a New Endpoint" and "Route rules (since 2026-10-30)", and the header comment of the route list in cloudformation/base.yaml. Cross-repo rule: vivreal-lambda + vivreal-auth-architecture.)
Prod serves stable, never main; promote order: CMS first, Secure second, portal last, each a dispatched promote (nothing ships without a dispatch). The model (cut, promote, backport as a patch, rollback needing a manual lambda_api.yml run) is in vivreal-infra:vivreal-lambda references/deploy.md; this repo's runbook is docs/RELEASE.md.
Read this before changing any of them: a verified signature proves ORIGIN and does not
bind a TENANT. The Shopify receiver is the clearest case. The HMAC is
base64(HMAC-SHA256(SHOPIFY_CLIENT_SECRET, rawBody)), and that secret is ONE app secret
shared by every merchant who has installed the app. The signature therefore covers the body
and only the body. The tenant is then selected from the x-shopify-shop-domain HEADER,
which is outside the signed material, by matching it against the shopDomain stored on an
active integration. So the check that passed authenticated the payload, not the choice of
customer, and a legitimately signed (body, signature) pair re-sent with a different shop
domain header still verifies.
The idempotency ledger does not close it either, because it is per tenant: the delivery id
is inserted into dynamicDb[dbKey].shopifyWebhookEvents, so the same id aimed at a second
tenant meets an empty ledger and is not a duplicate. When you audit a receiver here, state
explicitly which fields are inside the signature and which are not, and treat every field
outside it as caller-controlled, including the one that picks the customer.
Two related things the code already gets right, worth not undoing. The domain normaliser
strips only a trailing .myshopify.com rather than taking the first label, deliberately, so
a custom-domain header cannot be truncated into another tenant name. And the product
upsert and delete filters both pin groupID, because a shared tenant database holds many
groups and a provider product id is unique only per shop, so two groups can legitimately
hold the same id.
All on the integrations Lambda, Auth: NONE, signature-verified: POST /tenant/webhooks/square, GET+POST /tenant/webhooks/meta, POST /tenant/webhooks/stripe/{token}, POST /tenant/webhooks/shopify. Shared 5-step receiver pattern: rawBody (createApp verify hook) → verify-first + process-then-ack → tenant-route by a provider identifier with an active-account orphan guard, then resolvePlacement(group), then a per-tenant idempotency ledger (30d TTL: square_webhook_events, metaWebhookEvents twin, shopifyWebhookEvents). Ack ordering was INVERTED 2026-07: all three receivers (squareWebhook.js, stripeWebhook.js, metaWebhook.js) now process FIRST, then unconditional 200, on @codegenie/serverless-express the execution environment freezes the moment the response is written, so post-ack work never ran.
squareWebhook.js → RetrieveOrder → normalizeCompletionEvent.js (pure mapper) → oversell-safe stock decrement ($gte guard, inventory.oversell Sentry flag, never auto-refunds). Fulfillment: services/square/updateFulfillSquareOrder.js + PUT /tenant/updateFulfillSquareOrder. square_webhook_merchant_lookup index + backstop script. Stage-suffixed SQUARE_*/META_WEBHOOK_VERIFY_TOKEN env, deploy FAILS if unprovisioned.instagram_comments/instagram_conversations/instagram_messages tenant collections; webhook/send/sync writers). Messaging-window states incl. HUMAN_AGENT (7 days). 8 authenticated /tenant/instagram/* routes + 2 /tenant/tiktok/* routes.x-shopify-shop-domain against the bare stored shop subdomain, and the cents-vs-dollar-string price mismatch. Now: shopifyWebhookEvents tenant idempotency ledger with X-Shopify-Webhook-Id required (401 if absent), inserted BEFORE any state-affecting write with E11000 short-circuit; active: {$ne:false} lookup (site-created integrations carry no active key); mainDb groups index {integrations.type, integrations.shopDomain} + one-off createIndex backstop script; unconditional 200 once the signature verifies (repeated non-2xx makes Shopify auto-delete the subscription).processMediaFields → @shared/generateImageDerivatives.js using jimp (pure JS, arm64-safe): widths 320/640/1280, downscale-only, output JPEG q80 or PNG (alpha) at sibling keys {originalKey}.{width}.{jpg|png}, persisted as meta.derivatives + meta.derivativeFormat, consumed by VR_Client_API's signed srcset. Best-effort (failure never blocks the upload). A WebP/ffmpeg approach was tried and reverted (x86_64 layer + no jimp webp codec).
Two 2026-07 fixes: (1) clamped top rung, a source between ladder rungs (e.g. 600px) used to ship only derivatives:[320], so large layout boxes upscaled the 320w (blurry); now the source's full resolution is also written under the smallest ladder width above it. (2) Derivative metering, generateImageDerivatives returns total bytes PUT, and processMediaFields counts the 320/640/1280w derivatives into mediaUsage.totalSize (previously original-only, ran ~1.5x low) and stores the full footprint as the mediaFiles row size, symmetric with delete decrements.
Helper src/createAndUpdateIntegrations/services/scheduler/contentGoliveSchedule.js exports reconcileContentGolive / cancelContentGolive / contentGoliveScheduleName. Deterministic schedule name content-golive-{dbKey}-{objectID}; delete-then-maybe-create so one object never has two schedules; MIN_LEAD_MS 60s floor; never throws (the site's 24h TTL is the backstop), but callers must AWAIT it or the Lambda freezes the in-flight Scheduler call.
src/createAndUpdateColObjects/api/controllers/ require the Integrations-tree module: createCollectionObject, updateCollectionObject, decideApproval, revertCollectionObject, updatePublishDate, bulkUpdatePublishDate, bulkCreateCollectionObjects, bulkCreateCollectionObjectsJSON (all reconcile) and deleteCollectionObject (cancel). The import transitively loads createAndUpdateIntegrations/config, omitting FIFO_SQS_ARN/SCHEDULER_ROLE_ARN on ColObjects throws at cold start → 502.EventQueue.fifo (config.fifoSqsArn), MessageGroupId content-golive-{groupID}, actionAfterCompletion: DELETE, SchedulerExecutionRole.services/handleSqsEvent.js type 'content-golive' → contentGolive(): re-reads the live doc (the payload is frozen at CreateSchedule time), re-checks dueness vs DUE_SKEW_MS 60s, routes on the LIVE doc's groupID never the payload's, emits content.updated via @shared/emitWebhookEvent; skips return success so a deleted/not-due object can't churn the DLQ.decideApproval + revertCollectionObject also emit content.updated; updatePublishDate/bulkUpdatePublishDate emit webhooks AND reconcile go-live schedules; both bulk-import controllers bust site cache and schedule future-dated rows.scripts/backfill-content-golive-schedules.js (reconcile only fires on a mutation). Infra was already in place (scheduler:* + iam:PassRole + FIFO_SQS_ARN/SCHEDULER_ROLE_ARN env in cloudformation/create-update-col-objects.yaml).A product list carries collection_groups.commerce { state: selling | paused | moving, provider, moveId, movedAt } (strict sub-schema, no default: ABSENT MEANS SELLING). VR_Secure_API sets paused on "disconnect, keep my products"; when the owner connects the other provider it invokes VR-CMS-API-PaymentsMoveWorker with { groupID, dbKey, moveId, from, to } (services/payments/movePayments.js), which sets moving, moves each product idempotently (identity paths only, old ids under objectValue.previousProvider[from], never stock, sale fields or photos), re-types the list in place and sets selling. A failed product still moves with move.state: 'failed' and the "Needs fixing" badge; re-invoking the same moveId retries only those. A currency mismatch moves nothing. A list left moving is logged payments.move.stuck by sweepStuckMoves (the stuck-sweep SQS message); the DLQ, item failures and stuck moves are alarmed. Client checkout refuses 409 not_for_sale unless the list is selling.
GET /tenant/integrationSpecificInfo?view=waiting: Home's light read, { waitingCount, ordersTotal, ordersTruncated }, counted over the same newest-orders list Sales counts. Without view the payload is unchanged.getEvents projects archived on content entries, because the window matches by publishDate only; the MCP's list-events derives siteStatus from it.origin/stable 37a7e71)services/stripe/catalogState.js. Both Stripe receivers route product.updated, product.deleted and price.updated there only when previous_attributes.active is present (a delete always counts); it claims the event in the group's ledger, re-reads Stripe (a 404 means off), writes the item's sale state, and sends one off-sale email per item. Its test/fixtures/sellability-truth-table.json is byte-copied into VR_Client_API under a parity test.getValidShopifyToken is the one door to a Shopify token; no caller reads the stored token directly. Shopify prices are dollars end to end.src/shared/refreshOAuthToken.js writes through the native groups collection, because integrationAccountSchema declares neither refreshToken nor accessToken, so a Mongoose arrayFilter on them threw Could not find path and the "mark expired" write never landed.updateIntegrationObject) and an item edit (updateCollectionObject) ask the reference gate before deleteMediaFiles, so a photo reused elsewhere is not destroyed; reused photos get an Instagram fit (igFitBytes).GET /tenant/dashboardInsights here is the LIVE aggregate behind the portal's "Your week" sentences. The scanned SEO recommendations are a different producer: VR_Insights_Scan (one nightly Lambda, stack vr-insights-scan, deploys from main) writes deduplicated facts { rule, dedupeKey, params } to mainDb.site_recommendations, and writes no copy (wording lives in the portal's scannedCards.ts). VR_Secure_API reads that collection (src/getGroupInformation); this repo does not (git grep site_recommendations origin/stable -- src is empty here, against 55 files matching collectionObjects, 2026-10-28).
src/shared/uncountedSiteRoles.js UNCOUNTED_SITE_ROLES is bookings, subscribers, group-subscribers (VR_Secure_API's parked-domain sign-up store). A row in such a list is metered for bytes, but adding it spends no entry and deleting it gives none back: create, delete, bulk and JSON-bulk import all ask isUncountedRoleList (Outreach system lists are uncounted too, identified by system and name in @shared/outreachSystemList). This repo is the ENFORCER; VR_Secure_API's recountTenantUsage.js UNCOUNTED_SITE_ROLES is the HEALER, and vivreal-hq packages/fleet-ops/contract-drift (contract uncounted-list-roles, npm run check:contracts --workspace packages/fleet-ops) fails when the two sets differ or either lacks subscribers, bookings or Secure's group-subscribers role. Keep it a single Object.freeze([...]) of string literals so that parser can read it.collectionObject_<id>, items were metered under collection_<id>, and thousands of those rows were still live. @shared/usageTracking.js (updateDocOnGroup, legacyDocKeyFor) now handles them: a delete takes the current row or, when there is none, the legacy one, in ONE findOneAndDelete over both keys; an edit renames a legacy row to the current key in the same compare-and-set that moves its size. When both rows exist the delete takes only the current one and the duplicate is left for the reconciliation script; do not widen it. Seeding (Vivreal_EventHandler seedCollections) writes collectionObject_<id> since v7.1.importSubscribers.js requires an attestation (accepted: true, a source of at least 10 characters or ConsentSourceMissing, a statement), stores consentSource: 'import' with the import id, and hands VR_Main_API an INTENT (ids, never addresses) through @shared/requestSubscriberConfirmation.js onto the queue named by SUBSCRIBER_CONFIRM_QUEUE_URL (from SSM in cloudformation/create-update-col-objects.yaml). Main renders and sends. Site sign-ups are one step (VR_Client_API); this path is not.objectValue.vivrealExample: true (written by site-loader's seed plan; read by @shared/seededExample.js); an owner write that changes content, on any client and including revert, stores false, while an archive, a resave or a publish date keeps it. DELETE accepts onlyIfExample with the updatedAt the caller read (Joi requires the date only with the flag) and answers 409 EXAMPLE_CHANGED when the item changed, writing its version row only after a real delete (deleteCollectionObject.js). The portal's "Clear the examples" is the caller.archived semantics. In getCollectionObjects.js an explicit archived=false means $ne: true, so never-archived rows with no archived key count as not archived; a live read that sends no flag excludes archived items. An equality on false is the bug this replaced.getEvents takes excludePrivateLists (validator in getCollectionInfo/scripts/validators.js): mailing-list sign-ups, contact and quote requests and site-form enquiries are left out of the content arm, while bookings and booking requests stay. VR-MCP-Server's list-events always sends it._system survives an update. keepStoredSystemMeta (@shared/systemMeta.js) restores the stored objectValue._system on update, revert and integration-object update; creates strip a sent one. This is what makes the Outreach contact exclude mark durable.services/stripe/stripeProductFields.js), so Stripe-only extras are no longer stored or served.throwOnRequestTimeout: true, which bounds connect, upload and first byte, not a whole download.scripts/build-indexes.js --new-placement <pod> pre-builds the indexes of the next pod before its first tenant (refused when the pod already holds a document); the site_media_index and a collection_groups index were added in the same release. See vivreal-tenancy.handleTenantRoutes (older docs say handleHBRoutes). Controller sets req.resData.@shared/auditLog.js), fire-and-forget, lazy model registration, tenant collection audit_logs; each row carries expiresAt from the group's tier (resolveExpiresAt, the same rule VR_Secure_API and Vivreal_EventHandler stamp with), reaped by a TTL index. If the write fails the main op still succeeds.@shared/contentVersion.js), createVersion (auto-increment + tier-based pruning) hooked into create/update/delete; revert via PUT /tenant/collectionObject/revert. Versioning lives ONLY here, not Secure API. Callers now thread getTierQuotas(tier).maxVersionsPerObject into createVersion (package-authoritative).package.json, and the values from the package), quota reads are package-authoritative via getTierQuotas(tier): getDashboardInfo.js flipped all six quota fields to the package and deleted its hardcoded TIER_API_QUOTAS/TIER_CDN_QUOTAS tables; enforceCouponQuota.js resolves the coupon cap via getEffectiveLimit; checkGroupDataUsage.js adds a billing-frozen write guard (frozen === true || === 'true', authorizer context stringifies booleans) and exempts PUT from the entries cap; collection-group routes use checkGroupBillingState.js, the billing half without the entries and media caps (a collection is a schema and holds no bytes). A frozen or paused site stays READABLE: VR_Client_API's frozenPolicy.js serves the reads and refuses only what commits the owner. Audit retention is enforced twice now: getAuditLog.js clamps every read to the CURRENT tier's auditRetentionDays window (enterprise's -1 is unlimited, no clamp), and every row is written with its own expiresAt from the tier it was written under (resolveExpiresAt in @shared/auditLog.js), which the schema's TTL index reaps. Rows written before expiresAt existed carry none and are never reaped, so the read clamp is the only bound on them. The old "no clamp and no TTL" note is false. All three function customError.js maps gained GroupFrozen (403) and GroupPaused (403), shared/checkGroupDataUsage.js throws GroupPaused when pauseCollection.resumesAt is FUTURE-dated (not merely present, invoice.paid clears the fields on resume; a missed webhook must not lock a customer out forever; pauseCollection is declared in @hillbombcreations/schemas+). frozen handling is deliberately untouched (Client API's frozenCheck 402s delivery and would dark the site during a retention pause).services/sync/ + services/core/), provider adapter pattern (collectionName, fetchExternalItems, mapToDocument, getExternalId). bulkWrite upsert keyed on external ID. Providers: Stripe, Square, Shopify, Mailchimp + social (Facebook posts use JSON attached_media + Reels; FB Reel analytics now uses validated per-metric Graph calls; TikTok is full posting; Medium removed). X is no longer a postable platform (2026-09-28): SUPPORTED_SOCIAL_TYPES is ['linkedIn', 'instagram', 'facebook', 'tiktok'] in ONE file, services/social/supportedSocialTypes.js, and test/unit/social-supported-types-single-source.test.js fails on any second copy (the first removal missed the update path). The X sync adapter still exists; creating, editing and publishing are refused. The hourly scheduled sync, picture re-hosting, fetch health, the disconnect purge and their failure signatures are in vivreal-social-sync. IG publish race + DM/FB delete propagation fixed. Called by VR_Secure_API, not the portal directly.services/sync/{square,stripe,shopify}.js) store objectValue.price as STRING dollars ((cents/100).toFixed(2); Shopify's dollar string verbatim; default '0'), numbers made Variantable resolution treat the price as unresolvable (synced products rendered priceless, every cart add silently rejected).services/core/syncIntegrationData.js stamps $setOnInsert.publishDate at both bulkWrite sites (Client API's storefront query gates on publishDate <= now, synced products were invisible). Insert-only, skipped when the adapter maps its own. The same commit added groupID to the upsert filters (cross-tenant collision).services/stripe/updateStripeIntegrationObject.js, the client-supplied priceChange hint is GONE (stripped); reconcileStripePrices diffs incoming vs stored server-side and enforces shape invariants (scalar price ⇒ string price id; variant map ⇒ name→id map, the old unguarded Object.keys on scalar "25" minted $2.00/$5.00 prices from character indices); the no-op path retrieves the Stripe price and verifies unit_amount/active so drifted docs self-heal.src/shared/stripeAuthError.js, isStripeAuthError normalizes 401/api_key_expired/invalid_api_key to StripeKeyExpired 409 (a raw 401 made the portal's axios interceptor force /app/logout mid-edit); isStripeScopeError treats StripePermissionError/403 as a reconnect signal. Wired into errorHandler + handleTenantRoutes; the integrations Lambda's errorHandler wraps rather than re-exports and flags integrations.$.needsReconnect without flipping active.src/shared/stripeClient.js makes every Connect call with the platform key (rk_live_ / rk_test_ prefix) plus stripeAccount, so the key's own PERMISSIONS column (Vivreal's account) does not apply to those calls. Refunds sit under "Charges and Refunds"; there is no Refunds row. The live and test keys are edited separately and drift, so a test-mode walk proves nothing about the live key. A missing Connect permission comes back as a StripePermissionError, which isStripeScopeError turns into "reconnect": the owner is told to reconnect, not that Vivreal's key lacks a permission. Reading the columns is an owner browser read (Stripe Dashboard, Developers, API keys, the key's Edit page): the selected value shows only as a CSS class, not an aria attribute, and saving an edit asks for an SMS code only the owner types.resolvePlacement(group); the rules are in vivreal-tenancy). src/shared/deriveDbKey.js is deleted; a grep hit on the name is a comment recording the removal.POST /tenant/integrationObjects/batch (services/core/createIntegrationObjectsBatch.js): up to 4 cross-platform social posts (TikTok never batched, per validators.js). Idempotent via a lease (reserveIdempotencyLease/completeIdempotencyLease/releaseIdempotencyLease), batchKey namespaced server-side to ${groupID}:integrationObjectsBatch:${batchKey} (a placement such as pod_01 is ONE database shared by many groups). N-aware quota + frozen/paused pre-check; batch-scope media promotion so a shared preupload-* key isn't promoted-and-deleted by item 1. Always HTTP 200 with structured {ok:false, reason}.GET /tenant/announcements is RETIRED (H1064, 2026-09-23): route, controller, service, validator, config keys and CFN event all deleted (the portal half went 2026-08-10, zero requests in 30 days). The four authored rows in pod_01 stay on purpose. The rule it taught outlives it: a cross-tenant read takes its placement from the target group's own document via resolvePlacement, never from config (CMS CLAUDE.md:252).services/social/linkedInClient.js resolves the personal-post author URN three ways, stored context.platformUserId (from buildPlatformContext.js, zero extra calls) → OIDC /v2/userinfo → legacy /v2/me. As of 2026-07-28 w_organization_social + Community Management API are requested again, so /v2/me is the live path and userinfo is the dead one for post-revert tokens. Org-requested-but-broken-handle now THROWS before any network call instead of silently posting as the member.services/social/accountInsights.js linkedIn branch, GET /rest/memberFollowersCount?q=me + GET /rest/memberCreatorPostAnalytics × 5 metrics in one Promise.all with per-metric isolation; timeSeries/topPosts deliberately empty (no documented endpoints, not faked); scopeMissing is any-of-6; LI_HEADERS (LinkedIn-Version 202601) exported from linkedInClient.isGraphScopeError() classifies on error.code, NOT HTTP status, scope = 10, 102, 190 (all subcodes), 200 to 299; transient/rate-limit = 1, 2, 4, 17, 32, 613, 80000 to 80999. Meta delivers rate limits as HTTP 400, so the old status-only check flipped scopeMissing and rendered "Reconnect to enable analytics" for a self-clearing condition. LinkedIn call sites keep status-only isScopeError (LinkedIn bodies carry serviceErrorCode).markActivated awaited in createCollectionObject (2s time-box, idempotent leads updateMany in mainDb), feeds VR_Main_API's activation-nudge cohort.publishDate: null = draft. Scheduling is a per-post EventBridge Scheduler one-shot (scheduleExpression: at(...), actionAfterCompletion: DELETE) → SQS (EventQueue.fifo, now dead-lettered) → processSocialPost, not a standing FIFO pipe. The same queue now carries a parallel content-golive arm (see the content go-live section): publishDate is no longer a passive filter for content, a future-dated content item gets its own one-shot schedule that emits content.updated at go-live.sanitizeFilter is REMOVED, query-operator writes (e.g. the publish-claim CAS in processSocialPost) wrap operators in mongoose.trusted(). Don't reintroduce the global setting; it silently rewrote $nin/$lt filters.base member's publish or schedule on a social channel is held pending_review; only decideApproval can send it, through services/social/publishApprovedSocialPost.js, and processSocialPost refuses a pending post as defence in depth. Every caller (portal composer, batch create, TikTok dialog, VR-MCP-Server create-channel-post) funnels through createIntegrationObject, so the gate lives once (commit 6574577). getPendingApprovals surfaces held posts beside collection objects.Extension.Crash). OTEL collector caused this; removed March 2026. FFmpeg layer must also be arm64 (and jimp exists precisely to avoid layer-arch pain for images).collectionObjectSchema.js, siteSchema.js, the .index( calls): collectionObj.refID, publishDate, approvalStatus, sites.groupID and the compound bookings, subscriber and media-key indexes all exist. Two traps: sparse: true on a COMPOUND index indexes every row carrying ANY indexed key (so collectionObj_refID_subscriberEmail_1 is a no-op; use partialFilterExpression), and re-declaring a built index name with new options fails IndexKeySpecsConflict on every cold start, silently.getCollectionInfo/services/getCollectionObjects.js flipped ?? → || so '' falls back to createdAt; two sibling services still carry the unguarded pattern.Stage CFN param per branch ('' prod / '_DEV' dev) via --parameter-overrides.<secret-prefix>/cms-api (CLUSTER_URL, CLOUDFRONT_SIGNING_PRIVATE_KEY, SQUARE_WEBHOOK_SIGNATURE_KEY, META_WEBHOOK_VERIFY_TOKEN), <secret-prefix>/core (ENCRYPTION_KEY, PREVIEW_SECRET), <secret-prefix>/social-oauth (7 *_SECRET), and 13 SSM params, off the old hb-api-secrets. CDN_BASE_URL + MEDIA_BUCKET_PREFIX are hardcoded now.GET /tenant/dashboardInsights aggregate endpoint (2026-08), stock thresholds, signup dedup, cadence windows (this-week), plus a supporting integration_objects cadence index; shipped with several correctness fixes (stock $lte not $lt, signups tautology removed, object-shaped display-name guard, excluded-variant stock flag, bounded finds). Backs the portal's dash-insights "Your week" sentences.errorHandler is correct only in CONTROLLER position. It sets req.resData and always calls next(); from router-level middleware mounted before handleTenantRoutes, that next() runs the controller and the gate fails OPEN while still logging. Router-level middleware writes its own response.state was never stored until v2.9.9 declared it). A new persisted field needs a round-trip test through the REAL schema, with a control proving an undeclared field vanishes.preupload-* keys live one day (ExpirePreuploadOrphans on every tenant bucket). A reference left on one after a save is permanently dead (S3 403 behind the media 302). Verify media by diffing referenced keys against the bucket listing.Vivreal_Portal_Mobile/docs/projects/portal-frontend-testing-strategy/prod-bugs-found.md.Load vivreal-workflow:verification-discipline: a zero is only evidence once the same query returns a known hit. This repo's own idiom for it: a git grep "dynamicDb\[dbKey\]" misses most of the surface, and a query against a lowercased collection name returns zero rows against a database that has data.
cms-api expert agent, 2026-10-20)The expert agents are retired (2026-10-28), so the review checklist they used to carry lives
here. Query rules (tenant scoping, the mainDb _id
lookup, the publishDate and archived filters) live in vivreal-knowledge:vivreal-db, and
packaging and limits in vivreal-infra:vivreal-lambda; they are not repeated here.
test/unit/runtime-node22.test.js binds the claim to both templates); the five API functions carry WebSocket integration (WS_ENDPOINT + WS_TABLE).@hillbombcreations/schemas).insertMany with ordered: false for partial-failure tolerance.version atomically with $inc, prune via tail-deletion bounded by maxVersionsPerObject.connObj[dbKey] keeps its disconnected/error/close handlers for the life of the process; they used to delete THE SLOT, so a dead connection's teardown removed the entry a live request had just been given (TypeError: Cannot read properties of undefined on dynamicDb[dbKey].<model>; the null form came from createMainDb). All handlers are identity-guarded now (if (connObj[dbKey] === entry) in createTenantDb.js). Signature if it returns: the first request after an idle gap past maxIdleTimeMS, reconnect-length duration, an immediate successful retry. Do not go looking at the data.handleTenantRoutes.js keeps the handle connect() returns, but only for its own idempotency ledger; the services still re-read the mutable dynamicDb[...] map after more awaits, which a superseded teardown can empty. Count it with every spelling (git grep -o "dynamicDb\[[^]]*\]" -- src; dynamicDb[key] is most of it), never dynamicDb[dbKey] alone. The wrapper also refuses a key that is not the requesting group's own placement, so a caller cannot read another group's database by naming it.objectValue.order then _id, the same pair the public read uses. Items sharing a createdAt millisecond ordered "correctly" before only by an unspecified $setUnion tiebreak, so never copy createdAt ordering to either side.createMainDb takes collection as the mongoose MODEL name; with no collectionName, mongoose lowercases and pluralizes it, so a camelCase registration silently splits from a service that pins the name (domainOrders vs domainorders). Always pass collectionName; two collections both carrying a schema's full index set is the tell.test/unit/bulk-import-refuses-subscribers.test.js times out at 2000 ms on the FIRST full-suite run after npm ci and passes every run after (cold module load). Re-run, then run the file alone as the tiebreaker; do not raise the timeout.__v and a stale write gets a 409 instead of silent last-write-wins.GET /tenant/bookings (getCollectionInfo, siteRole bookings). Its fix is the general trap: Mongo limit(0) means NO limit, so a caller asking to skip a read gets the whole collection.bucketOf(group) (@shared/bucketOf): the stored group.bucket wins, else ${group.type}-${group.key}. Never assume a vivreal- prefix (some groups are collection-<key>); the vivreal- prefix on media URLs is the CloudFront path (buildMediaUrl.js), not the bucket.dynamicDb[dbKey]. dbKey is the tenant DATABASE name STORED on the group, read back by resolvePlacement(group) and never computed from a tier. A slugified per-group database is legacy drift, not the model, and at least one of those has no group pointing at it.collectionObject.approvalStatus enum (draft/pending_review/approved/rejected), gated by collectionGroup.approvalRequired.collectionGroup.siteRole is the stable discriminator for built-in site forms (subscribers, reviews, reservations, etc.), orthogonal to type and system.integration_accounts model).What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub hillbombcreations/vivreal-skills --plugin vivreal-knowledge27 skills in this plugin
/sentry-tracerUse when investigating what happened during a Vivreal user action across the stack, tracing an error end-to-end, validating a deploy, or doing tenant-scoped triage with Sentry. Teaches WHEN to trace cross-stack (frontend spans ↔ backend logs ↔ WebSocket events) and HOW (trace-ID propagation, the standard tag set, request_id fallback, service.* breadcrumbs). Triggers on: "what happened when I did X", "why did this error", trace this request, Sentry issue, deploy validation, "everything's broken for this group", crash, error timeline. For the full investigation agent with Sentry MCP tools wired in, dispatch the `sentry` agent / `/sentry-trace` (both in the `vivreal-sentry` plugin); this skill is the passively-loaded knowledge layer. Also covers the step from a Sentry error to the AWS and Atlas metric that confirms an infrastructure cause (502 with no backend event, Lambda timeout, Mongo connect-hang, throttling, OOM, stalled deploy)./vivreal-accounts-and-writesUse before filming, walking or capturing anything in the Vivreal portal or on vivreal.io, and before any write a capture or walk makes. Carries which login to use for which business (the demo account, the QA scratch owner, the owner session), the eight-step owner-approved write protocol (named approval, snapshot, write through the UI, fresh-process read-back, restore, manifest entry), the never-list (Post, Publish, Schedule, Connect and the rest), and the rules for stills that fill vivreal.io marketing slots (pair by what the slot says, no demo site has its own web address, mask comped plan figures). Shared by footage-recorder, tutorial-maker, help-page-producer, qa-walker and marketing-auditor. Triggers on: which login, demo account, QA scratch-2, test account, switch business, owner-approved write, write protocol, snapshot and restore, mutations, marketing still, screenshot swap, vivreal.io slot, walk harness, write guard, POST allow list, PRO badge./vivreal-admin-app-knowledgeUse when working on, walking, deploying or reasoning about the internal admin app (vivreal-hq packages/admin-app), the invite-only, sign-in-only staff hub that holds every staff surface since v7 (outreach CRM, sign-ups, monitoring, errors, tickets, flags, audit, usage, economics, deployed sites, team, staff push), covering where it lives, its own identity pool and session, how it calls the fleet with no active_ctx, the deploy by fast-forwarding deploy/admin-app, its two ops Lambdas, what each page reads, including the dark navy restyle and the Releases, Database, Marketing and Inbound pages. Source of truth: `vivreal-hq` `packages/admin-app/CLAUDE.md` (and the docs it links) at `origin/deploy/admin-app`./vivreal-agent-knowledgeUse when working on, writing about, or debugging Vivreal AI. The AI offering is connecting an AI agent through the Vivreal MCP server (VR-MCP-Server, plan flag mcpAccess, metered in mcpToolCalls), and nothing else: the in-app assistant is RETIRED (owner 2026-10-07, agentActions 0 on every tier; the global FAB, drawer and /agent page were deleted 2026-09-24) and only dead code survives in the portal (Studio AiRail, EditPlan) and VR_Secure_API's agent Lambda. Covers the copy rule ("AI agent", never assistant or a model name), the real gates, and the retired surface's archaeology. Triggers on: AI agent, MCP, connect an AI agent, AI assistant, AI assistant not showing, agentActions, aiActionsEnabled, aiSiteEditing, aiComponentGen, mcpAccess, mcpToolCalls, AiRail, useAgentAccess, EditPlan, proposeSiteEdits, agent/execute, agentProgress. Sources: VR-MCP-Server, Vivreal-Tier-Quotas src/tierQuotas.ts./vivreal-analytics-knowledgeUse when working on Vivreal's first-party analytics, VR_Analytics_API (the collect→store→rollup pipeline), the Templates SiteBeacon, or the per-site traffic dashboard (VR_Secure_API read route + portal AnalyticsPanel). Covers the CloudFront+WAF → Lambda Function URL ingest chain (X-Origin-Verify, bot filter, Joi, per-IP rate limit, daily-salt visitor hash), the analytics_rollup DynamoDB design, the daily rollup cron into mainDb.site_traffic_daily, the LIVE auto-deploy status (GitHub Actions → CloudFormation) plus the W4 CDN egress meter (runs unconditionally), and where increment 2 lives. Triggers on: analytics, site traffic, beacon, SiteBeacon, visitor stats, page views, unique visitors, analytics_rollup, site_traffic_daily, first-party analytics, per-site dashboard, collect.vivreal.io, visitor hash, rollup cron, CDN egress meter, VR_Analytics_API. Source of truth: `VR_Analytics_API` `CLAUDE.md` (and the docs it links) at `origin/main`./vivreal-blender-knowledgeUse when scripting or rendering in Blender for Vivreal, above all the Vivreal duck mascot in vivreal-hq/brand/mascot/model. Covers headless renders (blender -b -P script.py -- args, --factory-startup, --python-exit-code), bpy data versus ops, bmesh, depsgraph evaluated_get and new_from_object, mathutils transform gotchas, flat toon and NPR rendering in EEVEE (Emission plus the Standard view transform, exact sRGB hex, dither, filter size, transparent film, orthographic framing), outline methods compared (Freestyle, Grease Pencil Line Art, inverted hull, ID-pass edge inking), and the 4.2 to 5.2 API changes that break scripts (EEVEE engine id, blend_method, use_nodes, Grease Pencil v3). Triggers on: Blender, bpy, bmesh, headless render, background render, EEVEE, Workbench, Cycles, toon, cel, NPR, outline, inverted hull, Freestyle, Line Art, Grease Pencil, view transform, AgX, Filmic, mascot, the duck, duck.py, render.py, mascot-artist.