Skip to content
ContractSpec
Start here

Package manual · integrations

·Content, growth and creator operations

integration.growth-persistence

Tenant-scoped transactional persistence for GrowthOS referral and affiliate state.

integrationsintegrationv2.1.5experimentalservernode
@lssm-tech/integration.growth-persistence
bun add @lssm-tech/integration.growth-persistence
Package source ↗Manifest ↗

Manifest declarations describe the current workspace; they do not verify registry publication or runtime execution.

Package guide

Server-only persistence for GrowthOS referral and affiliate state. It provides a serialized in-memory adapter for tests, a structural PgLite/Postgres adapter, and matching Drizzle table exports with tenant, entity, external conversion, link-code, reward-rule/beneficiary, webhook-event, and idempotency constraints.

Every mutation runs inside a transaction. Ledger entries and webhook receipts are immutable, payout items remain separately addressable, and duplicate conversions or rewards are rejected. Provider credentials and raw acquisition tokens are not persisted.

The optional ./marketing subpath provides SqlMarketingExecutionStore, SqlEditorialStore and SqlMediaGenerationStore using the same pinned-transaction SQL client. Each exposes an additive migrate() for host-owned migrations in the private marketing_execution schema. Revision updates append history atomically. Budget reservations serialize by brand scope, unknown dispatches retain liability, and definitive failures release their reservation. Media history stores provider job IDs and durable artifact references, never temporary download URLs.

SqlMarketingProposalStore persists goal-plan requests and immutable result history. It permits one generating-to-result transition per request, protects the original goal/brand binding, and isolates records by tenant, workspace and brand.

SqlMarketingConversionStore persists conversion revisions and append-only receipt history in the private marketing_execution schema. Call migrate() before mounting the conversion service. Accepted history is immutable, corrections are ordered, and CAS claims prevent concurrent workers from dispatching the same revision twice.

SqlMarketingObservationStore preserves immutable snapshots partitioned by campaign, platform, account and tenant/workspace/brand. Late polls cannot replace newer snapshots; conflicting same-timestamp writes fail. SqlMarketingObservationEvidenceStore retains sanitized provider responses for replay and rejects credential-bearing artifacts. Run both stores' migrate() methods before mounting the observation service.

Social scheduling adapters (SqlSocialScheduleStore, SqlSocialIntentStore, SqlSocialRecoveryLeases) implement library-owned contracts with SQL history, CAS, server-clock lease expiry and monotonically fenced recovery. Call their migrate() methods before starting workers. Canonical intent creation verifies the publication-key binding and rejects changed payloads; recovery claims require the matching live lease. Grant verification, policy evaluation, provider bindings and audit delivery remain host-owned requirements. The adapters never supply an allowing authority.

SqlXPublicationStore persists immutable reviewed thread plans, per-part CAS claims and append-only history. It verifies canonical root identity, scoped native request digests, predecessor IDs and confirmation author/media/reply facts. SqlSocialIntentStore supports fenced continuation of reconciled parent intents without changing their publication keys.

SqlXUploadStore persists immutable asset/chunk manifests and sequential native upload claims with transactional history. Migrate before starting upload workers. It rejects plan changes, altered native identity, reset uncertain steps and terminal-state rewrites. Source media bytes and credentials remain outside the store.

SqlLinkedInMediaJobStore persists scoped image/video plans, exact dispatch claims, part receipts and immutable history. Private upload capabilities are stored separately through LinkedInSecretSessionVault; the SQL payload contains only versioned references. Migrate before running the bounded native upload worker.

SqlPlanningApprovalStore persists private planning quotes, immutable issued receipts, revocation and revision history. Its consume method implements the canonical nonce store with atomic SQL uniqueness. Run migrate first and retain nonce rows through their expiry. Receipt records are private authority evidence, never analytics or public assets.

SqlMarketingOptimizationEvidenceStore records immutable assessed experiment documents, recomputes assessments before writes, and returns canonical SHA-256 artifact references. Use record for the marketing promotion wrapper's recordEvidence callback. Reads require explicit marketing scope and verify stored content against the artifact digest. Host authorization remains mandatory before storage access.

SqlMarketingOptimizationLifecycleStore implements the shared lifecycle store with an explicit marketing scope/program binding. Candidates are immutable; receipt appends serialize per candidate and validate canonical replay before committing. Duplicate receipts must match exactly; changed identities, digest chains and sequence gaps fail. It reconstructs current state from durable history. Effect adapters must separately honor the lifecycle idempotency key and expected state/sequence before external actions.

SqlContentRightsStore serializes rights grants and registered uses per tenant/workspace and appends immutable snapshots. Revocation and withdrawal queue creation share one transaction. Supply it to ContentRightsService; provider removal and confirmation evidence remain separate execution responsibilities.

Rights invariants are also enforced at the storage boundary: revoked grants cannot be reactivated, registered-use identities cannot change, confirmed withdrawals cannot be rewritten, and revocation cannot commit while existing uses lack withdrawal obligations. A failed invariant rolls back the entire scope transaction.

Terminal withdrawal jobs must commit with matching registered-use state and evidence. An unavailable automated attempt may later be resolved by separately evidenced manual confirmation; a confirmed job cannot leave its use pending.

SqlContentWithdrawalQueue supplies durable pending-use discovery and batch-result tracking. Migrate the rights store first, then the queue. Discovery selects pending uses within its authorized scope and processes never-attempted/least-recently-attempted items first, so unresolved removals do not starve later revocations. Terminal result records must agree with authoritative use state. Bind loadPending/recordResults to the installation withdrawal worker's callbacks.

SqlEditorialStore.listRecovery reads scoped publishing/unknown claims ordered by update time and ID. Reconciled terminal records disappear from discovery; publication is never resubmitted by this read.

SqlEditorialGitStore provides additive scoped Git dispatch persistence with revision CAS. Compiler artifacts cannot change after dispatch, and confirmed commit identity cannot be rewritten. Run its migration before enabling a Git publisher.

Run the updated SqlEditorialGitStore.migrate() before enabling preparation-failure handling. Additive claim-lock and failure tables serialize failure versus dispatch, retain immutable receipts and fence failed claims. Preserve one canonical writer while upgrading. Confirmed preparation failure permits the editorial article to be revised under a new publication claim.

SqlEditorialStore.listPage supports bounded keyset discovery with a C-collation ID index and parameterized filters. Run migrate to install the additive listing index. The runtime authorizes rows and emits summaries without Markdown.

SqlEditorialStore.listHistory reads existing append-only editorial_record_history revisions with exact scope, revision bounds and pagination. It does not modify or reconstruct prior revisions.

Editorial record v2 tables (TS-01-EDCORE)

SqlEditorialStore.migrate() installs EDITORIAL_V2_DDL: marketing_execution.editorial_record (current revision, schema_version = 2, with kind, locale and publish_at columns for filters and due discovery) and marketing_execution.editorial_record_history (one immutable row per revision). The store-registry step is named editorial-record. This is a fresh schema with no upgrade path: rows in the former v1 marketing_execution.editorial table are never read or migrated. Hosts that still hold v1 records must re-create them as v2 drafts through the editorial operations. listDueScopes is the interim due-scope double that the RLS due_editorial_scopes function is planned to replace.

Media generation persistence rejects removal or replacement of existing artifact references. Each imported output may add a running-state history revision before final success.

Media persistence enforces immutable expected output counts and requires succeeded jobs to contain exactly that many durable artifact references when the count is known.

TS-01-P-IG

./marketing/instagram-publication-store: scoped SqlInstagramPublicationStore (immutable plan, forward-only states, append-only history; registered as instagram-publications) (TS-01-P-IG).

Row-level security (TS-01-RLS)

Run migrateAllGrowthStores, then applyGrowthRowLevelSecurity (./rls) on the NOSUPERUSER owner client, then grantGrowthAppMembership (./rls-roles) for each product role. Runtime stores receive createScopedGrowthSqlClient(pool, scope, { role }) (./scoped-client) instead of the owner client: under FORCE RLS the owner reads nothing. Workers discover due work through discoverGrowthDueScopes or forEachGrowthDueScope (./due-scopes), which return scope tuples only. Tenant ids must not contain : because lease ids are <tenantId>:<intentId>. eraseMarketingScope (./erasure) erases one (tenant, workspace, brand) scope; a multi-brand workspace is erased by one call per brand.

Per-actor privacy (TS-01-COMMENTS-RLS): GrowthRlsScope.actorId sets the transaction-local growth.actor_id setting (empty when absent; the scoped client still refuses set_config/SET/RESET of growth.*). On the three audience comment tables applyGrowthRowLevelSecurity(owner, { actorMembershipPredicate }) adds a RESTRICTIVE growth_app_actor_private policy requiring actor_ref = growth.actor_id and the host membership predicate (tenant_id, workspace_id, brand_id, actor_ref). The predicate must be a boolean STABLE SECURITY DEFINER function with a pinned search_path, owned by a NOSUPERUSER NOBYPASSRLS role, with no PUBLIC EXECUTE and EXECUTE for growth_app; growth_app and the owner need USAGE on its schema. Otherwise the apply fails with GROWTH_RLS_ACTOR_MEMBERSHIP_UNSAFE and rolls back. Without the option the policy uses the always-false marketing_execution.growth_actor_membership_denied, so comments fail closed while other tables are unchanged. Pass the same option on every reapply. The NOLOGIN NOSUPERUSER NOBYPASSRLS role growth_steward (the owner joins it WITH INHERIT FALSE, SET TRUE) owns three SECURITY DEFINER functions on the comment tables only, executable by growth_app only and refusing an unset scope (GROWTH_STEWARD_SCOPE_UNSET): audience_comment_redaction_candidates (content-blanked rows), audience_comment_redact and audience_comment_erase (used by eraseMarketingScope).

Social schedules v2 and publisher reservations (TS-01-SOC)

SqlSocialScheduleStore stores schedule records at schema 2 (schema 1 rows are refused) with CAS on version, owner/peer/capacity reads and an append-only history. ./marketing/social-publisher-store adds SqlSocialPublisherStore (marketing_execution.social_publishers, RLS class full, registered as social-publishers before social-schedules), the durable publisher reservation behind SCHEDULE_PUBLISHER_RESERVED. Social lease ids must carry the <tenantId>: prefix; the store refuses others with SOCIAL_LEASE_TENANT_PREFIX_REQUIRED before the database does.

Results and learning stores (TS-01-RESULTS)

./marketing/result-store (SqlMarketingResultStore, registered as result-observations) and ./marketing/learning-store (SqlMarketingLearningStore, registered as learning-decisions) keep publication-bound results with append-only corrections and deletion tombstones, and learning decisions with their next-cycle actions, in fully scoped marketing_execution tables under FORCE RLS. Receipts hold hashes only. The existing observations table DDL is unchanged; the new observation fields are optional inside its JSONB payload.

Copy runs (TS-01-GEN)

./marketing/copy-run-store (SqlMarketingCopyRunStore, registered as copy-runs before brand-revisions) keeps copy_runs and copy_run_attempts in fully scoped marketing_execution tables under FORCE RLS, with fenced CAS writes for the copy-run service.

Audience comments (TS-01-COMMENTS)

./marketing/audience-comment-store (SqlMarketingAudienceCommentStore, registered as audience-comments) adds marketing_execution.audience_comment_grants, audience_comment_cursors and audience_comments (RLS class full, so applyGrowthRowLevelSecurity puts them under FORCE RLS), with one active grant per actor and object, one root per provider comment, at most one successor per version, immutable grant identity and a non-reverting redaction scrub.

Content analysis (CONTENT-01f)

SqlContentAnalysisStore (CONTENT-01f) is the durable content-analysis receipt repository: marketing_execution.content_analysis_receipts (unique per tenant/workspace id and per idempotency key, lease fence, reservation_ref metadata, spec-shaped payload) and marketing_execution.content_analysis_outbox (one row per terminal event, no payload copy). Claims are create-if-absent; writes after a claim are fence-conditional and a stale writer gets CONTENT_ANALYSIS_FENCE_LOST; a terminal receipt and its outbox row commit together. Every query is scoped by tenant and workspace and runs through a FORCE RLS scoped client. Migrate it on the owner client, then apply row-level security.

Relationships

THIS PACKAGEintegration.growth-persistence55 import paths

Arrows point from a package to its direct dependency. Counts are derived from captured workspace manifests.

11 declarations

Declared capabilities

Integration Growth Persistence

Tenant-scoped transactional persistence for GrowthOS referral and affiliate state.

Scripts

  • publish:pkgbun publish --tolerate-republish --ignore-scripts --verbose
  • publish:pkg:canarybun publish:pkg --tag canary
  • buildcontractspec-bun-build build
  • build:bundlecontractspec-bun-build transpile
  • build:typescontractspec-bun-build types
  • devcontractspec-bun-build dev
  • cleanrimraf dist .turbo
  • lint:checknode ../../../scripts/biome.cjs check .
  • lint:fixnode ../../../scripts/biome.cjs check --write .
  • testbun test
  • prebuildcontractspec-bun-build prebuild
  • typechecktsgo --noEmit