Open-source social media scheduler built for AI agents and the teams behind them. Create, schedule and publish posts to every network through MCP or the REST API, or write them yourself in a composer your team will love.
PHP ai-agentsblueskyfacebookinstagramlaravellinkedinmastodonmcpmcp-serveropen-sourcerest-apiself-hostedsocial-mediasocial-media-managementsocial-media-schedulerthreadstiktokvuejsxyoutube
Remove planning docs and a stale agent guide left in the repo (#524)
Paulo Castellanoc61a979bdcdd
diff --git a/.dockerignore b/.dockerignoreindex 945b48ff5..e2042cb97 100644--- a/.dockerignore+++ b/.dockerignore@@ -74,5 +74,4 @@ yarn-error.log.claude.mcp.jsonCLAUDE.md-GEMINI.mdboost.jsondiff --git a/ANALYTIC.md b/ANALYTIC.mddeleted file mode 100644index f887445ed..000000000--- a/ANALYTIC.md+++ /dev/null@@ -1,30 +0,0 @@-# Analytics por rede social--Este documento descreve as métricas que o TryPost consegue consultar atualmente por conta e por publicação.--> Este é um inventário do comportamento atual, anterior ao novo módulo. O desenho aprovado está em `docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.md` e o plano executável está em `docs/superpowers/plans/2026-09-23-workspace-analytics-backfill.md`. Na V1 nova, LinkedIn, Telegram, Discord e Google Business Profile ficam fora de todas as superfícies de analytics; LinkedIn fica planejado para V2.--| Rede / integração | Métricas por conta | Métricas por publicação | Observações |-| --- | --- | --- | --- |-| TikTok | Seguidores; seguindo; curtidas totais; quantidade de vídeos; visualizações, curtidas, comentários e compartilhamentos agregados dos vídeos recentes | Visualizações; curtidas; comentários; compartilhamentos | O agregado da conta considera os 20 vídeos mais recentes. O seletor de período não é aplicado a essa consulta. Posts privados podem não fornecer um ID público consultável. |-| Instagram (conexão direta ou via Facebook) | Alcance; seguidores; curtidas; comentários; compartilhamentos; salvamentos; visualizações; interações | **Feed:** alcance, curtidas, comentários, compartilhamentos, salvamentos e interações.<br>**Reel:** alcance, curtidas, comentários, compartilhamentos, salvamentos e visualizações.<br>**Story:** alcance, visualizações e respostas. | Disponível no painel por conta e no detalhe da publicação. |-| Threads | Visualizações; curtidas; respostas; reposts; citações | Visualizações; curtidas; respostas; reposts; citações | Disponível no painel por conta e no detalhe da publicação. |-| Facebook Page | Alcance da página; alcance dos posts; engajamento dos posts; novos seguidores; visualizações da página | **Feed:** impressões, alcance, curtidas e cliques.<br>**Story:** impressões, alcance, interações, reações, respostas e compartilhamentos.<br>**Vídeo/Reel:** reproduções, reações e interações. | As métricas disponíveis dependem do tipo e do identificador da publicação. |-| X | Impressões; curtidas; reposts; respostas; citações; bookmarks | Impressões; curtidas; reposts; respostas; citações; bookmarks | A consulta da conta soma as métricas dos posts encontrados no período, com limite de 100 dias e de cinco páginas de resultados. |-| LinkedIn — perfil pessoal | Não disponível no painel por conta | Curtidas; comentários | A API usada pela integração de perfil pessoal não fornece ao TryPost o conjunto completo de analytics disponível para páginas. |-| LinkedIn — página de empresa | Visualizações da página; novos seguidores orgânicos; novos seguidores pagos; impressões; cliques; curtidas; comentários; compartilhamentos | Impressões; cliques; curtidas; comentários; compartilhamentos | Métricas com valor zero podem ser omitidas no painel por conta. |-| Pinterest | Impressões; cliques no Pin; engajamentos; salvamentos; taxa média de clique | Impressões; salvamentos; cliques no Pin; cliques externos; visualizações de vídeo | A consulta por publicação usa uma janela fixa dos últimos 90 dias. |-| YouTube Shorts | Visualizações; minutos assistidos; duração média da visualização; percentual médio assistido; inscritos ganhos; inscritos perdidos; curtidas | Visualizações; minutos assistidos; duração média da visualização; curtidas; comentários; compartilhamentos | As métricas da publicação são consultadas desde a data de publicação até o dia atual. |-| Telegram | Número de inscritos do canal | Número de inscritos do canal; reações separadas por emoji | A Bot API não fornece visualizações das mensagens para bots. As reações são recebidas pelo webhook e armazenadas nos metadados da publicação. |-| Bluesky | Não disponível no painel por conta | Curtidas; reposts; citações; respostas | Atualmente existe apenas analytics por publicação. |-| Mastodon | Não disponível no painel por conta | Favoritos; boosts/reblogs; respostas | Atualmente existe apenas analytics por publicação. |-| Discord | Quantidade aproximada de membros do servidor, disponível no serviço interno, mas ainda não exibida no painel geral | Quantidade aproximada de membros; reações separadas por emoji; respostas na thread | O Discord não fornece impressões, alcance ou visualizações para mensagens de bot. |-| Google Business Profile | Impressões no Search em desktop; impressões no Search em mobile; impressões no Maps em desktop; impressões no Maps em mobile; cliques no site; cliques para ligar; solicitações de rota; conversas; palavras-chave de busca; quando aplicável, agendamentos, pedidos de comida e cliques no cardápio | Não disponível | Palavras-chave são agregadas mensalmente. Contagens de termos com baixo volume podem ser estimadas. Agendamentos e métricas de comida com valor zero são ocultados. |--## Disponibilidade atual--O painel geral de analytics permite selecionar contas de TikTok, Instagram, Threads, Facebook, X, LinkedIn Page, Pinterest, YouTube, Telegram e Google Business Profile.--LinkedIn pessoal, Bluesky e Mastodon possuem apenas métricas por publicação. O Discord também possui métricas implementadas por publicação e uma métrica de conta, mas ainda não aparece no painel geral.--As métricas por publicação só são consultadas quando a publicação está com status `published` e possui um identificador retornado pela plataforma. Esses resultados ficam em cache por cinco minutos. As métricas do painel por conta usam, em geral, o período selecionado e ficam em cache por uma hora em produção.diff --git a/GEMINI.md b/GEMINI.mddeleted file mode 100644index 9cbc4e4b8..000000000--- a/GEMINI.md+++ /dev/null@@ -1,513 +0,0 @@-<laravel-boost-guidelines>-=== foundation rules ===--# Laravel Boost Guidelines--The Laravel Boost guidelines are specifically curated by Laravel maintainers for this application. These guidelines should be followed closely to enhance the user's satisfaction building Laravel applications.--## Foundational Context-This application is a Laravel application and its main Laravel ecosystems package & versions are below. You are an expert with them all. Ensure you abide by these specific packages & versions.--- php - 8.4.17-- inertiajs/inertia-laravel (INERTIA) - v2-- laravel/cashier (CASHIER) - v16-- laravel/framework (LARAVEL) - v12-- laravel/horizon (HORIZON) - v5-- laravel/nightwatch (NIGHTWATCH) - v1-- laravel/prompts (PROMPTS) - v0-- laravel/reverb (REVERB) - v1-- laravel/socialite (SOCIALITE) - v5-- laravel/wayfinder (WAYFINDER) - v0-- laravel/mcp (MCP) - v0-- laravel/pint (PINT) - v1-- laravel/sail (SAIL) - v1-- pestphp/pest (PEST) - v5-- phpunit/phpunit (PHPUNIT) - v13-- @inertiajs/vue3 (INERTIA) - v2-- tailwindcss (TAILWINDCSS) - v4-- vue (VUE) - v3-- @laravel/vite-plugin-wayfinder (WAYFINDER) - v0-- eslint (ESLINT) - v9-- laravel-echo (ECHO) - v2-- prettier (PRETTIER) - v3--## Conventions-- You must follow all existing code conventions used in this application. When creating or editing a file, check sibling files for the correct structure, approach, and naming.-- Use descriptive names for variables and methods. For example, `isRegisteredForDiscounts`, not `discount()`.-- Check for existing components to reuse before writing a new one.--## Verification Scripts-- Do not create verification scripts or tinker when tests cover that functionality and prove it works. Unit and feature tests are more important.--## Application Structure & Architecture-- Stick to existing directory structure; don't create new base folders without approval.-- Do not change the application's dependencies without approval.--## Frontend Bundling-- If the user doesn't see a frontend change reflected in the UI, it could mean they need to run `npm run build`, `npm run dev`, or `composer run dev`. Ask them.--## Replies-- Be concise in your explanations - focus on what's important rather than explaining obvious details.--## Documentation Files-- You must only create documentation files if explicitly requested by the user.--=== boost rules ===--## Laravel Boost-- Laravel Boost is an MCP server that comes with powerful tools designed specifically for this application. Use them.--## Artisan-- Use the `list-artisan-commands` tool when you need to call an Artisan command to double-check the available parameters.--## URLs-- Whenever you share a project URL with the user, you should use the `get-absolute-url` tool to ensure you're using the correct scheme, domain/IP, and port.--## Tinker / Debugging-- You should use the `tinker` tool when you need to execute PHP to debug code or query Eloquent models directly.-- Use the `database-query` tool when you only need to read from the database.--## Reading Browser Logs With the `browser-logs` Tool-- You can read browser logs, errors, and exceptions using the `browser-logs` tool from Boost.-- Only recent browser logs will be useful - ignore old logs.--## Searching Documentation (Critically Important)-- Boost comes with a powerful `search-docs` tool you should use before any other approaches when dealing with Laravel or Laravel ecosystem packages. This tool automatically passes a list of installed packages and their versions to the remote Boost API, so it returns only version-specific documentation for the user's circumstance. You should pass an array of packages to filter on if you know you need docs for particular packages.-- The `search-docs` tool is perfect for all Laravel-related packages, including Laravel, Inertia, Livewire, Filament, Tailwind, Pest, Nova, Nightwatch, etc.-- You must use this tool to search for Laravel ecosystem documentation before falling back to other approaches.-- Search the documentation before making code changes to ensure we are taking the correct approach.-- Use multiple, broad, simple, topic-based queries to start. For example: `['rate limiting', 'routing rate limiting', 'routing']`.-- Do not add package names to queries; package information is already shared. For example, use `test resource table`, not `filament 4 test resource table`.--### Available Search Syntax-- You can and should pass multiple queries at once. The most relevant results will be returned first.--1. Simple Word Searches with auto-stemming - query=authentication - finds 'authenticate' and 'auth'.-2. Multiple Words (AND Logic) - query=rate limit - finds knowledge containing both "rate" AND "limit".-3. Quoted Phrases (Exact Position) - query="infinite scroll" - words must be adjacent and in that order.-4. Mixed Queries - query=middleware "rate limit" - "middleware" AND exact phrase "rate limit".-5. Multiple Queries - queries=["authentication", "middleware"] - ANY of these terms.--=== php rules ===--## PHP--- Always use curly braces for control structures, even if it has one line.--### Constructors-- Use PHP 8 constructor property promotion in `__construct()`.- - <code-snippet>public function __construct(public GitHub $github) { }</code-snippet>-- Do not allow empty `__construct()` methods with zero parameters unless the constructor is private.--### Type Declarations-- Always use explicit return type declarations for methods and functions.-- Use appropriate PHP type hints for method parameters.--<code-snippet name="Explicit Return Types and Method Params" lang="php">-protected function isAccessible(User $user, ?string $path = null): bool-{- ...-}-</code-snippet>--## Comments-- Prefer PHPDoc blocks over inline comments. Never use comments within the code itself unless there is something very complex going on.--## PHPDoc Blocks-- Add useful array shape type definitions for arrays when appropriate.--## Enums-- Typically, keys in an Enum should be TitleCase. For example: `FavoritePerson`, `BestLake`, `Monthly`.--=== herd rules ===--## Laravel Herd--- The application is served by Laravel Herd and will be available at: `https?://[kebab-case-project-dir].test`. Use the `get-absolute-url` tool to generate URLs for the user to ensure valid URLs.-- You must not run any commands to make the site available via HTTP(S). It is always available through Laravel Herd.--=== tests rules ===--## Test Enforcement--- Every change must be programmatically tested. Write a new test or update an existing test, then run the affected tests to make sure they pass.-- Run the minimum number of tests needed to ensure code quality and speed. Use `php artisan test --compact` with a specific filename or filter.--=== inertia-laravel/core rules ===--## Inertia--- Inertia.js components should be placed in the `resources/js/Pages` directory unless specified differently in the JS bundler (`vite.config.js`).-- Use `Inertia::render()` for server-side routing instead of traditional Blade views.-- Use the `search-docs` tool for accurate guidance on all things Inertia.--<code-snippet name="Inertia Render Example" lang="php">-// routes/web.php example-Route::get('/users', function () {- return Inertia::render('Users/Index', [- 'users' => User::all()- ]);-});-</code-snippet>--=== inertia-laravel/v2 rules ===--## Inertia v2--- Make use of all Inertia features from v1 and v2. Check the documentation before making any changes to ensure we are taking the correct approach.--### Inertia v2 New Features-- Deferred props.-- Infinite scrolling using merging props and `WhenVisible`.-- Lazy loading data on scroll.-- Polling.-- Prefetching.--### Deferred Props & Empty States-- When using deferred props on the frontend, you should add a nice empty state with pulsing/animated skeleton.--### Inertia Form General Guidance-- The recommended way to build forms when using Inertia is with the `<Form>` component - a useful example is below. Use the `search-docs` tool with a query of `form component` for guidance.-- Forms can also be built using the `useForm` helper for more programmatic control, or to follow existing conventions. Use the `search-docs` tool with a query of `useForm helper` for guidance.-- `resetOnError`, `resetOnSuccess`, and `setDefaultsOnSuccess` are available on the `<Form>` component. Use the `search-docs` tool with a query of `form component resetting` for guidance.--=== laravel/core rules ===--## Do Things the Laravel Way--- Use `php artisan make:` commands to create new files (i.e. migrations, controllers, models, etc.). You can list available Artisan commands using the `list-artisan-commands` tool.-- If you're creating a generic PHP class, use `php artisan make:class`.-- Pass `--no-interaction` to all Artisan commands to ensure they work without user input. You should also pass the correct `--options` to ensure correct behavior.--### Database-- Always use proper Eloquent relationship methods with return type hints. Prefer relationship methods over raw queries or manual joins.-- Use Eloquent models and relationships before suggesting raw database queries.-- Avoid `DB::`; prefer `Model::query()`. Generate code that leverages Laravel's ORM capabilities rather than bypassing them.-- Generate code that prevents N+1 query problems by using eager loading.-- Use Laravel's query builder for very complex database operations.--### Model Creation-- When creating new models, create useful factories and seeders for them too. Ask the user if they need any other things, using `list-artisan-commands` to check the available options to `php artisan make:model`.--### APIs & Eloquent Resources-- For APIs, default to using Eloquent API Resources and API versioning unless existing API routes do not, then you should follow existing application convention.--### Controllers & Validation-- Always create Form Request classes for validation rather than inline validation in controllers. Include both validation rules and custom error messages.-- Check sibling Form Requests to see if the application uses array or string based validation rules.--### Queues-- Use queued jobs for time-consuming operations with the `ShouldQueue` interface.--### Authentication & Authorization-- Use Laravel's built-in authentication and authorization features (gates, policies, Sanctum, etc.).--### URL Generation-- When generating links to other pages, prefer named routes and the `route()` function.--### Configuration-- Use environment variables only in configuration files - never use the `env()` function directly outside of config files. Always use `config('app.name')`, not `env('APP_NAME')`.--### Testing-- When creating models for tests, use the factories for the models. Check if the factory has custom states that can be used before manually setting up the model.-- Faker: Use methods such as `$this->faker->word()` or `fake()->randomDigit()`. Follow existing conventions whether to use `$this->faker` or `fake()`.-- When creating tests, make use of `php artisan make:test [options] {name}` to create a feature test, and pass `--unit` to create a unit test. Most tests should be feature tests.--### Vite Error-- If you receive an "Illuminate\Foundation\ViteException: Unable to locate file in Vite manifest" error, you can run `npm run build` or ask the user to run `npm run dev` or `composer run dev`.--=== laravel/v12 rules ===--## Laravel 12--- Use the `search-docs` tool to get version-specific documentation.-- Since Laravel 11, Laravel has a new streamlined file structure which this project uses.--### Laravel 12 Structure-- In Laravel 12, middleware are no longer registered in `app/Http/Kernel.php`.-- Middleware are configured declaratively in `bootstrap/app.php` using `Application::configure()->withMiddleware()`.-- `bootstrap/app.php` is the file to register middleware, exceptions, and routing files.-- `bootstrap/providers.php` contains application specific service providers.-- The `app\Console\Kernel.php` file no longer exists; use `bootstrap/app.php` or `routes/console.php` for console configuration.-- Console commands in `app/Console/Commands/` are automatically available and do not require manual registration.--### Database-- When modifying a column, the migration must include all of the attributes that were previously defined on the column. Otherwise, they will be dropped and lost.-- Laravel 12 allows limiting eagerly loaded records natively, without external packages: `$query->latest()->limit(10);`.--### Models-- Casts can and likely should be set in a `casts()` method on a model rather than the `$casts` property. Follow existing conventions from other models.--=== wayfinder/core rules ===--## Laravel Wayfinder--Wayfinder generates TypeScript functions and types for Laravel controllers and routes which you can import into your client-side code. It provides type safety and automatic synchronization between backend routes and frontend code.--### Development Guidelines-- Always use the `search-docs` tool to check Wayfinder correct usage before implementing any features.-- Always prefer named imports for tree-shaking (e.g., `import { show } from '@/actions/...'`).-- Avoid default controller imports (prevents tree-shaking).-- Run `php artisan wayfinder:generate` after route changes if Vite plugin isn't installed.--### Feature Overview-- Form Support: Use `.form()` with `--with-form` flag for HTML form attributes — `<form {...store.form()}>` → `action="/posts" method="post"`.-- HTTP Methods: Call `.get()`, `.post()`, `.patch()`, `.put()`, `.delete()` for specific methods — `show.head(1)` → `{ url: "/posts/1", method: "head" }`.-- Invokable Controllers: Import and invoke directly as functions. For example, `import StorePost from '@/actions/.../StorePostController'; StorePost()`.-- Named Routes: Import from `@/routes/` for non-controller routes. For example, `import { show } from '@/routes/post'; show(1)` for route name `post.show`.-- Parameter Binding: Detects route keys (e.g., `{post:slug}`) and accepts matching object properties — `show("my-post")` or `show({ slug: "my-post" })`.-- Query Merging: Use `mergeQuery` to merge with `window.location.search`, set values to `null` to remove — `show(1, { mergeQuery: { page: 2, sort: null } })`.-- Query Parameters: Pass `{ query: {...} }` in options to append params — `show(1, { query: { page: 1 } })` → `"/posts/1?page=1"`.-- Route Objects: Functions return `{ url, method }` shaped objects — `show(1)` → `{ url: "/posts/1", method: "get" }`.-- URL Extraction: Use `.url()` to get URL string — `show.url(1)` → `"/posts/1"`.--### Example Usage--<code-snippet name="Wayfinder Basic Usage" lang="typescript">- // Import controller methods (tree-shakable)...- import { show, store, update } from '@/actions/App/Http/Controllers/PostController'-- // Get route object with URL and method...- show(1) // { url: "/posts/1", method: "get" }-- // Get just the URL...- show.url(1) // "/posts/1"-- // Use specific HTTP methods...- show.get(1) // { url: "/posts/1", method: "get" }- show.head(1) // { url: "/posts/1", method: "head" }-- // Import named routes...- import { show as postShow } from '@/routes/post' // For route name 'post.show'- postShow(1) // { url: "/posts/1", method: "get" }-</code-snippet>--### Wayfinder + Inertia-If your application uses the `<Form>` component from Inertia, you can use Wayfinder to generate form action and method automatically.-<code-snippet name="Wayfinder Form Component (Vue)" lang="vue">--<Form v-bind="store.form()"><input name="title" /></Form>--</code-snippet>--=== pint/core rules ===--## Laravel Pint Code Formatter--- You must run `vendor/bin/pint --dirty` before finalizing changes to ensure your code matches the project's expected style.-- Do not run `vendor/bin/pint --test`, simply run `vendor/bin/pint` to fix any formatting issues.--=== pest/core rules ===--## Pest-### Testing-- If you need to verify a feature is working, write or update a Unit / Feature test.--### Pest Tests-- All tests must be written using Pest. Use `php artisan make:test --pest {name}`.-- You must not remove any tests or test files from the tests directory without approval. These are not temporary or helper files - these are core to the application.-- Tests should test all of the happy paths, failure paths, and weird paths.-- Tests live in the `tests/Feature` and `tests/Unit` directories.-- Pest tests look and behave like this:-<code-snippet name="Basic Pest Test Example" lang="php">-it('is true', function () {- expect(true)->toBeTrue();-});-</code-snippet>--### Running Tests-- Run the minimal number of tests using an appropriate filter before finalizing code edits.-- To run all tests: `php artisan test --compact`.-- To run all tests in a file: `php artisan test --compact tests/Feature/ExampleTest.php`.-- To filter on a particular test name: `php artisan test --compact --filter=testName` (recommended after making a change to a related file).-- When the tests relating to your changes are passing, ask the user if they would like to run the entire test suite to ensure everything is still passing.--### Pest Assertions-- When asserting status codes on a response, use the specific method like `assertForbidden` and `assertNotFound` instead of using `assertStatus(403)` or similar, e.g.:-<code-snippet name="Pest Example Asserting postJson Response" lang="php">-it('returns all', function () {- $response = $this->postJson('/api/docs', []);-- $response->assertSuccessful();-});-</code-snippet>--### Mocking-- Mocking can be very helpful when appropriate.-- When mocking, you can use the `Pest\Laravel\mock` Pest function, but always import it via `use function Pest\Laravel\mock;` before using it. Alternatively, you can use `$this->mock()` if existing tests do.-- You can also create partial mocks using the same import or self method.--### Datasets-- Use datasets in Pest to simplify tests that have a lot of duplicated data. This is often the case when testing validation rules, so consider this solution when writing tests for validation rules.--<code-snippet name="Pest Dataset Example" lang="php">-it('has emails', function (string $email) {- expect($email)->not->toBeEmpty();-})->with([- 'james' => '[email protected]',- 'taylor' => '[email protected]',-]);-</code-snippet>--=== pest/v5 rules ===--## Pest 5--- Pest 5 builds on Pest 4 with PHPUnit 13, Test Impact Analysis, and first-party plugins, while keeping browser testing, smoke testing, visual regression testing, and test sharding.-- Browser testing is incredibly powerful and useful for this project.-- Browser tests should live in `tests/Browser/`.-- Use the `search-docs` tool for detailed guidance on utilizing these features.--### Browser Testing-- You can use Laravel features like `Event::fake()`, `assertAuthenticated()`, and model factories within Pest 5 browser tests, as well as `RefreshDatabase` (when needed) to ensure a clean state for each test.-- Interact with the page (click, type, scroll, select, submit, drag-and-drop, touch gestures, etc.) when appropriate to complete the test.-- If requested, test on multiple browsers (Chrome, Firefox, Safari).-- If requested, test on different devices and viewports (like iPhone 14 Pro, tablets, or custom breakpoints).-- Switch color schemes (light/dark mode) when appropriate.-- Take screenshots or pause tests for debugging when appropriate.--### Example Tests--<code-snippet name="Pest Browser Test Example" lang="php">-it('may reset the password', function () {- Notification::fake();-- $this->actingAs(User::factory()->create());-- $page = visit('/sign-in'); // Visit on a real browser...-- $page->assertSee('Sign In')- ->assertNoJavascriptErrors() // or ->assertNoConsoleLogs()- ->click('Forgot Password?')- ->fill('email', '[email protected]')- ->click('Send Reset Link')- ->assertSee('We have emailed your password reset link!')-- Notification::assertSent(ResetPassword::class);-});-</code-snippet>--<code-snippet name="Pest Smoke Testing Example" lang="php">-$pages = visit(['/', '/about', '/contact']);--$pages->assertNoJavascriptErrors()->assertNoConsoleLogs();-</code-snippet>--=== inertia-vue/core rules ===--## Inertia + Vue--- Vue components must have a single root element.-- Use `router.visit()` or `<Link>` for navigation instead of traditional links.--<code-snippet name="Inertia Client Navigation" lang="vue">-- import { Link } from '@inertiajs/vue3'- <Link href="/">Home</Link>--</code-snippet>--=== inertia-vue/v2/forms rules ===--## Inertia v2 + Vue Forms--<code-snippet name="`<Form>` Component Example" lang="vue">--<Form- action="/users"- method="post"- #default="{- errors,- hasErrors,- processing,- progress,- wasSuccessful,- recentlySuccessful,- setError,- clearErrors,- resetAndClearErrors,- defaults,- isDirty,- reset,- submit,- }"->- <input type="text" name="name" />-- <div v-if="errors.name">- {{ errors.name }}- </div>-- <button type="submit" :disabled="processing">- {{ processing ? 'Creating...' : 'Create User' }}- </button>-- <div v-if="wasSuccessful">User created successfully!</div>-</Form>--</code-snippet>--=== tailwindcss/core rules ===--## Tailwind CSS--- Use Tailwind CSS classes to style HTML; check and use existing Tailwind conventions within the project before writing your own.-- Offer to extract repeated patterns into components that match the project's conventions (i.e. Blade, JSX, Vue, etc.).-- Think through class placement, order, priority, and defaults. Remove redundant classes, add classes to parent or child carefully to limit repetition, and group elements logically.-- You can use the `search-docs` tool to get exact examples from the official documentation when needed.--### Spacing-- When listing items, use gap utilities for spacing; don't use margins.--<code-snippet name="Valid Flex Gap Spacing Example" lang="html">- <div class="flex gap-8">- <div>Superior</div>- <div>Michigan</div>- <div>Erie</div>- </div>-</code-snippet>--### Dark Mode-- If existing pages and components support dark mode, new pages and components must support dark mode in a similar way, typically using `dark:`.--=== tailwindcss/v4 rules ===--## Tailwind CSS 4--- Always use Tailwind CSS v4; do not use the deprecated utilities.-- `corePlugins` is not supported in Tailwind v4.-- In Tailwind v4, configuration is CSS-first using the `@theme` directive — no separate `tailwind.config.js` file is needed.--<code-snippet name="Extending Theme in CSS" lang="css">-@theme {- --color-brand: oklch(0.72 0.11 178);-}-</code-snippet>--- In Tailwind v4, you import Tailwind using a regular CSS `@import` statement, not using the `@tailwind` directives used in v3:--<code-snippet name="Tailwind v4 Import Tailwind Diff" lang="diff">- - @tailwind base;- - @tailwind components;- - @tailwind utilities;- + @import "tailwindcss";-</code-snippet>--### Replaced Utilities-- Tailwind v4 removed deprecated utilities. Do not use the deprecated option; use the replacement.-- Opacity values are still numeric.--| Deprecated | Replacement |-|------------+--------------|-| bg-opacity-* | bg-black/* |-| text-opacity-* | text-black/* |-| border-opacity-* | border-black/* |-| divide-opacity-* | divide-black/* |-| ring-opacity-* | ring-black/* |-| placeholder-opacity-* | placeholder-black/* |-| flex-shrink-* | shrink-* |-| flex-grow-* | grow-* |-| overflow-ellipsis | text-ellipsis |-| decoration-slice | box-decoration-slice |-| decoration-clone | box-decoration-clone |-</laravel-boost-guidelines>diff --git a/docs/superpowers/plans/2026-09-23-workspace-analytics-backfill.md b/docs/superpowers/plans/2026-09-23-workspace-analytics-backfill.mddeleted file mode 100644index e07e06020..000000000--- a/docs/superpowers/plans/2026-09-23-workspace-analytics-backfill.md+++ /dev/null@@ -1,1395 +0,0 @@-# Workspace Analytics and Native Backfill Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Replace request-time social analytics with workspace-scoped, database-backed follower history, reconciled TryPost/external publication history, persisted post metrics, and the Summary, Followers, Posts, Top 5 Posts, Performance, and individual-publication views.--**Architecture:** Four tables separate daily account facts, publication identity, daily cumulative publication metrics, and a deliberately small operational checkpoint used only by publication backfill/discovery. Every provider call runs in an isolated queued job; page, API, and MCP reads use local database-backed Actions only. Provider adapters normalize platform responses into stable DTOs, while a hybrid scalar-plus-JSON snapshot keeps cross-network queries portable across PostgreSQL and MySQL and preserves content-specific metrics.--**Tech Stack:** PHP 8.5, Laravel 13.24, Horizon 5.47, PostgreSQL and MySQL, Inertia Vue 3.6, Vue 3.5, Tailwind CSS 4, Pest 5, Pest Browser 5.--**Spec:** `docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.md`--**Execution status (2026-09-23):** Tasks 1–15 have been implemented and-committed on the requested branch, with their focused tests recorded in the-execution ledger. Task 16's code, PostgreSQL/MySQL tests, browser tests, and a-single-workspace local Threads canary are complete. Its production provider-capability checks, production canary, and global rollout remain open; the-unchecked implementation steps below are the original TDD recipe, not a claim-that their code has not been written.--**Read-model refactor (2026-09-23):** The two classes originally planned under-`app/Queries/Analytics` were removed to match the project's existing Actions-structure. `BuildWorkspaceAnalyticsReport` orchestrates the publication and-follower report Actions; `GetAnalyticsBounds` serves the date picker;-`ReadPublicationAnalytics` serves individual post metrics. The controller passes-the bounds it already read into the report Action to avoid a duplicate query.--## Global Constraints--- Execute all tasks on one branch named `feat/workspace-analytics-backfill`.-- Analytics tenancy and aggregation are always scoped to the current workspace; never trust a request-provided social-account id as tenancy proof.-- Multiple accounts on the same network remain separate series and Performance rows through `social_account_id` while connected and `social_account_key` historically; reconnecting the same workspace + network + provider user id reuses its historical key.-- V1 includes TikTok, Instagram, Instagram through Facebook, Facebook Pages, Threads, X, Pinterest, YouTube, Bluesky, and Mastodon.-- V1 excludes LinkedIn profile, LinkedIn Page, Telegram, Discord, and Google Business Profile from every analytics read, collection job, summary, chart, and post-detail block.-- LinkedIn profile and Page analytics remain a separate V2 after Community Management API approval.-- `origin=trypost` means a matching TryPost destination proves ownership; every other discovered publication is `origin=external` and renders `Published on <Platform>`.-- Target 365 days of owned-publication history, but persist and expose actual coverage when a provider is shallower, partial, or permission-limited.-- Never fabricate follower history, historical post-metric snapshots, unsupported metrics, zero values after provider failure, or a native/manual origin the provider cannot prove.-- Followers retry at widely spaced same-day windows and carry the last value forward only after the day is exhausted; provider `Retry-After` wins when valid.-- An analytics-endpoint authentication or permission rejection is not proof that a connected account cannot publish; record the analytics failure without changing the account's global status. The independent connection verifier owns that health decision.-- `/analytics`, post detail, REST, and MCP make no social-provider calls and never use Redis as the analytics source of truth.-- Common aggregate metrics are nullable scalar columns; content-specific metrics use stable enum-backed JSON keys with value, unit, time basis, precision, availability, and provider identity.-- `analytics_sync_states` is not a job ledger: only publication backfill/discovery use it. Queue/Horizon owns attempts and delays; follower and publication snapshots prove successful collection.-- Use string columns plus PHP backed enums; do not use database-native enum types.-- Every query, migration, unique constraint, and test must work on PostgreSQL and MySQL.-- Do not add a charting dependency; use focused Vue/SVG/CSS components and existing UI primitives.-- Do not alter the unrelated `package-lock.json` change. Preserve the existing- metric inventory in `ANALYTIC.md`; its only planning change is the note that- distinguishes current behavior from this V1 design.-- Generate Laravel files with `php artisan make:* --no-interaction`, use Pest TDD, run `vendor/bin/pint --dirty --format agent` after PHP edits, and commit after each task.--## Review Focus--- Two Instagram accounts in one workspace must remain independent in totals, charts, publication counts, and sorting; Task 12 adds a cross-network-duplicate account test.-- Deleting a live social account must null the foreign key without erasing historical identity or presentation; Tasks 1 and 2 test `social_account_key` and snapshot retention.-- Provider null/missing metrics must stay unavailable while a measured numeric zero remains zero; Tasks 3 and 10 add explicit parser and writer tests.-- Concurrent TryPost sync and external discovery of the same provider post id must converge to one publication with `trypost` origin; Task 5 tests both arrival orders.-- A failed paginated backfill must resume from the last committed cursor and disclose partial/provider-limited coverage instead of restarting or claiming 365 days; Task 9 tests checkpoint, retry, and completion conditions.-- A duplicate or stale page job must never move a provider cursor backward; Task 9 uses a captured checkpoint version and row lock around advancement.-- Pre-rollout `post_platforms` whose social account was already deleted cannot be safely assigned by username; Task 9 skips and reports them instead of inventing historical identity.-------## File Structure--The implementation introduces these focused areas:--- `app/Enums/Analytics/*`: stable persisted states, metric keys, units, and provenance.-- `app/Models/Analytics*`: four persistence boundaries and their relationships.-- `app/Dto/Analytics/*`: provider-independent account, publication, page, and metric results.-- `app/Contracts/Analytics/*`: follower, history, and publication-metric collector contracts.-- `app/Services/Analytics/Collectors/*`: one provider adapter per concern; no authorization or database writes.-- `app/Actions/Analytics/*`: idempotent writers, publication reconciliation, and local analytics read/report Actions.-- `app/Jobs/Analytics/*`: one bounded piece of external or local synchronization per job.-- `app/Console/Commands/Analytics/*`: chunked dispatchers and rollout entry points; commands never call providers.-- `resources/js/components/analytics/workspace/*`: reusable dashboard cards and dependency-free SVG/CSS charts.-- `tests/Feature/Analytics/*`, `tests/Unit/Analytics/*`, and `tests/Browser/WorkspaceAnalyticsTest.php`: provider contracts, persistence, queue behavior, read paths, and UI coverage.--### Task 1: Create the four-table analytics schema and persisted enums--**Files:**-- Create: `database/migrations/2026_09_23_103300_create_analytics_account_daily_snapshots_table.php`-- Create: `database/migrations/2026_09_23_103301_create_analytics_publications_table.php`-- Create: `database/migrations/2026_09_23_103302_create_analytics_publication_daily_snapshots_table.php`-- Create: `database/migrations/2026_09_23_103303_create_analytics_sync_states_table.php`-- Create: `app/Enums/Analytics/ObservationProvenance.php`-- Create: `app/Enums/Analytics/MetricPrecision.php`-- Create: `app/Enums/Analytics/PublicationOrigin.php`-- Create: `app/Enums/Analytics/PublicationAvailability.php`-- Create: `app/Enums/Analytics/PublicationContentType.php`-- Create: `app/Enums/Analytics/ExposureKind.php`-- Create: `app/Enums/Analytics/MetricUnit.php`-- Create: `app/Enums/Analytics/MetricTimeBasis.php`-- Create: `app/Enums/Analytics/MetricAvailability.php`-- Create: `app/Enums/Analytics/MetricKey.php`-- Create: `app/Enums/Analytics/SyncCollector.php`-- Create: `app/Enums/Analytics/SyncStatus.php`-- Test: `tests/Feature/Analytics/AnalyticsSchemaTest.php`--**Interfaces:**-- Consumes: existing UUID workspace, social-account, and post-platform keys; `App\Enums\SocialAccount\Platform`.-- Produces: the four tables and enum values consumed by every later task.--- [ ] **Step 1: Generate the migrations and failing schema test**--Run:--```bash-php artisan make:migration create_analytics_account_daily_snapshots_table --no-interaction-php artisan make:migration create_analytics_publications_table --no-interaction-php artisan make:migration create_analytics_publication_daily_snapshots_table --no-interaction-php artisan make:migration create_analytics_sync_states_table --no-interaction-php artisan make:test --pest Analytics/AnalyticsSchemaTest --no-interaction-```--Add assertions that all four tables exist, that account and publication rows accept two distinct account UUIDs on the same platform, and that deleting `social_accounts` nulls live foreign keys while `social_account_key`, platform, username, and historical facts remain.--```php-expect(Schema::hasColumns('analytics_account_daily_snapshots', [- 'workspace_id', 'social_account_id', 'social_account_key', 'platform',- 'network', 'platform_user_id',- 'snapshot_date', 'followers_count', 'metrics', 'provenance', 'precision',- 'provider_observed_at', 'collected_at',-]))->toBeTrue();-```--- [ ] **Step 2: Run the schema test and verify it fails**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsSchemaTest.php`--Expected: FAIL because the migrations and enum classes are empty or incomplete.--- [ ] **Step 3: Define the exact persisted enum vocabulary**--Use backed string enums. The cases and values are:--```php-enum ObservationProvenance: string { case Actual = 'actual'; case CarriedForward = 'carried_forward'; }-enum MetricPrecision: string { case Exact = 'exact'; case Approximate = 'approximate'; case Estimated = 'estimated'; case Experimental = 'experimental'; }-enum PublicationOrigin: string { case TryPost = 'trypost'; case External = 'external'; }-enum PublicationAvailability: string { case Available = 'available'; case Deleted = 'deleted'; case Unavailable = 'unavailable'; }-enum ExposureKind: string { case Reach = 'reach'; case Impressions = 'impressions'; case Views = 'views'; }-enum MetricUnit: string { case Count = 'count'; case Milliseconds = 'milliseconds'; case Percent = 'percent'; }-enum MetricTimeBasis: string { case Lifetime = 'lifetime'; case Range = 'range'; case Rolling90Days = 'rolling_90_days'; case Snapshot = 'snapshot'; }-enum MetricAvailability: string { case Available = 'available'; case Unsupported = 'unsupported'; case Unavailable = 'unavailable'; case Delayed = 'delayed'; case PrivacyLimited = 'privacy_limited'; }-enum SyncCollector: string { case PublicationBackfill = 'publication_backfill'; case PublicationDiscovery = 'publication_discovery'; }-enum SyncStatus: string { case Pending = 'pending'; case Running = 'running'; case Complete = 'complete'; case Partial = 'partial'; case ProviderLimited = 'provider_limited'; case Failed = 'failed'; }-```--`PublicationContentType` must contain `Text`, `Image`, `Carousel`, `Video`, `Reel`, `Story`, `Short`, `Link`, `Poll`, and `Unknown`. `MetricKey` must contain every metric in the spec catalog, including normalized reactions/comments/shares/saves/views/impressions/reach, watch-time metrics, clicks, video quartiles, follows, profile activity, Story navigation, Pinterest audience metrics, and YouTube subscriber gains/losses.--- [ ] **Step 4: Implement portable migrations and indexes**--Use UUID primary keys, string-backed enum columns, and explicit foreign keys.--`analytics_account_daily_snapshots` has `workspace_id` with cascade delete;-nullable `social_account_id` with null-on-delete; non-null-`social_account_key`, `network`, `platform_user_id`, and `platform`; account-name/username/avatar snapshots; `snapshot_date`; nullable-`followers_count`; nullable future account `metrics` JSON; `provenance`,-`precision`, nullable `provider_observed_at`, `collected_at`, and timestamps. Its-unique key is `workspace_id, social_account_key, snapshot_date`.--`analytics_publications` has `workspace_id` with cascade delete; nullable live-`social_account_id` and unique nullable `post_platform_id`, both null-on-delete;-non-null `social_account_key`, `network`, `platform_user_id`, `platform`,-`provider_post_id`, `provider_published_at`, `origin`, `content_type`, and-`availability`; nullable provider content type, permalink, excerpt, preview-metadata, account presentation snapshots, first/last seen times,-provider-synced time, and provider metadata JSON. Its provider identity unique-key is `workspace_id, social_account_key, network, provider_post_id`.--`analytics_publication_daily_snapshots` has only its UUID, non-null parent-`analytics_publication_id` with cascade delete, `snapshot_date`, `collected_at`,-nullable `provider_observed_at`, nullable metric-catalog JSON, and nullable-portable projections: reactions, comments, shares, saves, views, impressions,-reach, engagement, exposure, exposure kind, total watch milliseconds, and-average watch milliseconds. It deliberately has no duplicate `workspace_id`.-Its unique key is `analytics_publication_id, snapshot_date`.--`analytics_sync_states` has a non-null `social_account_id` with cascade delete,-collector, status, nullable provider-specific `checkpoint` JSON,-`target_since`, `oldest_reached_at`, `high_watermark_at`, `last_success_at`,-sanitized `last_error_category`, and timestamps. It deliberately has no-workspace/account-history copies, attempt count, retry timestamp, or raw error-message. Its unique key is `social_account_id, collector`.--Only snapshots and publications store `network` plus `platform_user_id`, because-they are historical identity. Operational sync state is tied to the live row and-is recreated on reconnect.--Add these query indexes:--```php-$table->index(['workspace_id', 'snapshot_date']);-$table->index(['workspace_id', 'social_account_key', 'snapshot_date']);-$table->index(['workspace_id', 'provider_published_at']);-$table->index(['workspace_id', 'social_account_key', 'provider_published_at']);-$table->index(['analytics_publication_id', 'collected_at']);-$table->index(['collector', 'status']);-```--Historical `social_account_id` and `post_platform_id` use `nullOnDelete()`;-sync-state `social_account_id` and every `workspace_id` use-`cascadeOnDelete()`. Keep provider ids as bounded strings, metric counters and-canonical durations as nullable big integers, precise rates as nullable-decimals, timestamps below the MySQL 2038 ceiling, and JSON object assertions-order-independent. Test that a publication snapshot cannot carry a tenant id-different from its parent because no such child column exists.--- [ ] **Step 5: Run schema tests on the configured database**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsSchemaTest.php`--Expected: PASS.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Enums/Analytics database/migrations tests/Feature/Analytics/AnalyticsSchemaTest.php-git commit -m "feat: add workspace analytics schema"-```--### Task 2: Add analytics models, factories, DTOs, and idempotent writers--**Files:**-- Create: `app/Models/AnalyticsAccountDailySnapshot.php`-- Create: `app/Models/AnalyticsPublication.php`-- Create: `app/Models/AnalyticsPublicationDailySnapshot.php`-- Create: `app/Models/AnalyticsSyncState.php`-- Create: `database/factories/AnalyticsAccountDailySnapshotFactory.php`-- Create: `database/factories/AnalyticsPublicationFactory.php`-- Create: `database/factories/AnalyticsPublicationDailySnapshotFactory.php`-- Create: `database/factories/AnalyticsSyncStateFactory.php`-- Create: `app/Dto/Analytics/AccountDailyObservation.php`-- Create: `app/Dto/Analytics/MetricValue.php`-- Create: `app/Dto/Analytics/PublicationMetricObservation.php`-- Create: `app/Actions/Analytics/WriteAccountDailySnapshot.php`-- Create: `app/Actions/Analytics/WritePublicationDailySnapshot.php`-- Create: `app/Actions/Analytics/ResolveAnalyticsAccountKey.php`-- Test: `tests/Feature/Analytics/AnalyticsObservationWriterTest.php`--**Interfaces:**-- Consumes: Task 1 tables and enums.-- Produces: `ResolveAnalyticsAccountKey::for(SocialAccount $account): string`, `WriteAccountDailySnapshot::handle(SocialAccount $account, AccountDailyObservation $observation): AnalyticsAccountDailySnapshot`, and `WritePublicationDailySnapshot::handle(AnalyticsPublication $publication, PublicationMetricObservation $observation): AnalyticsPublicationDailySnapshot`.--- [ ] **Step 1: Generate models, factories, actions, and the failing writer test**--Run:--```bash-php artisan make:model AnalyticsAccountDailySnapshot --factory --no-interaction-php artisan make:model AnalyticsPublication --factory --no-interaction-php artisan make:model AnalyticsPublicationDailySnapshot --factory --no-interaction-php artisan make:model AnalyticsSyncState --factory --no-interaction-php artisan make:class Dto/Analytics/AccountDailyObservation --no-interaction-php artisan make:class Dto/Analytics/MetricValue --no-interaction-php artisan make:class Dto/Analytics/PublicationMetricObservation --no-interaction-php artisan make:class Actions/Analytics/ResolveAnalyticsAccountKey --no-interaction-php artisan make:class Actions/Analytics/WriteAccountDailySnapshot --no-interaction-php artisan make:class Actions/Analytics/WritePublicationDailySnapshot --no-interaction-php artisan make:test --pest Analytics/AnalyticsObservationWriterTest --no-interaction-```--The test must prove same-day writes update one row, next-day writes create history, null stays null, numeric zero stays zero, deleting the social account preserves snapshots through the immutable key, reconnecting the same workspace + network + `platform_user_id` reuses that key, and a different provider identity receives a new key even if the username is identical.--```php-$writer->handle($account, new AccountDailyObservation(- date: CarbonImmutable::parse('2026-09-23', 'UTC'),- followers: 0,- provenance: ObservationProvenance::Actual,- precision: MetricPrecision::Exact,- providerObservedAt: null,-));--expect(AnalyticsAccountDailySnapshot::count())->toBe(1)- ->and(AnalyticsAccountDailySnapshot::first()->followers_count)->toBe(0);-```--- [ ] **Step 2: Run the writer test and verify it fails**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsObservationWriterTest.php`--Expected: FAIL because the models and writers do not exist.--- [ ] **Step 3: Implement typed DTOs and model relationships**--`MetricValue` is the JSON boundary:--```php-final readonly class MetricValue-{- public function __construct(- public MetricKey $key,- public int|float|null $value,- public MetricUnit $unit,- public MetricTimeBasis $timeBasis,- public MetricPrecision $precision,- public MetricAvailability $availability,- public ?string $providerMetric = null,- public ?CarbonImmutable $periodStart = null,- public ?CarbonImmutable $periodEnd = null,- ) {}-}-```--Models use `HasUuids`, `HasFactory`, explicit `$fillable`, enum/date/array casts, and typed `belongsTo`/`hasMany` relationships. Add relationships from `Workspace`, `SocialAccount`, and `PostPlatform` only when a later query uses them.--- [ ] **Step 4: Implement transactional upsert writers**--Use the unique business keys rather than process-local locks.-`ResolveAnalyticsAccountKey` searches historical account snapshots and-publications by workspace + `Platform::network()` + `platform_user_id`, and-otherwise returns the current social-account UUID. Sync state is operational-and is never an identity source. Snapshot presentation fields come from the-account at write time.--The publication writer locks the same-day row and atomically merges the metric-catalog and scalar projections. A collector response may update the metrics it-actually observed, but a missing/unsupported/delayed value never blanks a prior-successful same-day value and never becomes zero. The test compares every-scalar projection against its canonical JSON entry so the two representations-cannot drift. A carried-forward follower snapshot retains the original-`provider_observed_at` while recording its new `collected_at`, so staleness is-not hidden.--```php-return AnalyticsAccountDailySnapshot::query()->updateOrCreate(- [- 'workspace_id' => $account->workspace_id,- 'social_account_key' => $this->accountKeys->for($account),- 'snapshot_date' => $observation->date->toDateString(),- ],- $this->attributes($account, $observation),-);-```--- [ ] **Step 5: Run writer tests**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsObservationWriterTest.php`--Expected: PASS.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Models app/Dto/Analytics app/Actions/Analytics database/factories tests/Feature/Analytics/AnalyticsObservationWriterTest.php-git commit -m "feat: persist analytics observations"-```--### Task 3: Normalize follower collection for every included platform--**Files:**-- Create: `app/Contracts/Analytics/FollowerCollector.php`-- Create: `app/Exceptions/Analytics/AnalyticsCollectionException.php`-- Create: `app/Services/Analytics/Collectors/Followers/FollowerCollectorFactory.php`-- Create: `app/Services/Analytics/Collectors/Followers/InstagramFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/FacebookFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/ThreadsFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/XFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/PinterestFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/YouTubeFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/TikTokFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/BlueskyFollowerCollector.php`-- Create: `app/Services/Analytics/Collectors/Followers/MastodonFollowerCollector.php`-- Test: `tests/Feature/Analytics/Collectors/FollowerCollectorsTest.php`--**Interfaces:**-- Consumes: `SocialAccount` and Task 2 `AccountDailyObservation`.-- Produces: `FollowerCollector::collect(SocialAccount $account, CarbonImmutable $date): AccountDailyObservation` and `FollowerCollectorFactory::for(Platform $platform): FollowerCollector`.--- [ ] **Step 1: Write the contract and failing provider dataset**--```php-interface FollowerCollector-{- public function collect(SocialAccount $account, CarbonImmutable $date): AccountDailyObservation;-}-```--Use one Pest dataset that fakes and verifies these read paths and canonical fields:--| Platform | Read path | Field |-| --- | --- | --- |-| Instagram variants | Graph user/profile or account insights supported by login type | `followers_count` |-| Facebook Page | Graph Page | `followers_count` |-| Threads | user insights | `followers_count` |-| X | `/2/users/{id}?user.fields=public_metrics` | `public_metrics.followers_count` |-| Pinterest | `/v5/user_account` | `follower_count` |-| YouTube | `channels.list(part=statistics)` | `subscriberCount`, approximate; null if hidden |-| TikTok | `/v2/user/info/?fields=follower_count` | `follower_count` |-| Bluesky | `app.bsky.actor.getProfile` | `followersCount` |-| Mastodon | `/api/v1/accounts/{id}` | `followers_count` |--The test must also assert excluded platforms make no request and that missing fields throw an unavailable collection result rather than returning zero.--- [ ] **Step 2: Run the collector test and verify it fails**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/FollowerCollectorsTest.php`--Expected: FAIL because the collector factory is missing.--- [ ] **Step 3: Implement failure classification and provider collectors**--`AnalyticsCollectionException` carries `transient`, `rate_limited`, `authentication`, `permission`, `unsupported`, or `malformed`, plus nullable provider retry time. Reuse existing token refresh and Graph error classification where available; never log response bodies containing tokens.--The factory has an explicit match for the ten included platform values and throws for LinkedIn, Telegram, Discord, and Google Business. Instagram direct and Facebook-login variants share the collector class but branch on the existing platform value.--- [ ] **Step 4: Run collector tests**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/FollowerCollectorsTest.php`--Expected: PASS with `Http::assertSent` endpoint and field verification for every platform.--- [ ] **Step 5: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Contracts/Analytics app/Exceptions/Analytics app/Services/Analytics/Collectors/Followers tests/Feature/Analytics/Collectors/FollowerCollectorsTest.php-git commit -m "feat: collect normalized follower snapshots"-```--### Task 4: Queue daily followers, same-day retries, and carry-forward--**Files:**-- Create: `app/Jobs/Analytics/CollectAccountDailySnapshot.php`-- Create: `app/Jobs/Analytics/FinalizeAccountDailySnapshots.php`-- Create: `app/Console/Commands/Analytics/DispatchAccountDailyAnalytics.php`-- Modify: `routes/console.php`-- Modify: `app/Observers/SocialAccountObserver.php`-- Test: `tests/Feature/Analytics/AccountDailyJobsTest.php`-- Test: `tests/Feature/Analytics/AnalyticsScheduleTest.php`-- Modify: `tests/Feature/Observers/SocialAccountObserverTest.php`--**Interfaces:**-- Consumes: Task 3 collectors and Task 2 account writer.-- Produces: one actual or carried-forward row per eligible account/day and immediate collection after connection.--- [ ] **Step 1: Generate jobs/command and write failing dispatch tests**--Test included/excluded platforms, inactive/disconnected accounts, duplicate-network accounts, immediate post-commit dispatch, `analytics` queue selection, and scheduler guards.--```php-Bus::assertDispatched(CollectAccountDailySnapshot::class,- fn ($job) => $job->socialAccountId === $instagram->id- && $job->observationDate === '2026-09-23');-Bus::assertNotDispatched(CollectAccountDailySnapshot::class,- fn ($job) => $job->socialAccountId === $linkedin->id);-```--- [ ] **Step 2: Run queue tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/AccountDailyJobsTest.php tests/Feature/Analytics/AnalyticsScheduleTest.php tests/Feature/Observers/SocialAccountObserverTest.php`--Expected: FAIL because jobs and schedules are absent.--- [ ] **Step 3: Implement bounded dispatch and job isolation**--The command uses `lazyById(200)` and dispatches IDs only. The job re-queries the social account, revalidates active/connected/included status, uses `WithoutOverlapping` keyed by account/date, and exits if an actual row already exists.--On a transient/rate-limit exception, release near the next `06:00`, `10:00`, `14:00`, `18:00`, or `22:00` UTC window, honoring a later provider time inside the same UTC day. Authentication/permission errors stop the analytics retry without writing a value or mutating the account's publishing status. Existing connection verification owns token-health transitions. Set job `retryUntil()` to the end of its observation day.--Set `tries = 6` for the initial `02:00` attempt plus the five delayed windows.-Because `release()` consumes an attempt, calculate the next window from the-observation date and current attempt rather than using a fast `backoff()` array.-If `Retry-After` points beyond the UTC day, stop retrying and let the finalizer-decide whether a historical value exists.--- [ ] **Step 4: Implement end-of-day fallback**--`FinalizeAccountDailySnapshots` iterates eligible accounts without an actual-row. It copies the last non-null follower count into the current date with-`CarriedForward`, preserves the source row's original `provider_observed_at`,-and records a new `collected_at`. It writes nothing when history is absent and-never overwrites an actual row, including when a late successful job races the-finalizer.--- [ ] **Step 5: Schedule and observer integration**--Schedule the dispatch command at `02:00` UTC and finalizer at `23:30` UTC,-after the last retry window, both with `withoutOverlapping()` and-`onOneServer()`. Dispatch initial collection `afterCommit()` when an included-account becomes connected; observers must never throw during delete/reconnect.--- [ ] **Step 6: Run queue/schedule tests**--Run: `php artisan test --compact tests/Feature/Analytics/AccountDailyJobsTest.php tests/Feature/Analytics/AnalyticsScheduleTest.php tests/Feature/Observers/SocialAccountObserverTest.php`--Expected: PASS.--- [ ] **Step 7: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Jobs/Analytics app/Console/Commands/Analytics routes/console.php app/Observers/SocialAccountObserver.php tests/Feature/Analytics tests/Feature/Observers/SocialAccountObserverTest.php-git commit -m "feat: schedule resilient follower analytics"-```--### Task 5: Reconcile TryPost and external publications into one catalog--**Files:**-- Create: `app/Dto/Analytics/DiscoveredPublication.php`-- Create: `app/Dto/Analytics/TryPostPublicationIdentity.php`-- Create: `app/Actions/Analytics/UpsertAnalyticsPublication.php`-- Create: `app/Actions/Analytics/SyncTryPostPublication.php`-- Create: `app/Jobs/Analytics/SyncTryPostPublication.php`-- Modify: `app/Observers/PostPlatformObserver.php`-- Create: `tests/Feature/Analytics/PublicationReconciliationTest.php`-- Modify: `tests/Feature/Observers/PostPlatformObserverTest.php`--**Interfaces:**-- Consumes: Task 2 `AnalyticsPublication` and existing published `PostPlatform`.-- Produces: `UpsertAnalyticsPublication::external(SocialAccount $account, DiscoveredPublication $publication): AnalyticsPublication` and `SyncTryPostPublication::handle(PostPlatform $postPlatform): AnalyticsPublication`.--- [ ] **Step 1: Write failing reconciliation tests for both arrival orders**--Test external-first/TryPost-second, TryPost-first/external-second, duplicate-provider pages, same provider id on two social accounts, workspace isolation,-and deletion of the social account after the job is dispatched but before it-runs.--```php-expect(AnalyticsPublication::query()->where('provider_post_id', 'remote-1')->count())->toBe(1)- ->and(AnalyticsPublication::first()->origin)->toBe(PublicationOrigin::TryPost)- ->and(AnalyticsPublication::first()->post_platform_id)->toBe($postPlatform->id);-```--- [ ] **Step 2: Run reconciliation tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationReconciliationTest.php tests/Feature/Observers/PostPlatformObserverTest.php`--Expected: FAIL because catalog actions/jobs are absent.--- [ ] **Step 3: Implement the discovery DTO and transactional upsert**--`DiscoveredPublication` carries provider id, publication time,-normalized/provider content type, permalink, excerpt, preview metadata, and-provider metadata. Resolve the historical account key first, then lock the-provider identity row using workspace + key + normalized network + provider-post id. `trypost` origin wins; provider publication time never becomes-discovery time; presentation snapshots update only with non-null values.--A lock cannot protect a row that does not exist yet. Treat the database unique-constraint as the final concurrency arbiter: attempt the insert, catch only the-unique-constraint collision, reload the winning row under lock, and merge. Test-that simultaneous discovery and TryPost sync converge without swallowing any-other database error.--`TryPostPublicationIdentity` is a token-free primitive snapshot captured while-the live account still exists: workspace id, social-account id, resolved-historical key, normalized network, provider account id, platform, and account-presentation. The queued local-catalog sync receives this DTO plus the-post-platform id. This closes the race where a user deletes the account after-dispatch but before the job runs; the job must not depend on reloading the live-account to establish historical identity.--- [ ] **Step 4: Dispatch catalog sync after a destination becomes published**--Extend `PostPlatformObserver` independently of the PostHog flag: whenever-status changes to `Published` and `platform_post_id` is present on an included-platform, resolve the identity snapshot and dispatch-`App\Jobs\Analytics\SyncTryPostPublication` with that snapshot and the-post-platform id using `afterCommit()`. The observer remains non-throwing: a-local sync dispatch failure is reported and repaired by the rollout/daily local-reconciliation command.--- [ ] **Step 5: Run reconciliation/observer tests**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationReconciliationTest.php tests/Feature/Observers/PostPlatformObserverTest.php`--Expected: PASS.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Dto/Analytics app/Actions/Analytics app/Jobs/Analytics/SyncTryPostPublication.php app/Observers/PostPlatformObserver.php tests/Feature/Analytics/PublicationReconciliationTest.php tests/Feature/Observers/PostPlatformObserverTest.php-git commit -m "feat: reconcile analytics publications"-```--### Task 6: Add owned-publication collector contracts and Meta/Threads adapters--**Files:**-- Create: `app/Contracts/Analytics/PublicationHistoryCollector.php`-- Create: `app/Dto/Analytics/PublicationPage.php`-- Create: `app/Services/Analytics/Collectors/Publications/PublicationHistoryCollectorFactory.php`-- Create: `app/Services/Analytics/Collectors/Publications/InstagramPublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/FacebookPublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/ThreadsPublicationCollector.php`-- Test: `tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php`--**Interfaces:**-- Consumes: Task 5 `DiscoveredPublication`.-- Produces: `PublicationHistoryCollector::page(SocialAccount $account, ?string $cursor, CarbonImmutable $cutoff): PublicationPage`.--- [ ] **Step 1: Define the page contract and failing cursor tests**--```php-final readonly class PublicationPage-{- /** @param list<DiscoveredPublication> $publications */- public function __construct(- public array $publications,- public ?string $nextCursor,- public bool $providerExhausted,- public bool $providerLimited = false,- ) {}-}-```--Tests must prove: Instagram paginates `/media` for feed/carousel/Reels but does not claim expired Stories; Facebook uses Page-owned published posts plus required video/Reel hydration without visitor posts; Threads paginates owned posts; timestamps stop at but do not cross the cutoff; preview failure does not drop the publication.--- [ ] **Step 2: Run Meta collector tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php`--Expected: FAIL because collectors are absent.--- [ ] **Step 3: Implement one-page Meta adapters**--Each call reads exactly one provider page and returns the provider cursor without dispatching or persisting. Share only a low-level Graph client/error parser with Repurpose; do not call `PollRepurposeSource`, create `RepurposeItem`, or download media. Parse Instagram direct and Facebook-login field differences explicitly.--- [ ] **Step 4: Run Meta collector tests**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php`--Expected: PASS.--- [ ] **Step 5: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Contracts/Analytics app/Dto/Analytics/PublicationPage.php app/Services/Analytics/Collectors/Publications tests/Feature/Analytics/Collectors/MetaPublicationCollectorsTest.php-git commit -m "feat: discover Meta analytics publications"-```--### Task 7: Add X, Pinterest, YouTube, and TikTok publication adapters--**Files:**-- Create: `app/Services/Analytics/Collectors/Publications/XPublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/PinterestPublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/YouTubePublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/TikTokPublicationCollector.php`-- Modify: `app/Services/Analytics/Collectors/Publications/PublicationHistoryCollectorFactory.php`-- Test: `tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php`--**Interfaces:**-- Consumes/produces: Task 6 history contract and page DTO.--- [ ] **Step 1: Write failing endpoint, pagination, and capability tests**--Cover X `users/:id/tweets` next tokens and paid-read fields; Pinterest `/v5/pins` bookmarks; YouTube uploads-playlist page tokens followed by batched `videos.list`; TikTok `video.list` cursor with maximum 20. TikTok without `video.list` must return provider-limited coverage, not fail account connection. YouTube imports all uploads as `Video` unless the provider gives an authoritative type; do not infer Shorts from duration or aspect ratio.--- [ ] **Step 2: Run collector tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php`--Expected: FAIL because collectors are absent.--- [ ] **Step 3: Implement bounded provider pages and ephemeral preview handling**--Never persist TikTok cover URLs as durable truth: store them as provider preview metadata with `expires_at`, and let UI fallback when expired. Pinterest records provider metric time-basis metadata. X requests only fields required by the catalog to control read cost.-X's official user-post timeline exposes at most the [3,200 most recent posts](https://docs.x.com/x-api/posts/timelines/introduction). The backfill checkpoint counts committed X publications across pages; if it exhausts at that cap before the 365-day target, mark coverage `provider_limited` with `x_timeline_3200`, not `complete`. Resume a failed cursor without resetting the count, but reset it when restarting from the first page. This adds no table and requires no extra paid read.--- [ ] **Step 4: Run collector tests**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php`--Expected: PASS.--- [ ] **Step 5: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Services/Analytics/Collectors/Publications tests/Feature/Analytics/Collectors/MediaPublicationCollectorsTest.php-git commit -m "feat: discover media network publications"-```--### Task 8: Add Bluesky and Mastodon publication adapters--**Files:**-- Create: `app/Services/Analytics/Collectors/Publications/BlueskyPublicationCollector.php`-- Create: `app/Services/Analytics/Collectors/Publications/MastodonPublicationCollector.php`-- Modify: `app/Services/Analytics/Collectors/Publications/PublicationHistoryCollectorFactory.php`-- Modify: `app/Http/Controllers/Auth/MastodonController.php`-- Test: `tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php`-- Modify: `tests/Feature/Auth/MastodonOAuthTest.php`--**Interfaces:**-- Consumes/produces: Task 6 history contract and page DTO.--- [ ] **Step 1: Write failing Bluesky repository and Mastodon scope tests**--Bluesky must page `com.atproto.repo.listRecords` for `app.bsky.feed.post` and hydrate batches for public counts instead of trusting `getAuthorFeed` completeness. Mastodon must page `/api/v1/accounts/{id}/statuses` with `max_id`; private/complete history requires `read:statuses`. Existing accounts without that scope remain public-history/partial rather than failing.--- [ ] **Step 2: Run tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php tests/Feature/Auth/MastodonOAuthTest.php`--Expected: FAIL because collectors and the scope change are absent.--- [ ] **Step 3: Implement adapters and request `read:statuses` for new Mastodon connections**--Keep instance URLs account-specific and validate them through the existing connection flow. Mark existing insufficient-scope imports `Partial` with a reconnect hint; never silently claim complete private history.--- [ ] **Step 4: Run tests**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php tests/Feature/Auth/MastodonOAuthTest.php`--Expected: PASS.--- [ ] **Step 5: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Services/Analytics/Collectors/Publications app/Http/Controllers/Auth/MastodonController.php tests/Feature/Analytics/Collectors/OpenPublicationCollectorsTest.php tests/Feature/Auth/MastodonOAuthTest.php-git commit -m "feat: discover open network publications"-```--### Task 9: Run resumable account backfill and daily publication discovery entirely through jobs--**Files:**-- Create: `app/Jobs/Analytics/BootstrapAccountAnalytics.php`-- Create: `app/Jobs/Analytics/BackfillAccountPublications.php`-- Create: `app/Jobs/Analytics/DiscoverAccountPublications.php`-- Create: `app/Jobs/Analytics/BackfillTryPostPublications.php`-- Create: `app/Console/Commands/Analytics/DispatchPublicationDiscovery.php`-- Create: `app/Console/Commands/Analytics/BackfillExistingAnalytics.php`-- Create: `app/Actions/Analytics/AdvanceAnalyticsSyncState.php`-- Modify: `app/Observers/SocialAccountObserver.php`-- Modify: `routes/console.php`-- Test: `tests/Feature/Analytics/PublicationBackfillJobsTest.php`-- Test: `tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php`--**Interfaces:**-- Consumes: Tasks 5–8 catalog action, collectors, and sync-state model.-- Produces: resumable 365-day initial import, local TryPost catalog seeding, and overlapping daily discovery.--- [ ] **Step 1: Write failing job-chain and resume tests**--Test one provider page per execution, separate backfill/discovery state rows,-cursor committed only after publication upserts, continuation dispatch after-commit, duplicate job idempotency, stale checkpoint version rejection, account-deletion cascading operational state only, reconnect creating fresh state while-reusing historical publication identity, failure resume, 365-day stop,-exhausted stop, provider-limited stop, overlap window, existing-account rollout-chunking, and per-account isolation. Assert daily discovery is suppressed while-backfill is pending/running and enabled after every terminal backfill state.--```php-Bus::assertDispatched(BackfillAccountPublications::class,- fn ($job) => $job->socialAccountId === $account->id);-expect($state->fresh()->checkpoint['cursor'])->toBe('provider-next-page')- ->and($state->fresh()->status)->toBe(SyncStatus::Running);-```--- [ ] **Step 2: Run backfill tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationBackfillJobsTest.php tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php`--Expected: FAIL because jobs and command are absent.--- [ ] **Step 3: Implement sync-state locking and bounded jobs**--Jobs carry account/state ids only and use a provider-specific queue limiter.-Inside a short transaction, lock the sync-state row, capture its checkpoint and-`updated_at` version, and mark it running. Fetch exactly one provider page-outside the transaction. In a second transaction, lock the state again and-upsert the returned publications idempotently. Advance `checkpoint`, coverage,-and high-water fields only if the captured checkpoint/version still matches;-otherwise leave progress untouched. A stale duplicate may safely reconcile-facts but can never move the cursor backward.--The sync table has no retry counters or timestamps: queue attempts, classified-delays, failed-job storage, and Horizon are authoritative. Persist only the-sanitized latest error category needed to explain coverage in the UI; never a-raw provider body.--Set `target_since` to the bootstrap time minus 365 days for initial history.-Daily discovery uses the high-water mark minus a fixed overlap window and the-same provider identity unique key. Persist `oldest_reached_at`,-`last_success_at`, and a truthful final status. A provider listing omission is-not proof of deletion: mark a publication deleted/unavailable only on an-explicit provider response for that publication.--When backfill first becomes terminal, initialize discovery from the newest-provider publication already stored for that account, falling back to the-current time only when the catalog is empty. If a provider invalidates an old-cursor, clear only that cursor and restart from `oldest_reached_at` plus an-overlap window; idempotent publication identity prevents duplicates and the-365-day target remains unchanged.--- [ ] **Step 4: Implement rollout and local TryPost backfill**--`analytics:backfill-existing` first uses `lazyById(100)` to dispatch-`BackfillTryPostPublications` for published included destinations with a live-social account, then dispatches `BootstrapAccountAnalytics` for active included-accounts. The command itself performs no provider calls and accepts an optional-workspace id for controlled rollout.--Pre-rollout published destinations whose `social_account_id` is already null-are counted and logged as `historical_identity_unrecoverable`; they are not-merged by username and no synthetic account key is invented. This limitation-applies only to facts orphaned before the analytics catalog exists. The command-is repeatable, and discovery later reconciles any reachable provider post by-its real account identity.--- [ ] **Step 5: Connect observer and schedule**--On included account creation/reconnection, dispatch `BootstrapAccountAnalytics` after commit. Schedule daily discovery dispatch with `withoutOverlapping()` and `onOneServer()`.--- [ ] **Step 6: Run backfill tests**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationBackfillJobsTest.php tests/Feature/Analytics/BackfillExistingAnalyticsCommandTest.php tests/Feature/Observers/SocialAccountObserverTest.php`--Expected: PASS.--- [ ] **Step 7: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Jobs/Analytics app/Console/Commands/Analytics app/Actions/Analytics app/Observers/SocialAccountObserver.php routes/console.php tests/Feature/Analytics tests/Feature/Observers/SocialAccountObserverTest.php-git commit -m "feat: backfill native analytics through jobs"-```--### Task 10: Normalize and persist post metrics for all included networks--**Files:**-- Create: `app/Contracts/Analytics/PublicationMetricsCollector.php`-- Create: `app/Services/Analytics/Collectors/Metrics/PublicationMetricsCollectorFactory.php`-- Create: one `*PublicationMetricsCollector.php` in that directory for Instagram, Facebook, Threads, X, Pinterest, YouTube, TikTok, Bluesky, and Mastodon-- Refactor: `app/Services/Social/InstagramAnalytics.php`-- Refactor: `app/Services/Social/FacebookAnalytics.php`-- Refactor: `app/Services/Social/ThreadsAnalytics.php`-- Refactor: `app/Services/Social/XAnalytics.php`-- Refactor: `app/Services/Social/PinterestAnalytics.php`-- Refactor: `app/Services/Social/YouTubeAnalytics.php`-- Refactor: `app/Services/Social/TikTokAnalytics.php`-- Refactor: `app/Services/Social/BlueskyAnalytics.php`-- Refactor: `app/Services/Social/MastodonAnalytics.php`-- Test: `tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php`--**Interfaces:**-- Consumes: `AnalyticsPublication` and Task 2 metric DTOs.-- Produces: `PublicationMetricsCollector::collect(AnalyticsPublication $publication, CarbonImmutable $date): PublicationMetricObservation`.--- [ ] **Step 1: Write failing normalized-metric datasets**--The dataset must pin the exact mapping from the spec:--- Instagram feed/Reel/Story common engagement, reach/views, Reel watch time/average/skip, and Story navigation; parse both `values[].value` and `total_value.value`.-- Facebook Page publication reactions, comments, shares, impressions/reach, and video metrics when supported.-- Threads views, likes, replies, reposts, and quotes.-- X impressions, likes, reposts, replies, quotes, bookmarks, and 30-day-only private/video fields when available.-- Pinterest image/video Pin metrics with lifetime/range/rolling basis retained and batch-ready IDs.-- YouTube views, engaged views, watch time, average duration/percentage, likes, comments, shares, subscriber gains/losses.-- TikTok views, likes, comments, shares and no fabricated retention.-- Bluesky likes, replies, reposts, quotes.-- Mastodon favourites, replies, reblogs.--For every provider, include measured zero, omitted, unsupported, malformed, rate-limited, and stale-value-preservation cases.--- [ ] **Step 2: Run metric collector tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php`--Expected: FAIL because normalized collectors are absent.--- [ ] **Step 3: Implement stable normalized observations**--```php-interface PublicationMetricsCollector-{- public function collect(- AnalyticsPublication $publication,- CarbonImmutable $date,- ): PublicationMetricObservation;-}-```--Split Meta metric families that cannot share one request. Store all durations-canonically as integer milliseconds and convert only at presentation time.-Compute normalized engagement numerator from supported interaction components-and preserve `exposure_count` plus `ExposureKind`; do not store a provider-engagement rate as if it were the normalized TryPost rate. The writer updates-the JSON catalog and every corresponding scalar projection in one transaction.--Refactor existing service methods to share low-level authenticated requests/parsers where safe, but do not return translated labels to persistence. Excluded providers remain callable by legacy code until Task 13 removes their analytics read paths, but the new factory never returns them.--- [ ] **Step 4: Run metric collector and existing provider tests**--Run:--```bash-php artisan test --compact tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php tests/Feature/Services/Social tests/Feature/XAnalyticsTest.php tests/Feature/YouTubeAnalyticsTest.php-```--Expected: PASS.--- [ ] **Step 5: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Contracts/Analytics app/Services/Analytics/Collectors/Metrics app/Services/Social tests/Feature/Analytics/Collectors/PublicationMetricsCollectorsTest.php tests/Feature/Services/Social-git commit -m "feat: normalize publication analytics metrics"-```--### Task 11: Queue metric refresh, baseline backfill, and Story lifecycle collection--**Files:**-- Create: `app/Jobs/Analytics/CollectPublicationMetrics.php`-- Create: `app/Console/Commands/Analytics/DispatchPublicationMetrics.php`-- Create: `app/Jobs/Analytics/ScheduleInstagramStoryMetrics.php`-- Modify: `app/Jobs/Analytics/BackfillAccountPublications.php`-- Modify: `app/Jobs/Analytics/DiscoverAccountPublications.php`-- Modify: `routes/console.php`-- Test: `tests/Feature/Analytics/PublicationMetricsJobsTest.php`--**Interfaces:**-- Consumes: Task 10 collector factory and Task 2 publication writer.-- Produces: latest persisted metrics with 20-day X, 30-day other-network, one-time old backfill baseline, and sub-day Story collection.--- [ ] **Step 1: Write failing eligibility and retry tests**--Test included/excluded platforms, usable provider ids, active access, X day 20/day 21, other day 30/day 31, final-day collection, old imported baseline exactly once, no perpetual old refresh, same-day idempotency, latest-value preservation on failure, batching eligibility, and Story immediate/pre-expiry runs.--- [ ] **Step 2: Run job tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationMetricsJobsTest.php`--Expected: FAIL because jobs are absent.--- [ ] **Step 3: Implement metric job and dispatcher**--The job re-queries publication and live account, skips stale/excluded rows,-collects, then writes one daily snapshot. Use the same classified same-day retry-policy as followers. Default to a bounded batch job per account/provider; use a-single publication for endpoints that do not batch and the documented provider-maximum for Pinterest, TikTok, and YouTube. Persist successful items before-retrying only failed items, so one bad id never discards a whole successful-batch.--- [ ] **Step 4: Implement import handoff and Story schedule**--New publications inside the refresh window dispatch normal collection. Older-backfill rows dispatch one baseline job only when that publication has no-snapshot; baseline completion is therefore proved by the fact table, not sync-metadata. Instagram Stories dispatch immediately, at configured within-lifetime-checkpoints, and once shortly before expiry; all writes converge on the daily-writer. A delayed insight must not be mistaken for unsupported, and Story jobs-stop after the provider availability window.--- [ ] **Step 5: Schedule daily metric dispatch and run tests**--Run: `php artisan test --compact tests/Feature/Analytics/PublicationMetricsJobsTest.php tests/Feature/Analytics/AnalyticsScheduleTest.php`--Expected: PASS.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Jobs/Analytics app/Console/Commands/Analytics routes/console.php tests/Feature/Analytics-git commit -m "feat: schedule persisted publication metrics"-```--### Task 12: Build the portable workspace analytics read model--**Files:**-- Create: `app/Dto/Analytics/DateRange.php`-- Create: `app/Actions/Analytics/BuildWorkspaceAnalyticsReport.php`-- Create: `app/Actions/Analytics/BuildPublicationAnalyticsReport.php`-- Create: `app/Actions/Analytics/BuildFollowerAnalyticsReport.php`-- Create: `app/Actions/Analytics/GetAnalyticsBounds.php`-- Create: `app/Actions/Analytics/ReadPublicationAnalytics.php`-- Create: `app/Support/Analytics/PeriodBuckets.php`-- Create: `app/Support/Analytics/MetricComparison.php`-- Test: `tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php`--**Interfaces:**-- Consumes: all four analytics models.-- Produces: `BuildWorkspaceAnalyticsReport::execute(Workspace $workspace, DateRange $range): array` and `ReadPublicationAnalytics::latestForPostPlatform(PostPlatform $postPlatform): array`.--- [ ] **Step 1: Write failing query tests covering every dashboard block**--Create two Instagram accounts and one X account in the same workspace plus a foreign-workspace account. Assert:--- min/max date bounds from snapshots or publications;-- range validation and equal-length previous range;-- end-date follower total, per-account Line/Bar/Growth, carry-forward provenance;-- Posts Bar totals and daily/weekly/monthly zero-filled buckets at 14/15/90/91-day boundaries;-- exactly five Summary values;-- pooled engagement `sum(numerator) / sum(denominator)`, excluding only invalid denominators;-- deterministic Top 5 ties by publication time then id;-- Performance rows per social account, including two separate Instagram rows;-- historical rows after live account deletion;-- cumulative metrics for posts selected by publication date use their latest- successful observation and are never summed across snapshot dates;-- an imported YouTube upload without authoritative Short metadata is presented- as YouTube Video, not falsely as YouTube Short;-- no excluded platform or foreign-workspace contribution;-- unavailable/null distinct from zero.--- [ ] **Step 2: Run read-model tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php`--Expected: FAIL because report Actions are absent.--- [ ] **Step 3: Implement date/bucket value objects and indexed queries**--Avoid JSON predicates for dashboard aggregation. Select latest publication snapshot through portable subqueries keyed by publication id and maximum collected time/date. Use scalar nullable columns and Eloquent/query builder without `ILIKE`, driver-specific date truncation, or database-specific JSON functions. Generate calendar bucket boundaries in PHP and group fetched aggregate rows into those boundaries.--The response shape is stable:--```php-[- 'bounds' => ['min' => '2025-09-23', 'max' => '2026-09-23'],- 'range' => ['start' => '2026-08-25', 'end' => '2026-09-23'],- 'summary' => [...],- 'followers' => ['total' => 15200, 'accounts' => [...], 'series' => [...]],- 'posts' => ['resolution' => 'weekly', 'accounts' => [...], 'buckets' => [...]],- 'top_posts' => ['reactions' => [...], 'comments' => [...]],- 'performance' => [...],- 'coverage' => [...],-];-```--- [ ] **Step 4: Run query tests and inspect query count**--Run: `php artisan test --compact tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php`--Expected: PASS with a fixed query count that does not grow with account/publication count.--- [ ] **Step 5: Run the same test suite against PostgreSQL and MySQL**--Run the repository's configured PostgreSQL and MySQL CI/database commands. Expected: identical values and ordering on both engines; JSON assertions use recursive equality.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Dto/Analytics/DateRange.php app/Actions/Analytics app/Support/Analytics tests/Feature/Analytics/WorkspaceAnalyticsReportTest.php-git commit -m "feat: query workspace analytics reports"-```--### Task 13: Replace analytics web, post, REST, and MCP read paths with persisted data--**Files:**-- Modify: `app/Http/Controllers/App/AnalyticsController.php`-- Modify: `routes/app.php`-- Modify: `app/Http/Controllers/App/PostController.php`-- Modify: `app/Services/Post/PostMetricsFetcher.php`-- Modify: `app/Mcp/Tools/Post/GetPostMetricsTool.php`-- Modify: `app/Http/Controllers/Api/PostController.php`-- Modify: `app/Http/Resources/Api/PostMetricsResource.php`-- Test: `tests/Feature/Analytics/AnalyticsControllerTest.php`-- Test: `tests/Feature/Analytics/PersistedPostMetricsReadTest.php`-- Modify: `tests/Feature/AnalyticsResilienceTest.php`--**Interfaces:**-- Consumes: Task 12 queries.-- Produces: one workspace analytics Inertia response and one persisted publication-detail contract shared by web/API/MCP.--- [ ] **Step 1: Write failing no-provider-read tests**--Seed analytics rows, call `/analytics`, post metrics JSON, REST, and MCP, then assert response values and `Http::assertNothingSent()`. Assert an account id from another workspace cannot affect results. Assert LinkedIn, Telegram, Discord, and Google Business expose no V1 block.--- [ ] **Step 2: Run controller/read tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsControllerTest.php tests/Feature/Analytics/PersistedPostMetricsReadTest.php tests/Feature/AnalyticsResilienceTest.php`--Expected: FAIL because current controllers call provider services and Redis-backed `PostMetricsFetcher`.--- [ ] **Step 3: Make `AnalyticsController@index` the only dashboard read endpoint**--Validate `start`/`end` as dates, clamp them to available bounds, authorize the current workspace, and pass the Task 12 report to `Inertia::render('analytics/Index', ...)`. Remove the per-account `show` route and provider dispatch after all frontend callers are removed.--- [ ] **Step 4: Convert `PostMetricsFetcher` into a persisted read facade**--Remove `Cache::remember` and all social-service dependencies. It delegates to `ReadPublicationAnalytics`, returns canonical metric keys/labels/units/freshness/origin, and preserves its web/API/MCP callers until their response types are updated together.--- [ ] **Step 5: Run all analytics read tests**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsControllerTest.php tests/Feature/Analytics/PersistedPostMetricsReadTest.php tests/Feature/AnalyticsResilienceTest.php tests/Feature/Mcp`--Expected: PASS and no provider HTTP requests.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Http/Controllers app/Services/Post/PostMetricsFetcher.php app/Mcp routes/app.php tests/Feature/Analytics tests/Feature/AnalyticsResilienceTest.php tests/Feature/Mcp-git commit -m "feat: read analytics exclusively from database"-```--### Task 14: Build the workspace analytics dashboard--**Files:**-- Replace: `resources/js/pages/analytics/Index.vue`-- Create: `resources/js/components/analytics/workspace/types.ts`-- Create: `resources/js/components/analytics/workspace/AnalyticsSection.vue`-- Create: `resources/js/components/analytics/workspace/SummaryCards.vue`-- Create: `resources/js/components/analytics/workspace/FollowersChart.vue`-- Create: `resources/js/components/analytics/workspace/PostsChart.vue`-- Create: `resources/js/components/analytics/workspace/TopPosts.vue`-- Create: `resources/js/components/analytics/workspace/PerformanceTable.vue`-- Create: `resources/js/components/analytics/workspace/ImportCoverage.vue`-- Create: `resources/js/components/analytics/workspace/AccountIdentity.vue`-- Create: `resources/js/components/analytics/workspace/charts/LineChart.vue`-- Create: `resources/js/components/analytics/workspace/charts/HorizontalBarChart.vue`-- Create: `resources/js/components/analytics/workspace/charts/StackedBarChart.vue`-- Modify: `lang/en/analytics.php`-- Modify: every locale counterpart required by localization parity-- Test: `tests/Browser/WorkspaceAnalyticsTest.php`--**Interfaces:**-- Consumes: Task 13 Inertia report shape.-- Produces: responsive workspace dashboard matching the reference behavior without provider calls.--- [ ] **Step 1: Write the failing browser test**--The test seeds two Instagram accounts and one X account, visits `/analytics`, asserts exactly five Summary cards, separate account labels, Line/Bar/Growth switching, Posts Bar/Stacked Bar switching, Top 5 Reactions/Comments switching, Performance rows, range navigation, origin labels, coverage state, empty state, and no JavaScript errors/console logs.--```php-$page = visit(route('app.analytics'));-$page->assertSee('Total Followers')- ->assertSee('@first · Instagram')- ->assertSee('@second · Instagram')- ->click('Growth')- ->assertSee('-20')- ->assertNoJavaScriptErrors()- ->assertNoConsoleLogs();-```--- [ ] **Step 2: Run the browser test and verify it fails**--Run: `php artisan test --compact tests/Browser/WorkspaceAnalyticsTest.php`--Expected: FAIL because the workspace components are absent.--- [ ] **Step 3: Implement typed dashboard composition and date filter**--Use a single root element, existing `DateRangePicker`, and an Inertia GET visit preserving state/scroll. Set picker min/max from report bounds and disable it in the no-data/import-pending state. All chart-mode toggles are client-side because the response contains every required series.--- [ ] **Step 4: Implement dependency-free visualizations**--`LineChart.vue` computes SVG points from daily values and leaves gaps where no observation exists. `HorizontalBarChart.vue` supports positive/negative Growth around a zero axis. `StackedBarChart.vue` renders zero-filled daily/weekly/monthly buckets. Use stable account colors based on account order/id, platform icons, semantic buttons, keyboard focus, tooltips for precision/freshness, and horizontal scrolling on narrow screens.--- [ ] **Step 5: Implement reporting blocks and translations**--Summary contains only Posts, Total Followers, Reactions, Comments, and-Engagement Rate. Top 5 cards show destination origin and only valid actions.-Performance sorting is local over the returned rows. Unsupported renders an em-dash, never `0`; measured zero renders `0`. Summary, Top 5, and Performance-tooltips disclose that reactions/comments are the latest cumulative values for-posts published in the selected period, not events that occurred inside it.--- [ ] **Step 6: Run browser and frontend checks**--```bash-php artisan test --compact tests/Browser/WorkspaceAnalyticsTest.php-npm run lint-npx vue-tsc --noEmit-npm run build-```--Expected: all pass.--- [ ] **Step 7: Commit**--```bash-git add resources/js/pages/analytics resources/js/components/analytics/workspace lang tests/Browser/WorkspaceAnalyticsTest.php-git commit -m "feat: add workspace analytics dashboard"-```--### Task 15: Replace individual-post analytics UI and add external publication detail--**Files:**-- Modify: `resources/js/components/posts/PostPlatformMetrics.vue`-- Modify: `resources/js/pages/posts/Show.vue`-- Create: `resources/js/components/analytics/workspace/PublicationMetrics.vue`-- Create: `resources/js/pages/analytics/Publications/Show.vue`-- Create: `app/Http/Controllers/App/AnalyticsPublicationController.php`-- Modify: `routes/app.php`-- Modify: `lang/en/posts.php`-- Modify: locale counterparts required by parity-- Test: `tests/Feature/Analytics/AnalyticsPublicationControllerTest.php`-- Test: `tests/Browser/PublicationAnalyticsTest.php`--**Interfaces:**-- Consumes: Task 13 persisted detail contract.-- Produces: rich persisted metrics for TryPost destinations and a read-only route for imported external publications.--- [ ] **Step 1: Write failing authorization and browser tests**--Assert workspace ownership, imported rows have no edit/retry/delete action, `Published via TryPost` versus `Published on Instagram`, content-specific metric groups, canonical display units, last-collected/stale/estimated labels, excluded-platform absence, and no provider request.--- [ ] **Step 2: Run tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsPublicationControllerTest.php tests/Browser/PublicationAnalyticsTest.php`--Expected: FAIL because the page and persisted UI contract are absent.--- [ ] **Step 3: Implement controller and shared presentation component**--Authorize through the publication's immutable workspace id. The controller passes publication identity, origin, public URL, preview, account snapshot, and latest metric groups. `PublicationMetrics.vue` renders common engagement, exposure, and video-retention sections and is reused by `PostPlatformMetrics.vue`.--- [ ] **Step 4: Remove request-time fetching from the post component**--Pass persisted metrics as page props or load them from the local-only JSON endpoint. Do not keep `onMounted` provider semantics, Redis loading language, or swallowed provider errors. Excluded destinations do not render the block.--- [ ] **Step 5: Run tests and frontend checks**--```bash-php artisan test --compact tests/Feature/Analytics/AnalyticsPublicationControllerTest.php tests/Browser/PublicationAnalyticsTest.php tests/Browser/PostShowContentTypeTest.php-npm run lint-npx vue-tsc --noEmit-```--Expected: PASS.--- [ ] **Step 6: Format and commit**--```bash-vendor/bin/pint --dirty --format agent-git add app/Http/Controllers/App/AnalyticsPublicationController.php routes/app.php resources/js/components/posts resources/js/components/analytics/workspace/PublicationMetrics.vue resources/js/pages/analytics/Publications lang tests/Feature/Analytics tests/Browser-git commit -m "feat: persist individual publication analytics"-```--### Task 16: Verify rollout, observability, portability, and remove obsolete analytics code--**Files:**-- Modify: `config/horizon.php`-- Delete: `resources/js/components/analytics/AnalyticsAccountSelector.vue`-- Delete: `resources/js/components/analytics/FacebookAnalytics.vue`-- Delete: `resources/js/components/analytics/GoogleBusinessAnalytics.vue`-- Delete: `resources/js/components/analytics/InstagramAnalytics.vue`-- Delete: `resources/js/components/analytics/LinkedInPageAnalytics.vue`-- Delete: `resources/js/components/analytics/MetricsGrid.vue`-- Delete: `resources/js/components/analytics/PinterestAnalytics.vue`-- Delete: `resources/js/components/analytics/TelegramAnalytics.vue`-- Delete: `resources/js/components/analytics/ThreadsAnalytics.vue`-- Delete: `resources/js/components/analytics/TikTokAnalytics.vue`-- Delete: `resources/js/components/analytics/XAnalytics.vue`-- Delete: `resources/js/components/analytics/YouTubeAnalytics.vue`-- Delete: `resources/js/components/analytics/types.ts`-- Modify: `docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.md`-- Test: `tests/Feature/Analytics/AnalyticsObservabilityTest.php`-- Test: `tests/Feature/LocalizationParityTest.php`--**Interfaces:**-- Consumes: the completed feature.-- Produces: deployable queue configuration, truthful operational logs, clean code, and verified cross-engine behavior.--- [x] **Step 1: Write failing observability and queue configuration tests**--Assert every log context contains workspace id, social-account key, platform, collector, date/cursor, attempt, and sanitized category but excludes access/refresh tokens and raw sensitive responses. Assert analytics jobs use the `analytics` queue and Horizon supervises it.--- [x] **Step 2: Run observability tests and verify they fail**--Run: `php artisan test --compact tests/Feature/Analytics/AnalyticsObservabilityTest.php`--Expected: FAIL until queue/log configuration is complete.--- [x] **Step 3: Configure the queue and clean obsolete read paths**--Add the analytics queue to existing Horizon supervisors without changing unrelated queue balancing. Remove old account selector/per-network dashboard components only after `rg` proves no imports. Keep low-level social analytics calls that normalized collectors share; remove translated request-time wrappers only when no publisher, test, API, or MCP path references them.--- [x] **Step 4: Run targeted and full verification**--```bash-vendor/bin/pint --dirty --format agent-php artisan test --compact tests/Feature/Analytics tests/Feature/Services/Social tests/Feature/Observers tests/Feature/Mcp tests/Browser/WorkspaceAnalyticsTest.php tests/Browser/PublicationAnalyticsTest.php tests/Feature/LocalizationParityTest.php-npm run lint-npx vue-tsc --noEmit-npm run build-php artisan test --compact-```--Expected: all pass.--- [x] **Step 5: Verify PostgreSQL and MySQL**--Run the full database-dependent analytics suite on both supported engines. Confirm migrations roll up/down, all four unique keys enforce the same identities, nullable booleans/JSON are asserted portably, and aggregate ordering is deterministic.--Local verification: PostgreSQL Feature 3,853 passed (14,726 assertions; 1 skipped), Unit 1,335 passed (3,618 assertions), and browser 74 passed (301 assertions). On an isolated temporary MySQL database, the analytics and post-consumer suite passed 225 tests (939 assertions); the four analytics migrations rolled back and reapplied successfully. A later focused MySQL run for the authorization/fixture safety fix passed 34 tests (148 assertions), then its temporary database was removed. Frontend lint, typecheck, and build passed. These checks do not validate production API permissions or quota.--After the X timeline-cap and account-reactivation fixes, the complete default-PostgreSQL test command (`php artisan test --compact`) was rerun on 2026-09-23:-5,196 passed, 1 skipped, 18,389 assertions. This is fresh regression evidence-for the committed branch; it is not a new MySQL, browser, provider-permission,-or production-canary result.--- [ ] **Step 6: Perform controlled capability and rollout checks**--Local canary evidence (2026-09-23): the workspace from the reported-`/analytics` request (`01a0caa6-1121-732e-9197-4ab7bbc8b5d9`) has one-eligible Threads account. Its queued history backfill is `complete`, reached-the 365-day target (oldest publication 2025-09-23), and stored 50 external-publications with 50 measured metric snapshots plus one actual follower-snapshot. Running `analytics:backfill-existing --workspace=<that UUID>`-reported `historical_identity_unrecoverable=0`; afterward the analytics queue-was empty and the publication count was unchanged, confirming this local-rerun did not duplicate the catalog. A failed-page bootstrap now preserves the-last committed cursor, verified by 13 backfill tests on both PostgreSQL and-MySQL. This local canary does not prove production application permissions,-quotas, other platform adapters, or a safe global rollout.--Post-canary safety audit: an analytics-only `401`/`403` no longer calls-`markAsTokenExpired()` on an otherwise connected account. It records the-analytics failure without a false follower value, while the separately-scheduled connection verifier owns publishing-health transitions. The focused-tests cover both rejection categories and isolate account-created jobs in-schema/backfill fixtures; the full PostgreSQL Feature and browser suites pass.--Pinterest pagination audit: the official [Pins API contract](https://github.com/pinterest/pinterest-python-generated-api-client/blob/main/docs/PinsApi.md)-documents bookmark pagination but does not guarantee chronological ordering;-the [pagination reference](https://developers.pinterest.com/docs/reference/pagination/)-allows 250 items per page. The collector now skips out-of-range Pins while-following every bookmark at that page size, and its-sync page explicitly disables date-boundary early completion. Regression tests-cover an old Pin before a newer Pin and a Pin exactly on the cutoff with a-remaining bookmark. The 137-test PostgreSQL analytics suite passes; live-Pinterest permissions, volume, and bookmark behavior remain rollout checks.--Instagram/YouTube local canary (2026-09-23): both accounts in workspace-`01a0caa6-1121-732e-9197-4ab7bbc8b5d9` completed the publication backfill.-Instagram has 50 publications, 50 metric snapshots, and one follower snapshot.-YouTube imported 38 publications, but its two newest videos initially lacked-metric snapshots because the Analytics API returned no processed rows. The-official [YouTube data model](https://developers.google.com/youtube/analytics/data_model)-documents a typical 48–72-hour delay and recommends Data API `videos.list`-for current counts. A fallback now records views, likes, and comments from-that endpoint when the Analytics report is empty; two isolated queued canary-jobs produced the missing snapshots, bringing YouTube to 38/38. The isolated-queue emptied. Re-running `analytics:backfill-existing` only for this workspace-reported `historical_identity_unrecoverable=0` and left publication/snapshot-counts unchanged. These are local app credentials and do not prove other-platforms or production quotas.--X timeline-cap safeguard (2026-09-23): regression tests now cover the-3,200-post cap, true exhaustion below that cap, failed-cursor resume,-stale-worker fencing, and count reset on invalid cursor or terminal restart.-No live X request was made; billed-read cost remains a release gate.--Account reactivation audit (2026-09-23): re-enabling an inactive connected-account now dispatches its initial follower and publication bootstrap jobs.-Previously the observer only reacted to a status change, so a paused account-could stay without a backfill until an operator ran the rollout command.-Disconnected or excluded accounts still do not start analytics collection.--Before dispatching the production rollout:--1. confirm the production TikTok app has `video.list` and `user.info.stats`;-2. connect/test one Instagram-direct and one Instagram-via-Facebook account;-3. verify Facebook Page posts, videos/Reels, and follower fields with the current Page token;-4. confirm Threads follower insights and owned-post pagination with a production-approved token;-5. measure X follower, owned-post, and metric read cost on one bounded 365-day account before widening rollout;-6. verify Pinterest owned-Pin bookmarks, lifetime/range analytics, and the production app's read scopes;-7. verify the YouTube uploads playlist, batched video details, channel statistics, and Analytics API scopes;-8. confirm Bluesky repository pagination plus public count hydration against a large account;-9. reconnect a Mastodon test account with `read:statuses` and confirm private-history behavior on two different instances;-10. verify follower collection once for every included platform and both Instagram login variants;-11. export the selected canary workspace UUID as `ANALYTICS_CANARY_WORKSPACE_ID`, then run `php artisan analytics:backfill-existing --workspace="$ANALYTICS_CANARY_WORKSPACE_ID"`;-12. verify coverage, orphan-skip, rate-limit, and retry states, then run the command without the workspace filter.--- [ ] **Step 7: Update spec status and commit**--Mark implemented gates with the actual provider limitations observed; do not weaken documented coverage silently.--```bash-git add config .env.example app resources/js docs/superpowers/specs tests-git commit -m "chore: finalize workspace analytics rollout"-```--## Self-Review Results--- **Spec coverage:** Every V1 surface, included/excluded platform, follower fallback, native backfill, reconciliation rule, metric catalog, date range, Summary, Top 5, Performance, individual detail, REST/MCP read path, and LinkedIn V2 boundary maps to Tasks 1–16.-- **Schema audit:** The four-table design is retained as the minimum safe split.- Publication snapshots no longer duplicate tenant ownership, and sync state is- reduced to two live-account cursor workflows rather than becoming a second- job/fact ledger.-- **Concurrency audit:** Unique constraints arbitrate missing-row races,- same-day metric families merge under a row lock, and paginated jobs advance- only a checkpoint version they actually fetched.-- **Lifecycle audit:** Historical facts survive account/post deletion, sync- checkpoints do not, reconnects reuse identity through provider ids, and- pre-rollout orphan destinations are skipped and disclosed rather than guessed.-- **Placeholder scan:** The plan contains no forbidden placeholder markers, no unnamed error handling, and no task that delegates unspecified work. Provider mappings and final manual capability gates are explicit.-- **Type consistency:** The four model names, DTO constructors, collector signatures, origin values, sync states, and query method names are introduced once and reused consistently.-- **Review focus:** Each of the five highest-risk inputs is pinned to an explicit test in Tasks 1/2, 3/10, 5, 9, or 12.-- **Scope decomposition:** Backend persistence, account collection, publication discovery, metric collection, read model, dashboard, and detail UI are independent review gates but remain in one plan and one branch because their contracts form one source-of-truth migration.diff --git a/docs/superpowers/plans/2026-09-24-independent-social-posts.md b/docs/superpowers/plans/2026-09-24-independent-social-posts.mddeleted file mode 100644index ee55a61ed..000000000--- a/docs/superpowers/plans/2026-09-24-independent-social-posts.md+++ /dev/null@@ -1,254 +0,0 @@-# Independent Social Posts Implementation Plan--> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.--**Goal:** Create one independently editable post per selected social account from a two-step dialog, preserving production history and parity across web, API, and MCP.--**Architecture:** Keep `posts` and `post_platforms`: every new post has exactly one enabled delivery row. A batch Action resolves account-specific overrides, validates all destinations, and writes all rows in one transaction. Preserve settled legacy rows; split only editable multi-target drafts and scheduled posts at a guarded cutover.--**Tech Stack:** PHP 8.5, Laravel 13.24.0, PostgreSQL and MySQL, Pest 5, Inertia Laravel 3.3.1, Vue 3.5, `@inertiajs/vue3` 3.6, Wayfinder, existing Asset Library and queue.--**Spec:** `docs/superpowers/specs/2026-09-24-independent-social-posts-design.md`--## Global Constraints--- One selected **social account** equals one `posts` row and one enabled `post_platforms` row; multiple accounts on one network are valid.-- Account/network cannot change on edit; a compatible `content_type` can change.-- Compose in browser state until Save Draft, Schedule, or Publish. Upload media through the existing Asset Library before saving posts.-- Keep the current sidebar/status navigation. The proposed single Posts item and tabs are deferred.-- Batch database creation is atomic. A rejected request leaves already uploaded assets in the workspace library.-- Web, REST API and MCP call the same Actions. `POST /posts` retains a single-resource response; a distinct endpoint/tool handles batches.-- `posts.scheduled_at` remains the schedule source; `FinalizePostPublication` remains the only settler.-- X caption limits and previews must use the existing sanitized-content/defused-link behavior; the new dialog needs the same `xLinkTlds` prop when `X_DEFUSE_LINKS` is enabled.-- Preserve settled legacy IDs, analytics FKs, comments, media and provider IDs/URLs. Split only active drafts/scheduled rows after pausing writes/scheduler and draining affected workers.-- No new dependency or schema migration. SQL, migrations and tests must work on PostgreSQL and MySQL; MySQL `timestamp()` ends at 2038-01-19.-- Read `.ai/rules/index.md` and matching rules before each implementation area; search versioned Laravel Boost docs before code changes. Consult official platform docs if changing platform API behavior.-- Every code change has a focused test. Run affected Pest/browser tests and `vendor/bin/pint --dirty --format agent` after PHP edits.--## Review Focus--Each likely failure has a test in the owning task:--1. Two accounts on the same network must produce two independent posts (Task 2).-2. Explicit empty caption/media overrides must replace shared values while inherited values track first-step changes (Task 5).-3. Changing Instagram Post to Reel/Story must revalidate media without changing the account (Task 3).-4. One invalid/inactive/foreign-workspace destination must roll back the entire batch and dispatch no jobs (Task 2).-5. Rerunning the legacy split with disabled placeholders and nested comments must preserve IDs and relationships (Task 8).-------## File map--| Area | Files | Responsibility |-| --- | --- | --- |-| Domain | `app/Support/PostCompositionValidator.php`, `app/Actions/Post/{CreateChannelPost,CreatePosts,UpdatePost}.php` | Resolve, validate, create and edit individual destination posts. |-| API/MCP | `app/Http/Controllers/Api/PostController.php`, `app/Http/Requests/Api/Post/{StorePostRequest,StorePostsRequest,UpdatePostRequest}.php`, `routes/api.php`, `app/Mcp/Tools/Post/{CreatePostTool,CreatePostsTool,UpdatePostTool}.php`, `app/Mcp/Servers/TryPostServer.php` | Single and batch contracts via Actions. |-| Composer | `resources/js/composables/usePostComposition.ts`, `resources/js/components/posts/composer/PostComposerDialog.vue`, `resources/js/components/ImageCropperDialog.vue`, `resources/js/lib/imageCrop.ts` | Two-step dialog, inheritance, per-account crop and upload. |-| Web | `app/Http/Controllers/App/PostController.php`, app post requests, `app/Support/LegacyPostCard.php`, `resources/js/pages/posts/{Index,Calendar,Edit}.vue`, `routes/app.php` | Dialog routes, individual/legacy cards and old links. |-| Internal paths | AI creation, repurpose and duplication callers of `CreatePost::execute` / `SyncPostPlatforms::execute` | Remove all grouped writes. |-| Legacy | `app/Console/Commands/{AuditLegacyPosts,SplitLegacyActivePosts}.php` | Audit and idempotent split. |--Develop Tasks 1–7 without enabling new write routes in production. Task 8 supplies the data gate; Task 9 enables the flow. Each task ends with a reviewable commit.--### Task 1: Resolve and validate compositions--**Files:** Create `app/Support/PostCompositionValidator.php`; test `tests/Unit/Support/PostCompositionValidatorTest.php`. Reuse `PostMediaRules`, `PostPlatformMetaRules`, `ContentFitsPlatformLimits`, `ContentTypeCompatibleWithMedia`.--**Interfaces:** `PostCompositionValidator::validate(Workspace $workspace, array $composition): array` returns ordered fully resolved `destinations[]` with `social_account_id`, `content_type`, `meta`, `content`, `media`.--- [ ] **Step 1: Write failing tests** for inheritance, explicit `content: ''` / `media: []`, duplicate accounts, inactive and foreign accounts, unsupported type, bad labels, media asset ownership, and scheduled media/caption/meta errors keyed as `destinations.N.field`. Include X sanitized-length behavior. Core assertion:--```php-$resolved = PostCompositionValidator::validate($workspace, $composition);-expect($resolved['destinations'][0]['content'])->toBe('Shared');-expect($resolved['destinations'][1]['content'])->toBe('');-```--- [ ] **Step 2: Run** `php artisan test --compact tests/Unit/Support/PostCompositionValidatorTest.php`; expect missing class.-- [ ] **Step 3: Implement** one account lookup, duplicate-ID check, account/workspace/activity/type checks and existing per-platform media/content/meta rules. Drafts may be incomplete; scheduled/publishing posts must be publishable. Resolve overrides with key presence:--```php-$content = array_key_exists('content', $destination) ? $destination['content'] : ($composition['content'] ?? '');-$media = array_key_exists('media', $destination) ? $destination['media'] : ($composition['media'] ?? []);-```--- [ ] **Step 4: Run** focused tests on PostgreSQL and MySQL test configurations; run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): validate per-account compositions`.--### Task 2: Create one post per destination atomically--**Files:** Create `app/Actions/Post/{CreateChannelPost,CreatePosts}.php`; test `tests/Feature/Actions/CreatePostsTest.php`. Use snapshot fields from `SyncPostPlatforms.php`.--**Interfaces:** `CreateChannelPost::execute(Workspace $workspace, User $user, array $destination): Post`; `CreatePosts::execute(Workspace $workspace, User $user, array $composition): Collection` in input order. Both consume Task 1's resolved shape.--- [ ] **Step 1: Write failing tests** for four accounts/four posts/four enabled targets and zero disabled placeholders; two Instagram accounts separate; labels and schedule copied; draft/scheduled/immediate statuses; invalid destination creates zero rows and zero `PublishPost` jobs. Check failure/retry on one post leaves siblings unchanged:--```php-$posts = CreatePosts::execute($workspace, $user, $composition);-expect($posts)->toHaveCount(4);-foreach ($posts as $post) {- expect($post->postPlatforms()->count())->toBe(1);- expect($post->postPlatforms()->enabled()->count())->toBe(1);-}-```--- [ ] **Step 2: Run** `php artisan test --compact tests/Feature/Actions/CreatePostsTest.php`; expect missing Actions.-- [ ] **Step 3: Implement** single parent+target creation with account snapshot, no `SyncPostPlatforms`. Validate before `DB::transaction`; within it create each post, attach labels, and set status/schedule. Queue immediate publication only after commit:--```php-$resolved = PostCompositionValidator::validate($workspace, $composition);-return DB::transaction(fn (): Collection => collect($resolved['destinations'])->map(- fn (array $destination): Post => CreateChannelPost::execute($workspace, $user, $destination)-));-```--Include labels/status/schedule and `PublishPost::dispatch($post)->afterCommit()` inside the actual transaction mapping; no external publish inside it.-- [ ] **Step 4: Run** this test and `tests/Feature/Jobs/PublishPostTest.php` on both engines; run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): create independent destination posts`.--### Task 3: Edit only one destination--**Files:** Modify `app/Actions/Post/UpdatePost.php`, app/API update requests; test `tests/Feature/Actions/UpdateChannelPostTest.php` and existing `tests/Feature/UpdatePostRequestTest.php`.--**Interfaces:** Retain `UpdatePost::execute(Workspace $workspace, Post $post, array $data): array{post: Post, action: PostAction|null}`. Accept content, media, content_type, meta, schedule/status and labels; reject destination replacement.--- [ ] **Step 1: Write failing tests** changing Instagram Post to Reel/Story with compatible media; incompatible media gives 422 and rolls back; a different `social_account_id` or `platforms[]` gives 422. Editing one of two new posts leaves the other unchanged. Finalized and legacy multi-target posts remain readable and cannot enter the new edit flow.-- [ ] **Step 2: Run** `php artisan test --compact tests/Feature/Actions/UpdateChannelPostTest.php tests/Feature/UpdatePostRequestTest.php`; expect failures.-- [ ] **Step 3: Implement** validation against the final content/media/type, then update only the sole enabled target's type/meta and parent fields. Keep status transitions and Google Business cleanup behavior. Never disable/re-enable all targets:--```php-if (array_key_exists('social_account_id', $data) || array_key_exists('platforms', $data)) {- throw ValidationException::withMessages(['social_account_id' => __('posts.errors.target_fixed')]);-}-$target = $post->postPlatforms()->enabled()->sole();-```--- [ ] **Step 4: Run** focused tests and API update tests; run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): edit one account post`.--### Task 4: Add API and MCP single/batch parity--**Files:** Modify API PostController, `StorePostRequest`, routes, MCP `CreatePostTool`/`UpdatePostTool`/server; create `app/Http/Requests/Api/Post/StorePostsRequest.php`, `app/Mcp/Tools/Post/CreatePostsTool.php`; test `tests/Feature/Api/PostApiTest.php`, `tests/Feature/Mcp/PostToolTest.php`.--**Interfaces:** `POST /api/posts` creates exactly one destination and returns one `PostResource`; `POST /api/posts/batch` takes `destinations[]` and returns ordered `posts: PostResource[]`; MCP single/batch tools return one or ordered IDs. Both call `CreatePosts`.--- [ ] **Step 1: Write failing tests** for single legacy `platforms[0]`, clear 422 on multi-platform single create, batch 201/ordered IDs, invalid batch zero rows, MCP permissions/parity, fixed-account update, and old aggregate GET readability.-- [ ] **Step 2: Run** `php artisan test --compact tests/Feature/Api/PostApiTest.php tests/Feature/Mcp/PostToolTest.php`; expect contract failures.-- [ ] **Step 3: Implement** conversion of one legacy platform into one destination, register batch route before parameterized route, call Actions and preserve `PostResource`:--```php-Route::post('/posts/batch', [PostController::class, 'storeBatch'])->name('api.posts.batch.store');-Route::post('/posts', [PostController::class, 'store'])->name('api.posts.store');-```--Register `CreatePostsTool` in `TryPostServer`. Reject multi-platform old requests explicitly; do not silently return a new response shape.-- [ ] **Step 4: Run** focused tests and `php artisan route:list --path=api/posts --except-vendor`; run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): expose independent batch creation in API and MCP`.--### Task 5: Build the two-step dialog and account-specific crop--**Files:** Create `resources/js/composables/usePostComposition.ts`, `resources/js/components/posts/composer/PostComposerDialog.vue`; modify `ImageCropperDialog.vue`, `imageCrop.ts`; test `tests/Browser/PostComposerDialogTest.php`.--**Interfaces:** Dialog emits the spec's `PostComposition`; edit mode receives one post/target. Crop output is an uploaded Asset Library snapshot for only the chosen account.--- [ ] **Step 1: Write failing browser tests** selecting four accounts, overriding one caption/crop/type, returning to step one, and checking inherited fields update while explicit empty/other overrides persist. Removing/re-adding an account resets its override. Upload before save creates an asset but no post. GIF/video cannot use static crop; crop upload failure leaves original selected. The X preview/character count matches sanitized output when link defusing is on.-- [ ] **Step 2: Run** `php artisan test --compact tests/Browser/PostComposerDialogTest.php`; expect missing UI.-- [ ] **Step 3: Implement** base step and expandable per-account step, account-ID-keyed override map, platform previews, existing asset upload, optional aspect ratio/output dimensions in cropper, and disabled final button during submission. Reuse the editor's `xLinkTlds` prop and `defuseXLinks` mirror for X previews/counts. Materialize inheritance by key presence:--```ts-const content = Object.prototype.hasOwnProperty.call(override, 'content') ? override.content! : composition.content;-const media = Object.prototype.hasOwnProperty.call(override, 'media') ? override.media! : composition.media;-```--- [ ] **Step 4: Run** browser test and the typecheck/lint scripts in `package.json`; expect pass.-- [ ] **Step 5: Commit** `feat(posts): compose and crop per account in a dialog`.--### Task 6: Wire web routes and independent cards--**Files:** Create `app/Support/LegacyPostCard.php`; modify `app/Http/Controllers/App/PostController.php`, app post requests, `resources/js/pages/posts/{Index,Calendar,Edit}.vue`, `routes/app.php`; test `tests/Feature/PostControllerTest.php`, `tests/Browser/SidebarMenuTest.php`, `tests/Browser/PostComposerDialogTest.php`.--**Interfaces:** Web store calls `CreatePosts`; web edit calls `UpdatePost`; New Post/Edit open Task 5's dialog. Keep old status/deep-link URLs.--- [ ] **Step 1: Write failing tests**: opening New Post creates no draft, saving four drafts gives four cards, edit affects one, account fixed/type mutable, Calendar opens same composer, old status URLs and sidebar links remain usable, search/labels/pagination still work. A settled legacy multi-target post yields one read-only card per enabled target without changing its DB rows.-- [ ] **Step 2: Run** focused controller/sidebar/composer tests; expect old full-page/autosave behavior.-- [ ] **Step 3: Implement** dialog props and route redirects, replace empty-draft-on-open, use Actions, flatten settled legacy aggregate into one read-only card per enabled target and keep new posts as one card each. Keep `/posts/create`, `/posts/{post}/edit`, the existing sidebar and status deep links. Controller entry pattern:--```php-$posts = CreatePosts::execute($workspace, $request->user(), $request->validated());-return redirect()->route('app.posts.index')->with('created_post_ids', $posts->pluck('id')->all());-```--- [ ] **Step 4: Run** focused tests, TypeScript check, Wayfinder generation/check and localization parity; run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): use dialog and independent cards`.--### Task 7: Remove grouped internal writes without changing publishers--**Files:** Modify `app/Jobs/Ai/StreamPostCreation.php`, `app/Jobs/Repurpose/ProcessRepurposeItem.php`, `app/Actions/Post/DuplicatePost.php` and every remaining production caller found by search; retire `app/Actions/Post/CreatePost.php`, `SyncPostPlatforms.php`; test affected AI/repurpose/duplicate suites and `tests/Feature/Jobs/PublishPostTest.php`.--**Interfaces:** Internal single destination calls `CreateChannelPost`; multi-destination internal creation calls `CreatePosts`. `PublishPost` and `FinalizePostPublication` keep their interfaces.--- [ ] **Step 1: Write failing tests** for one-target AI and repurpose posts, one-target duplication, per-post failure/retry, scheduler using `posts.scheduled_at`, and legacy in-flight multi-target publication completing unchanged.-- [ ] **Step 2: Run** focused AI/repurpose/duplicate/publish tests; expect placeholder or grouped-write failures.-- [ ] **Step 3: Move** callers to new Actions while preserving `created_via`, provenance, labels, media and schedule. Search all production callers with:--```bash-rg -n 'CreatePost::execute|SyncPostPlatforms::execute' app routes-```--Retire old grouped writers after the search has no production call site. Do not rewrite platform publishers.-- [ ] **Step 4: Run** focused tests and repeat the search; run Pint. Expect pass/no grouped caller.-- [ ] **Step 5: Commit** `refactor(posts): retire grouped post writers`.--### Task 8: Audit and split active legacy rows--**Files:** Create `app/Console/Commands/{AuditLegacyPosts,SplitLegacyActivePosts}.php`; modify web PostController for zero-target draft recovery; test `tests/Feature/Commands/{AuditLegacyPosts,SplitLegacyActivePosts}Test.php`.--**Interfaces:** `php artisan posts:audit-legacy --no-interaction` reports counts/anomalies read-only; `php artisan posts:split-legacy-active --no-interaction` idempotently splits draft/scheduled rows with >1 enabled target. Settled/in-flight rows remain unchanged.--- [ ] **Step 1: Write failing tests** with two enabled targets plus disabled placeholders, labels, media, nested comments. After two runs original post/first target IDs remain, second target ID moves to clone, comment parent IDs map to cloned comments, schedule/labels/media preserved and second run changes nothing. Audit flags zero-target scheduled rows; zero-target drafts are recoverable. Settled/in-flight rows and analytics IDs remain untouched.-- [ ] **Step 2: Run** focused command tests; expect missing commands.-- [ ] **Step 3: Implement** read-only audit, then lock active parent/targets in ID order in a transaction, clone parent/labels/comments quietly, move each additional enabled target, and assert one enabled target per resulting active post. Exclude disabled placeholders, avoid asset duplication and event emission. Zero-target draft recovery creates new destination posts and deletes the empty draft only after success:--```php-$targets = $post->postPlatforms()->enabled()->orderBy('id')->lockForUpdate()->get();-if ($targets->count() <= 1) {- return;-}-foreach ($targets->skip(1) as $target) {- $clone = $this->clonePostAndRelationsQuietly($post);- $target->updateQuietly(['post_id' => $clone->id]);-}-```--- [ ] **Step 4: Run** command tests on PostgreSQL and MySQL and rehearse audit/split on a restored production snapshot; compare post/target counts, IDs, schedules, labels/comments, media and analytics references. Run Pint. Expect pass.-- [ ] **Step 5: Commit** `feat(posts): audit and split editable legacy posts`.--### Task 9: Guarded cutover and regression gate--**Files:** Only fixes exposed by Tasks 1–8; affected tests and deployment record.--**Interfaces:** Enable new write paths only after strict audit/split succeeds.--- [ ] **Step 1: Write a failing regression test** for any defect found in production-snapshot rehearsal. At minimum strict audit must fail on a zero-target scheduled row:--```php-$this->artisan('posts:audit-legacy', ['--strict' => true])->assertFailed();-```--- [ ] **Step 2: Run** that focused test and observe red before its fix. If it was already covered in Task 8 and no new defect appears, use that existing red/green evidence and add no duplicate test.-- [ ] **Step 3: Apply** the smallest regression fix. The branch contains the composer and new write paths together, so cut over during a maintenance window: back up production; pause post writes and `posts:process-scheduled`; drain affected publishing workers; deploy the branch while application ingress remains closed; run the read-only audit, resolve zero-target scheduled and unavailable-target blockers, split editable multi-target rows, then run strict audit and reconcile counts before reopening ingress and resuming workers/scheduler. If the gate fails, keep ingress closed and restore the prior application release against the unchanged backup or fix forward after assessing any writes. Do not run the split on live data outside the maintenance window.-- [ ] **Step 4: Run** affected post/API/MCP/command/browser tests on both engines, TypeScript check/lint, localization parity, Wayfinder generation/check, route listing and Pint. Verify four-account draft/schedule through web, API and MCP yields four IDs; editing one leaves three unchanged; old aggregate GET/history/analytics still load.-- [ ] **Step 5: Commit** regression fixes as `fix(posts): complete independent-post cutover` if any; record actual production audit/split counts, snapshot rehearsal, both-engine results and go/no-go decision in the deployment record when that work is authorized and available.--## Completion criteria--- Every new writer makes one enabled target per post and no disabled placeholders.-- Save Draft and Schedule each make one independent card/ID per account, including two accounts on the same network.-- Account stays fixed on edit; type, caption, media/crop, metadata and schedule affect only that post.-- Existing navigation remains usable, and opening the composer never creates a post.-- Web, API, MCP and internal producers use shared Actions; settled legacy IDs/analytics remain readable.-- Production audit/split is repeatable, rehearsed on a production snapshot and both engines, and blocks enablement on anomalies.--## Release gate still requiring an environment--The local branch can be completed and reviewed without touching production. A release is **not** approved by local tests alone. Before production cutover, run the audit/split against a restored production snapshot on its database engine and check row counts, target IDs, schedules, media, labels, comments, history and analytics references. Run the suite on MySQL as well as PostgreSQL. Record those results and a fresh production backup before entering the maintenance window above. No production audit, split or deployment has been run as part of local implementation.diff --git a/docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.md b/docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.mddeleted file mode 100644index 18f4bc8ab..000000000--- a/docs/superpowers/specs/2026-09-23-workspace-follower-analytics-design.md+++ /dev/null@@ -1,1434 +0,0 @@-# Workspace follower and post analytics — design--**Status:** V1 implemented on `feat/workspace-analytics-backfill`; production provider validation and a controlled canary backfill remain release gates.--The four analytics migrations have been applied to the local PostgreSQL app-database. The workspace dashboard, queued daily collection and native-history-import, persisted post metrics, and individual-publication detail are in the-branch. On a separate temporary MySQL database, 225 analytics/post-consumer-tests passed (939 assertions), and all four migrations passed rollback and-reapplication; that temporary database was removed. Production app permissions-and provider quotas remain unverified: run the controlled capability checks and-canary rollout below before dispatching a global backfill. LinkedIn remains V2.-The local PostgreSQL Feature suite passed 3,853 tests, Unit passed 1,335, and-the full browser suite passed 74 after isolating asynchronous analytics jobs in-unrelated synchronous-queue test fixtures.--A local Threads workspace canary subsequently completed the 365-day publication-backfill with 50 external publications, 50 measured metric snapshots, and an-actual follower snapshot. The workspace-filtered rollout command reported no-unrecoverable orphan identities and did not duplicate records on rerun. This-is local evidence only; production scopes, quotas, other networks, and global-rollout remain unverified. A failed paginated backfill now resumes from its-last committed cursor, with focused PostgreSQL and MySQL tests.--## Objective--Replace the request-time, per-social-account analytics experience with an-initial workspace-level analytics view covering follower history, posts-successfully published through TryPost, and native posts imported from connected-social accounts.--After the daily collection pipeline begins producing local snapshots, the page-must answer seven questions without querying social APIs at request time:--1. How many followers did this workspace have at the end of the selected- period?-2. How did each connected social account's follower count change over that- period?-3. Which accounts gained or lost followers?-4. How many posts did each social account publish during the selected period,- whether through TryPost or natively, and how was that volume distributed over- time?-5. How did publication volume, reactions, comments, and engagement compare- with the immediately preceding equivalent period?-6. Which destination publications and social accounts performed best?-7. Which detailed metrics, including video-retention metrics where available,- explain the performance of an individual published destination?--Success means `/analytics` renders without making social API calls, daily-follower collection is resilient to transient failures and rate limits, one-broken platform cannot block another account's data, and post volume is derived-from a local unified publication catalog. Post history and performance metrics-are imported or collected ahead of page requests and retained locally.--## Scope boundary--Analytics are always scoped to the **current workspace**. There is no-cross-workspace or user-global total.--The workspace is the tenancy and aggregation boundary. A social account is a-dimension inside that workspace so two accounts on the same network remain-separate chart series.--Every query and collection write must validate the relationship between the-workspace and social account. The design must continue to support multiple-accounts of the same network.--## First-version scope--### Included platforms--| Platform | Value represented | Precision / caveat |-| --- | --- | --- |-| TikTok | Profile followers | Exact value exposed by the user stats API |-| Instagram | Professional-account followers | Includes direct Instagram login and Instagram through Facebook |-| Facebook | Page followers | Page follower total, not daily follows gained |-| Threads | Profile followers | Account insight |-| X | Profile followers | Public user metric; subject to the application's X access and billing limits |-| Pinterest | Account followers | Account `follower_count` |-| YouTube | Channel subscribers | YouTube may round the public subscriber count for larger channels |-| Bluesky | Profile followers | Profile `followersCount` |-| Mastodon | Account followers | Account `followers_count` from the connected instance |--The value is labelled using the platform's native meaning where needed in-tooltips, but all values participate in the workspace's top-level follower-total.--### Explicit v1 platform exclusions--The following platforms are excluded from every analytics surface in v1:--- LinkedIn personal profile-- LinkedIn Page-- Telegram-- Discord-- Google Business Profile--They receive no follower or post-performance collection jobs, appear in no-follower or Posts chart, contribute to no Summary, Top 5, or Performance value,-and expose no individual-post analytics block in this delivery. Their successful-publication records remain intact but are filtered out of `/analytics`.-Publishing, comments/community features, and account connection behavior remain-unchanged.--LinkedIn personal follower analytics requires `r_member_profileAnalytics`,-which is provisioned through the vetted Community Management API product. That-product must initially be the only product on a separate LinkedIn developer-application. LinkedIn post metrics are also deferred so the network enters the-new analytics architecture as one coherent v2 rather than partially in v1.--### Planned v2: LinkedIn--Analytics for both LinkedIn identity types are planned for v2:--- LinkedIn personal profile follower count;-- LinkedIn Page follower count;-- database-backed post metrics for personal profiles and Pages;-- inclusion in Posts, Summary, Top 5, Performance, and individual-post detail.--The v2 keeps the network consistent by introducing both identity types-together. LinkedIn Page data is already technically accessible through the-current application scopes, but personal-profile data remains gated by-Community Management API approval and `r_member_profileAnalytics`.--Before v2 implementation, TryPost must:--1. create a separate LinkedIn developer application with no other provisioned- products;-2. request and receive Community Management API access;-3. confirm the production credential arrangement with LinkedIn after approval;-4. add the newly provisioned analytics scope to the appropriate OAuth flow;-5. require affected LinkedIn accounts to reconnect so their tokens contain the- approved scope;-6. verify the current LinkedIn follower, post, video, and engagement metric- endpoints, API version, scopes, and data-retention requirements;-7. create a separate v2 implementation plan for collection, persistence, and- read-path inclusion.--If Community Management API access is not approved, LinkedIn cannot enter v2.-Shipping LinkedIn Page alone would then require a new explicit product decision-rather than happening implicitly.--Telegram, Discord, and Google Business Profile have no planned analytics v2 in-this design. Adding any of them later requires a new product decision and-official API capability review.--## User experience--### Workspace total--The Total Followers card inside Summary sums one daily follower value per-included social account for the selected range's end date.--- An account contributes at most once.-- Two accounts on the same network both contribute.-- An account with no value for the end date does not silently contribute an- older, unclassified value.-- A carried-forward value created by the daily fallback does contribute.-- An account that was disconnected or deactivated before that date does not- receive a snapshot for the date and therefore does not contribute.--### Follower chart--One follower widget presents the same workspace dataset in three modes:--- **Line:** daily follower count per social account across the selected range.-- **Bar:** follower count per social account on the selected end date.-- **Growth:** net change per social account between its first and last available- values inside the selected range. Positive and negative changes share a zero- axis.--Series and rows use the social account's platform icon, display name or-username, and stable social-account identity. They are not collapsed by-network.--The initial display mode is Line. Changing modes is client-side because all-three views derive from the same response dataset.--### Native post history import--Connecting an account on a platform included in analytics v1 dispatches a-non-blocking native-history backfill. The product target is every owned post-published during the preceding 365 days. The importer paginates until it reaches-that cutoff, exhausts the provider feed, or encounters a documented provider-limit. It never claims a complete year when the API returned less.--For Pinterest, `GET /pins` documents bookmark pagination but not chronological-ordering. Its importer uses the documented 250-item page size, filters out-older Pins, and follows bookmarks until the-provider exhausts them; an old Pin cannot prove that later pages lack eligible-Pins. The sync state may stop at the date boundary only when its collector-explicitly guarantees that ordering.--The account connection succeeds before the backfill finishes. Analytics shows-an import-progress state with the oldest covered publication date, latest-successful sync time, and whether coverage is complete, provider-limited,-partially failed, or still running. Imported results become visible-incrementally; one slow account cannot delay another.--After the initial backfill, a daily queued discovery job imports newly published-native posts. This is separate from the follower and metric collectors. It uses-a per-account high-water mark plus provider cursor checkpoints, overlaps the-last completed window to tolerate late provider results, and relies on an-idempotent key of workspace + social account + platform + native post id.-Reconnects of the same platform identity resume the catalog rather than creating-a second history.--Feature rollout also dispatches the same resumable backfill for every already-connected, active account on an included v1 platform. Rollout work is chunked-and rate limited; it does not require users to disconnect and reconnect to seed-their analytics.--Each imported publication retains, when available:--- workspace and social-account ownership;-- native post id and platform;-- provider publication timestamp;-- content type;-- permalink;-- caption or textual excerpt;-- preview/thumbnail reference and enough immutable presentation metadata to- render a historical card;-- discovery and last-sync timestamps;-- origin (`trypost` or `external`);-- provider coverage and availability state.--The publishing enum labels the integration `YouTube Shorts`, but the owned-uploads API returns every channel upload and does not authoritatively classify-all of them as Shorts. Analytics labels imported unknown uploads as `YouTube`-and content type `Video`; only a TryPost destination or provider field that-proves a Short may render `Short`.--An imported post is an analytics record, not a draft or published `Post` owned-by the TryPost publishing workflow. Importing it must not enable editing,-deletion, retry, repurpose processing, or publishing lifecycle actions. The-physical persistence design may share a catalog with TryPost destinations, but-it must not manufacture `posts` or `post_platforms` rows whose states imply that-TryPost published the content.--When discovery returns a native id already present on a TryPost destination,-the records reconcile into one analytics publication and `trypost` origin wins.-This prevents one post from being counted twice. The same reconciliation runs-when a delayed publish result gains its provider id after native discovery.--The current Repurpose source fetchers prove that Instagram and Facebook media-can already be discovered with the connected account. The analytics importer-may extract and share their low-level provider clients and response parsers, but-it does not reuse `PollRepurposeSource`, `RepurposeItem`, media-download rules,-or activation watermarks. Those components fetch only selected video formats,-currently request one page of 25 items, and have different lifecycle semantics.--For a newly imported publication inside the normal post-metric refresh window,-the importer dispatches the ordinary post-performance job. For an older post in-the 365-day backfill, it dispatches one rate-limited baseline metric collection-and then retains the result without enrolling the post in perpetual daily-refresh. A provider that no longer exposes metrics leaves the post visible with-an explicit unavailable state.--Post-history backfill does not fabricate follower history. Follower charts begin-at the first real follower observation unless the provider has a separately-documented historical follower endpoint.--### Posts chart--A second widget shows the number of analytics publications in the selected-range, combining successful TryPost destinations with imported native posts. It-uses two modes:--- **Bar:** horizontal total per social account across the entire selected- range.-- **Stacked Bar:** publication count over time, with one colored segment per- social account in each time bucket.--The initial display mode is Stacked Bar. The time bucket is selected-automatically from the inclusive range length:--- up to 14 days: one bucket per day;-- 15 through 90 days: one bucket per week;-- more than 90 days: one bucket per calendar month.--The first and last weekly or monthly buckets may be partial when the selected-range begins or ends inside that period. Empty buckets are returned with zero-values so the time axis remains continuous.--One analytics publication counts as one post for its social account. For-example, one TryPost post successfully delivered to Instagram and X contributes-one count to each account, while one natively published Instagram post adds one-Instagram count. The metric is based on the reconciled destination/native-publication, not the parent TryPost post, so a partially successful-multi-network post counts only its successful destinations.--The Posts widget includes only the platforms included in analytics v1. It-excludes LinkedIn personal profiles, LinkedIn Pages, Telegram, Discord, and-Google Business Profile even when their TryPost destination publication-succeeded. For included platforms, it counts posts published from any TryPost-entry point, such as the app, API, MCP, or repurpose flows, plus native posts-discovered through the connected account. It excludes drafts, scheduled posts-that have not yet published, and failed or rejected destinations.--A retry that eventually succeeds counts once because the destination record is-counted once. Historical publications remain facts even if an account is later-deactivated or disconnected. Account snapshot metadata stored with the-destination is used for historical presentation when the live social-account-row is no longer available.--### Summary--The page includes one workspace-level Summary block with exactly five cards:--- **Posts:** reconciled TryPost and imported native analytics publications whose- provider publication timestamp falls inside the selected range.-- **Total Followers:** the follower total at the selected range's end date,- using the same eligibility rules as the follower widget.-- **Reactions:** the sum of the latest stored reactions for eligible analytics- publications inside the selected range.-- **Comments:** the sum of the latest stored comments for eligible analytics- publications inside the selected range.-- **Engagement Rate:** pooled engagement divided by pooled exposure for the- eligible analytics publications inside the selected range.--Cross-network labels are normalized for comparison. Reactions include native-likes, favorites, and reactions. Comments include native comments and replies-when the platform exposes replies as its comment-equivalent metric. The-underlying native name remains available in the post detail and tooltip.--Engagement follows the industry-standard model approved for this design. Each-platform collector normalizes the interactions that its API treats as-engagement, such as reactions, comments, reposts/shares, saves, and clicks when-available. Exposure uses the platform-appropriate impressions, reach, or views-denominator. The workspace rate is calculated from the pooled numerator and-pooled denominator, rather than averaging post percentages, so a low-exposure-post does not weigh the same as a high-exposure post.--A destination without a supported or valid exposure denominator is excluded-from Engagement Rate only. Its supported reactions and comments still-contribute to those cards. Unsupported metrics render as unavailable and are-never converted to zero.--Provider post metrics are cumulative. Historical range reports therefore-answer “how have posts published in this period performed as of their latest-collection,” not “how many reactions happened during this period.” Summary,-Top 5, Performance, and comparison tooltips state this explicitly; TryPost does-not infer a daily reaction timeline that providers did not return.--### Period comparison--Summary and Performance compare the selected inclusive range with the-immediately preceding range of equal length. For example, a 30-day selection-compares against the preceding 30 days. The comparison period is calculated-automatically and is not a second user-selectable range.--- Posts, Reactions, and Comments show percentage change.-- Engagement Rate shows the relative percentage change between the two pooled- rates.-- Total Followers shows the absolute follower change between the two period-end- totals, matching the reference design.-- When the previous value is zero or unavailable, the UI shows a neutral- unavailable/new-data state instead of infinity or a fabricated percentage.-- Partial historical coverage is disclosed in the tooltip and is not presented- as a complete comparison.--### Top 5 Posts--The page includes one Top 5 Posts block with a two-option toggle:--- **Reactions** is the initial ranking;-- **Comments** ranks the same eligible dataset by normalized comments.--The ranking unit is the reconciled analytics publication, not the parent post.-A parent sent to multiple social accounts may therefore appear more than once-when more than one destination qualifies. Imported native posts participate as-their own publication. Only publications inside the selected range participate.--Each card shows rank, normalized metric value, platform/account identity,-publication date, content type, excerpt, thumbnail when available, publication-origin, and actions to open the TryPost post or its public social URL when-supported. An imported native post has no edit action or fake TryPost post link.-Ties are resolved by newest provider publication timestamp and then by stable-analytics-publication id so the order does not jump between requests.--A destination whose selected ranking metric is unsupported is excluded from-that ranking. Fewer than five cards are shown when fewer than five eligible-destinations have a real value. An empty state replaces the list when none do.--### Performance--The page includes one Performance table with one row per social account that has-an eligible TryPost or imported native publication in the selected range.-Multiple accounts on the same network remain separate rows.--The fixed first-version columns are:--- Channel;-- Posts;-- Reactions;-- Comments;-- Engagement Rate.--Posts use the local reconciled analytics-publication count. The other columns-aggregate the latest stored post-performance observations using the same-normalization and pooled-rate rules as Summary. Each supported numeric column-can be sorted, and its current value includes the equivalent-period comparison-when a valid comparison exists.--When a network or content type does not expose a metric, the cell shows an-unavailable marker rather than zero. Historical account snapshot metadata keeps-rows presentable after an account is disconnected or deleted.--These are exactly the three additional reporting blocks in v1: Summary, Top 5-Posts, and Performance. More cards, ranking modes, or configurable Performance-columns require a later product decision.--### Individual post analytics--For platforms included in analytics v1, the existing analytics area inside each-published post is part of this same delivery. It must stop fetching provider-metrics during the page request and must stop treating the five-minute Redis-entry as the metric source. Destinations on excluded platforms show no analytics-block.--Imported native posts open a read-only analytics detail using the same metric-components and observation contract. Every detail view displays an origin label:-`Published via TryPost` for a matched TryPost destination, or `Published on-<Platform>` for an imported native publication. Origin is stored data, not-inferred from the presence of a local caption or URL.--The post-performance pipeline collects through queued jobs and persists through-one observation writer. The individual post page, REST API, MCP, Summary, Top 5-Posts, and Performance all read the same latest persisted observation for each-reconciled analytics publication. Redis is not a source of truth for post-analytics; a-database-query cache may be added later only if profiling proves it useful.--The individual post page is richer than the cross-network reporting blocks. It-shows every persisted metric supported by that platform and content type,-grouped into common engagement, exposure, and video-retention sections. It also-shows when the metrics were last collected and whether the value is actual,-estimated, stale after a failed refresh, experimental, or unsupported.--The response contract uses stable metric keys and explicit units. Translated-labels are presentation only and are never stored as metric identity. An-unsupported metric is omitted or marked unavailable; an API error must not-replace the most recent successful value with zero.--### Industry per-post reference audit--Industry reference documentation for sent posts and insights provides the following UX and-normalization reference for individual posts. It is a discovery catalog, not-proof that TryPost's credentials, scopes, account type, or current API version-can retrieve every value. Each collector still requires verification against-the network's official API documentation before implementation.--| Channel | Per-post metrics exposed or named by the industry reference |-| --- | --- |-| Instagram Professional | Reactions/likes, comments, reposts/shares, views or impressions, reach, saves, follows, and engagement rate; availability varies between Feed, Reel, and Story |-| Facebook Page | Reactions, comments, shares/reposts, clicks, reach, views, impressions where still returned, and engagement rate; Group analytics are excluded |-| X/Twitter | Reactions/likes, replies/comments, reposts, quotes, clicks, impressions on the Sent surface, and a derived engagement rate |-| LinkedIn Page | Reactions, comments, reposts/shares, impressions, engagement rate, and for video: views, total watch time in minutes, and unique viewers |-| LinkedIn personal profile | Reactions, comments, reach, impressions, video views, and engagement rate; reliable repost counts are not available |-| Pinterest business | Reactions, comments, saves, clicks, impressions, views, and engagement rate where a valid exposure value exists |-| Mastodon | Favorites/reactions, replies/comments, and reblogs/reposts |-| TikTok | Reactions/likes, comments, shares/reposts, views, reach, and engagement rate |-| YouTube | Reactions/likes, comments, video views, shares in aggregate reporting, and a derived engagement rate where one can be calculated |-| Threads | Reactions/likes, comments/replies, reposts, quotes, views, and engagement rate |-| Bluesky | Reactions/likes, replies/comments, reposts, quotes, and a derived engagement rate |--The industry reference does not provide this per-post reference for Telegram, Discord, or-Google Business Profile, and it does not expose post analytics for Instagram-Personal accounts or Facebook Groups. Together with the product decision for-this release, that absence keeps Telegram, Discord, and Google Business Profile-outside analytics v1. Existing locally available reactions, replies, or account-counts for those networks are not promoted into the new analytics surfaces.--Reference product surfaces are not internally identical. Sent posts, the new-Insights product, and the retiring Analyze product can expose different metrics-and historical windows. For example, reference tools document X impressions in Sent-posts while also saying its Insights visibility view has no X impressions or-views. TryPost records the provider metric identity, source, time basis, and-formula so a value is never promoted merely because another reference surface-lists it.--The industry normalization vocabulary is useful and is adopted for cross-network-presentation only:--- `Reactions` covers native likes, favorites, and reactions;-- `Comments` covers comments and reply-equivalents;-- `Reposts` covers retweets, reblogs, reshares, and reposts;-- native names and raw metric identities remain visible in post detail;-- engagement rate must disclose whether it is provider-returned or derived,- plus its interaction numerator and exposure denominator.--Compared with the existing request-time TryPost collectors, the audit produces-the following implementation inventory. A reference-only metric is a candidate to-verify, not permission to invent or request an undocumented field.--| Channel | Existing TryPost per-post collector | Candidate gap to verify |-| --- | --- | --- |-| Facebook | Feed: impressions, reach, likes, clicks; Story: impressions, reach, interactions, reactions, replies, shares; Reel/video: plays, reactions, interactions | Feed comments/shares and richer Reel actions exposed by current Meta APIs |-| Instagram | Reach, views, likes, comments, shares, saves, replies, or total interactions depending on content type | The expanded Feed/Reel/Story catalog below |-| X/Twitter | Impressions, likes, retweets, replies, quotes, and bookmarks | Click metrics and their access level |-| LinkedIn Page | Impressions, clicks, likes, comments, and shares | Deferred to v2: provider engagement rate plus video views, watch time, and unique viewers |-| LinkedIn personal profile | Likes and comments | Deferred to v2: impressions, reach, reliable video views, and derived engagement inputs under newly approved scopes |-| Pinterest | Impressions, saves, Pin clicks, outbound clicks, and video views | Lifetime reactions/comments, rates, audience values, and video-retention metrics described below |-| Mastodon | Favorites, replies, and reblogs | No reference-identified basic metric gap |-| TikTok | Views, likes, comments, and shares | Reach is a reference candidate but is unavailable in TryPost's currently approved Display API fields |-| YouTube | Views, total watch time, average view duration, likes, comments, and shares | Engaged views, average percentage viewed, and subscriber change described below |-| Threads | Views, likes, replies, reposts, and quotes | No reference-identified basic metric gap |-| Bluesky | Likes, replies, reposts, and quotes | No reference-identified basic metric gap |--LinkedIn rows above are v2 research only. They are not part of the v1 collector-or persistence scope. Telegram, Discord, and Google Business Profile are omitted-from the implementation inventory because they are excluded from analytics v1-and have no planned analytics v2 in this design.--### Content-specific metric catalog--The initial content-type analysis establishes the following catalog. It is the-minimum that the platform collectors should request and persist when supported-by the connected account, login type, API version, and media type.--| Content type | Metrics for the individual post page | Current TryPost gap |-| --- | --- | --- |-| Instagram feed | Views, reach, likes/reactions, comments, shares, saves, reposts, total interactions, follows, profile visits, and profile activity | The current collector omits views, reposts, follows, profile visits, and profile activity |-| Instagram Reel | Views, reach, likes/reactions, comments, shares, saves, reposts, total interactions, total watch time, average watch time, and skip rate when returned | The current collector already has views/reach/basic engagement but omits interactions, reposts, watch-time metrics, and skip rate |-| Instagram Story | Views, reach, replies, shares, reposts, follows, profile visits/activity, link clicks, and navigation breakdown | The current collector only requests views, reach, and replies |-| YouTube video or Short | Video views, engaged views, watch time, average view duration, average percentage viewed, likes/reactions, comments, shares, subscribers gained, and subscribers lost | The current collector already has views, watch time, average duration, likes, comments, and shares, but omits engaged views, average percentage viewed, and subscriber change |-| TikTok video | Views, likes, comments, and shares | The current Display API collector already exposes the complete performance set available to this integration; video duration is metadata, not watch time |-| Pinterest image Pin | Impressions, saves, comments, reactions, engagements, engagement rate, save rate, Pin clicks/rate, outbound clicks/rate, profile visits, follows, total audience, and engaged audience | The current collector has impressions, saves, Pin clicks, and outbound clicks, but omits the remaining native and lifetime metrics |-| Pinterest video Pin | Every applicable image-Pin metric plus video views, average video play time, 10-second plays, plays to 95%, and total play time | The current collector only adds basic video views and omits the richer video-retention metrics |--Instagram Reel total watch time is displayed in minutes and average watch time-in seconds, matching the reference UI, while persistence stores both as integer-milliseconds to avoid rounding drift between providers and displays. Metrics-that Meta marks estimated or in-development, currently including Reel reach, watch time, views, total-interactions, and skip rate as applicable, preserve that precision/stability-metadata for tooltips.--Meta documents that Instagram insight values can lag by up to 48 hours. A-successful response with an absent or not-yet-populated metric is therefore not-converted to measured zero. The read model keeps the last successful value and-exposes its collection time so the UI can distinguish fresh, delayed, and stale-data. Provider retention does not control TryPost retention: once collected,-the observation remains stored under TryPost's permanent-history policy.--Instagram Reel engagement rate uses the normalized interactions divided by-reach when both are available. This matches the reference behavior and avoids-using repeated views as though they were unique people.--The Meta collector must parse both `values[].value` and `total_value.value`, and-must preserve requested breakdowns such as Story navigation actions. It splits-incompatible or experimental metric families into separate provider requests:-one rejected metric must not blank every otherwise supported metric for the-post.--Instagram cross-posted and Facebook-only view metrics are conditional: they are-stored and displayed only when the Reel was actually shared or recommended to-Facebook and the API returns them. They do not replace Instagram views.--The approved TikTok Display API does not expose total watch time, average watch-time, completion rate, or retention. Those values must remain unavailable-rather than being inferred from view count and video duration.--YouTube's per-video report already supports the retention metrics needed for-Shorts. The collector expands its current query rather than introducing a-second Shorts-specific API path.--YouTube Analytics data typically lags by 48–72 hours. When a video report has-headers but no processed row, the collector uses `videos.list?part=statistics`-for current lifetime views, likes, and comments. It stores only fields the Data-API actually returns; missing values are not zero. Later scheduled collections-can add watch time, retention, shares, and subscriber metrics once the Analytics-report is available.--On the individual YouTube post, the cross-network `Reactions` label maps to the-native `likes` metric, `Comments` maps to `comments`, and `Video Views` maps to-`views`. The YouTube Analytics API does not return a native per-video engagement-rate, so that native field is unavailable rather than fabricated. A normalized-TryPost engagement rate used by Summary or Performance is a separately labelled-derived value with its numerator and `views` denominator preserved; it must not-be represented as a provider-returned YouTube metric.--Pinterest uses two complementary sources. The Pin Analytics endpoint provides-date-range metrics, including impressions, saves, engagement, clicks, rates,-and video performance. `GET /pins/{pin_id}?pin_metrics=true` provides rolling-and lifetime Pin metrics, including total comments and total reactions. The-collector combines both into one idempotent observation while retaining each-metric's time basis (`range`, `rolling_90_day`, or `lifetime`). A lifetime value-must never be presented as though it occurred entirely inside the selected-dashboard range.--Pinterest's native engagement rate remains the provider-defined engagements-divided by impressions. Saves, comments, and reactions are displayed as their-own metrics; comments and reactions are not silently added to the provider's-engagement numerator unless Pinterest includes them in the returned native-definition. This keeps the reference labels without changing their meaning.--Instagram Stories require an exception to the normal 30-day refresh window:-their media insights are generally available for only 24 hours. A queued-collection is scheduled during the Story lifetime, the `story_insights` webhook-is enabled when the integration supports it, and a final collection runs-shortly before expiry. Webhook deliveries and scheduled jobs persist through the-same idempotent observation writer. The normal once-daily sweep alone is-insufficient because it can miss the availability window. Stored Story metrics-remain available after the provider stops serving them. Privacy-threshold or-"not enough viewers" responses mean unavailable, not measured zero and not a-reason to erase a previous observation.--### Date range--The existing analytics range date picker remains the shared page filter for the-Summary, follower chart, Posts widget, Top 5 Posts, and Performance.--- `minDate` is the earliest follower snapshot or reconciled TryPost/native- analytics publication on an included v1 platform available in the workspace.-- `maxDate` is the latest follower snapshot or reconciled TryPost/native- analytics publication on an included v1 platform available in the workspace.-- The picker cannot select a range wholly outside those bounds.-- All chart modes and the total use the same selected range.-- A social account connected after the selected start date begins when its own- data begins; no pre-connection values are invented.-- A widget shows its own empty state when the selected range contains no data- for that metric.-- With neither follower snapshots nor analytics publications, the picker is- disabled and the page shows an analytics-empty/import-pending state.--Historical data for a disconnected or deactivated account is retained. Its-line ends on the last day for which it was eligible; it remains visible when-the selected range overlaps that history.--## Collection architecture--```text-Laravel scheduler (daily, UTC)- -> native-post discovery dispatch-only command- -> one queued incremental discovery job per eligible social account- -> platform-owned-post paginator- -> reconciled analytics publication catalog- -> post-performance jobs for new publications-- -> follower dispatch-only command- -> one queued job per eligible social account- -> platform follower collector- -> normalized follower observation- -> persistence boundary-- -> post-performance dispatch-only command- -> one queued job per eligible reconciled analytics publication- -> platform post-metrics collector or trusted local metric source- -> normalized post-performance observation- -> persistence boundary-- -> Instagram Story lifecycle jobs and `story_insights` webhook- -> same idempotent post-performance observation writer--End-of-day finalizer- -> identifies eligible accounts without a successful observation- -> carries forward the most recent known value when one exists--Account connection- -> immediate follower collection- -> resumable native-post backfill through the preceding 365 days-```--### Scheduler and dispatcher--The scheduled command starts at `02:00 UTC`, runs with-`withoutOverlapping()` and `onOneServer()`, reads eligible accounts in bounded-chunks, and only dispatches jobs. It never calls a social API itself.--An account is eligible when it:--- belongs to a workspace;-- uses an included platform;-- is active;-- is connected and has the platform metadata required by its collector.--Each account gets an independent job on a dedicated analytics queue. The job's-logical uniqueness key is follower metric + social account + UTC observation-date. Re-dispatching the same logical job is safe and cannot create a second-daily value.--Connecting a supported account dispatches an immediate first follower-collection and the resumable native-history backfill so the workspace does not-wait for the next daily sweep. These jobs follow the same isolation,-idempotency, and widely spaced retry principles as their scheduled counterparts.-Backfill jobs run in bounded pages and re-dispatch the next page rather than-holding one worker for the entire year.--### Collector contract--Each platform-specific collector has one responsibility: fetch the current-follower-equivalent value for one social account and return a normalized-observation. A collector does not authorize workspace access, aggregate totals,-or know the database schema.--The normalized result contains, at minimum:--- metric identity (`followers` at this stage);-- integer value;-- observation date in UTC;-- actual versus carried-forward provenance;-- exact versus approximate precision;-- platform response timestamp when the API provides one.--This contract is intentionally independent of the physical persistence model-so future metrics can reuse the collection pipeline after their data shapes are-known.--### Retry policy--Transient HTTP failures, connection failures, server errors, and rate limits-must retry far apart within the same UTC day. The target attempt windows are:--- 02:00-- 06:00-- 10:00-- 14:00-- 18:00-- 22:00--The actual delayed execution may occur later under queue load. When a platform-returns a longer valid retry time, the job respects that time instead of the-four-hour default, provided the attempt still belongs to the observation day.--Permanent authentication or permission rejection from an analytics endpoint is-not retried six times as a transient error and does not write zero as a-follower value. It also does not by itself mark the entire social account-token-expired: an analytics scope can be missing while publishing still works.-The independent daily connection verifier owns global account-health changes.--An attempt exits without writing when another attempt has already persisted an-actual observation for the account and date.--### End-of-day fallback--After the final attempt window, a finalizer covers eligible accounts that had-no successful API observation that day:--- If an earlier valid follower value exists, copy it into the current date and- mark it as carried forward / estimated.-- If the account has never produced a valid follower value, no value can be- invented; it remains unavailable until a collection succeeds.-- A disconnected or deactivated account is not eligible for carry-forward.-- A carried-forward value may itself be carried into a later unavailable day,- while retaining provenance that the newest value is not a fresh API- observation.--This keeps charts and workspace totals continuous during a platform outage-without misclassifying a repeated value as a successful API fetch.--## Post-performance collection--The complete supported post metric catalog, including reactions, comments,-exposure, engagement inputs, and video retention, must not trigger social API-calls while `/analytics` or an individual post is rendering. Metrics are-refreshed in queued jobs and stored through the same idempotent persistence-boundary as follower observations.--The daily dispatcher selects reconciled TryPost/native analytics publications-that have a native post id, use a platform included in analytics v1, have a-connected account with the required access, and remain inside their refresh-window. LinkedIn personal profiles, LinkedIn Pages, Telegram, Discord, and-Google Business Profile are never selected:--- X destinations: through 20 days after publication;-- every other supported destination: through 30 days after publication.--Instagram Stories use their separately documented within-24-hours schedule-instead of the 30-day sweep.--There is no free-versus-paid retention rule in TryPost. All workspaces use the-same collection windows. The windows limit external API work only; all values-already collected are retained permanently.--Each eligible analytics publication gets an independent queued job so one-failing API or post cannot block another. The logical uniqueness key is-post-performance + analytics publication + UTC collection date. The job-normalizes only metrics genuinely returned for that network and content type,-preserving unsupported separately from a measured zero.--Post-performance values are cumulative totals for that analytics publication as-of the collection timestamp. Summary, Top 5 Posts, and Performance use the-latest stored observation for each publication selected by its provider-publication date; they do not add daily snapshots together.--The normal daily run collects once per UTC day. The final eligible day performs-one final collection before the destination becomes inactive for scheduled-refresh. Transient and rate-limit failures use the same widely spaced, same-day-retry approach as follower collection. If the final-day collection fails, the-latest successful observation remains available with its collection timestamp;-the system does not replace it with zero.--Metrics already maintained from trusted local events, such as webhook-backed-reaction metadata, may be normalized from that local source without making a-redundant provider request. An included v1 platform without a supported post-metric may still contribute its locally known Posts count and show the metric as-unavailable. An excluded v1 platform contributes neither posts nor metrics.--## Persistence design--The physical design uses four tables: three analytics fact/catalog tables and-one operational synchronization table. This is the minimum that keeps account-snapshots, publication identity, cumulative publication metrics, and resumable-job state independent. Combining those lifecycles would either lose history,-reintroduce Redis as durable state, or produce a sparse table that cannot be-aggregated portably on both PostgreSQL and MySQL.--Database enum types are not used. Enum-backed values are stored in string-columns and cast through PHP enums so new providers and metrics do not require-engine-specific enum migrations.--The reviewed four-table split is:--| Table | Cardinality and responsibility | Why it is separate |-| --- | --- | --- |-| `analytics_account_daily_snapshots` | One account/day follower fact | Time-series values and carry-forward provenance |-| `analytics_publications` | One account/provider-post identity | Reconciles TryPost and externally discovered posts once |-| `analytics_publication_daily_snapshots` | One publication/day cumulative metric set | Atomic metric history and portable ranking projections |-| `analytics_sync_states` | One live account/import collector checkpoint | Cursor/high-water coordination only; deleted with the account |--This is the smallest design that preserves strict keys for each different-cardinality. It intentionally does not introduce a fifth shadow-account table,-does not store workspace totals, and does not mix operational cursors into fact-rows.--### Daily account snapshots--`analytics_account_daily_snapshots` stores one effective observation per-workspace, immutable social-account key, and UTC date. It contains:--- UUID primary key;-- immutable `workspace_id` ownership;-- nullable `social_account_id` foreign key for the currently connected row;-- non-null `social_account_key`, initially copied from the originating- social-account UUID and retained after that row is deleted;-- provider identity snapshot (`network` plus `platform_user_id`) used to resolve- and reuse the historical key when the same provider identity reconnects;-- platform string cast to the existing `SocialAccount\\Platform` enum;-- immutable account presentation snapshots;-- `snapshot_date`;-- nullable `followers_count` bigint;-- nullable JSON `metrics` for future account-level metrics that are not yet- promoted to first-class aggregate columns;-- actual or carried-forward provenance;-- exact or approximate precision;-- provider observation time and collection time.--The unique key is workspace + social-account key + snapshot date. Platform is a-dimension, not account identity: two Instagram accounts in one workspace remain-two independent series. Cross-network totals sum the latest eligible row for-each social-account key. `social_account_id` is used while the connection-exists; `social_account_key` and the presentation snapshots preserve truthful-historical series after deletion. A connection/reconnection resolver first-looks for an existing key with the same workspace + network + platform user id;-only a genuinely new identity starts with the current social-account UUID.--### Reconciled publication catalog--`analytics_publications` stores one publication per workspace, immutable-social-account key, platform, and provider post id. It contains:--- UUID primary key and immutable `workspace_id` ownership;-- nullable live `social_account_id` plus non-null historical- `social_account_key`;-- nullable unique `post_platform_id` for a TryPost-owned destination;-- platform, normalized network, provider account id, provider post id, provider- publication time, normalized content type, and provider content type;-- origin `trypost` or `external`;-- permalink, excerpt, preview metadata, and immutable account presentation- snapshots;-- available, deleted, or unavailable state;-- first-seen, last-seen, and provider-sync timestamps;-- JSON provider metadata that is not used for cross-network aggregation.--`external` means only that TryPost did not publish the record. Provider APIs do-not reliably distinguish a manual native-app post from a post created by-a third-party client, so the UI says `Published on <Platform>` rather than-claiming it was posted manually. A matching `post_platform_id` proves TryPost-origin and produces `Published via TryPost`.--The unique provider identity is workspace + social-account key + network +-provider post id. Network, rather than login variant, prevents the same-Instagram media from duplicating when an identity reconnects through direct-Instagram instead of Facebook login. A TryPost destination and external-discovery reconcile onto that identity; `trypost` origin wins and the-publication is counted once.--### Daily publication snapshots--`analytics_publication_daily_snapshots` stores at most one cumulative-observation per analytics publication and UTC date. Repeated successful-collections on the same date merge into that row under a database row lock-instead of creating additional facts or blanking a metric family collected by-another provider request. It does not duplicate `workspace_id`; workspace-ownership is obtained through the parent analytics publication, preventing an-inconsistent child/parent tenant pair.--Its portable aggregate projections are nullable big integers for-`reactions_count`, `comments_count`, `shares_count`, `saves_count`,-`views_count`, `impressions_count`, `reach_count`, `engagement_count`,-`exposure_count`, `watch_time_milliseconds`, and-`average_watch_time_milliseconds`, plus nullable `exposure_kind`. A null means-unavailable; a numeric zero means measured zero. Milliseconds are the canonical-duration unit and the UI converts them to minutes or seconds.--The same row has a JSON metric catalog for provider/content-specific values.-Each JSON entry uses a stable enum-backed metric key and retains numeric value,-unit, provider metric identity, lifetime/range/rolling time basis,-nullable period start/end for range metrics, exact/estimated/experimental-precision, and availability. Cross-network queries use the first-class columns;-the JSON catalog powers the richer individual-post detail. This hybrid avoids-both engine-specific JSON aggregation and an EAV row explosion.--Imported historical publications receive a real baseline observation collected-at import time. The system does not fabricate daily metric history between the-publication date and that baseline.--### Synchronization state--`analytics_sync_states` is deliberately a small operational checkpoint table,-not a general log of every analytics job. It exists only for workflows whose-progress cannot be inferred from fact rows: the finite 365-day publication-backfill and continuing publication discovery. Daily follower success is-represented by an account snapshot, publication-metric success by a publication-snapshot, and attempts/retries by the queue and Horizon; duplicating those in a-sync-state row would create competing sources of truth.--Each row belongs to one live `social_account_id` with `cascadeOnDelete()` and-one collector (`publication_backfill` or `publication_discovery`). Its columns-are: UUID primary key, non-null social-account foreign key, collector, status,-nullable JSON `checkpoint`, `target_since`, `oldest_reached_at`,-`high_watermark_at`, `last_success_at`, sanitized `last_error_category`, and-timestamps. The unique key is social account + collector. Workspace, platform,-historical account key, next retry, attempt count, and raw error message are not-duplicated here.--The checkpoint is the one safe JSON boundary for sync control: provider cursor-shapes vary, it is never filtered or aggregated by SQL, and exactly one-collector owns each row. The job locks that row before reading or advancing the-checkpoint. Keeping these rows separate from `social_accounts.meta` prevents-unrelated collectors from overwriting one shared JSON object or locking the-entire account row.--Operational state does not need to survive deletion. Historical facts remain-in the three analytics tables; deleting the live account removes its obsolete-checkpoint. Reconnecting the same provider identity receives fresh operational-state, while the identity resolver reuses the prior `social_account_key` found-in account snapshots or publications and provider-id uniqueness makes the-restarted import idempotent.--Backfill and discovery use separate rows and lifecycles. Discovery does not run-while backfill is pending or running. Once backfill reaches a terminal state-(`complete`, `provider_limited`, `partial`, or `failed`), discovery may keep new-content current while a partial backfill is retried independently.--The X user-post timeline is [limited to 3,200 recent posts](https://docs.x.com/x-api/posts/timelines/introduction). The backfill checkpoint tracks the committed X page count. If the timeline ends at that cap before reaching the 365-day cutoff, coverage is `provider_limited` (`x_timeline_3200`), not complete. Cursor retries preserve the count; a restart from page one resets it. This does not require another table or X API request.--For every page, a job captures the locked checkpoint and row version, releases-the transaction before the provider request, then locks the row again. It may-upsert publications idempotently, but advances the checkpoint only when the-captured version still matches; a stale duplicate can never move the cursor-backward.--### Historical identity limitation at rollout--Existing `post_platforms` rows null `social_account_id` when an account is-deleted and retain only presentation fields, not the provider account id or the-original social-account UUID. Therefore pre-rollout orphan destinations cannot-be assigned to a historical account without guessing from a mutable username.-The local catalog backfill imports only destinations that still have a live-social account and records the omitted-orphan count in rollout logs. It must not-invent an account key or merge rows by username. After rollout, every analytics-publication is written while the account identity is available and remains-historically addressable after later deletion.--This approved schema must support:--- workspace-scoped queries;-- social-account breakdown;-- one effective follower value per account and UTC date;-- idempotent writes;-- actual versus carried-forward provenance;-- exact versus approximate precision;-- earliest/latest available workspace dates;-- retaining history after an account is disconnected;-- efficient aggregation at a selected end date;-- latest supported post-performance values per destination;-- permanent retention after a destination leaves its refresh window;-- unsupported versus measured-zero post metrics;-- stable metric keys and units independent of the active UI locale;-- content-type-specific metrics without sparse schema assumptions;-- provider and collection timestamps needed to disclose freshness;-- a reconciled analytics-publication identity spanning TryPost destinations and- imported native posts without duplicating a native post id;-- publication origin, provider publication time, content excerpt, permalink,- content type, presentation metadata, and import coverage state;-- resumable per-account provider cursor/high-water checkpoints;-- efficient workspace, publication-range, account, and ranking aggregations.--Workspace totals are derived from account observations and are not stored as a-second source of truth.--The Posts widget does not require daily count snapshots. Its source of truth is-the reconciled analytics-publication catalog: existing successful TryPost-destinations plus imported native posts. A counted record must belong to the-current workspace, use a platform included in analytics v1, have a provider-publication timestamp inside the selected range, and represent one unique-social-account/native-id pair. The concrete persistence and reconciliation-queries must work on PostgreSQL and MySQL.--## Read path--`/analytics` reads only local persisted data. It performs no request-time-social API calls for any analytics block.--The server response supplies:--- the workspace's available date bounds;-- the effective selected range after validation;-- the follower total at the range end;-- one daily series per social account;-- account identity and platform presentation metadata;-- actual/carried-forward and exact/approximate provenance required for- truthful tooltips;-- reconciled TryPost/native publication totals per social account;-- zero-filled publication buckets and per-account values for the automatically- selected daily, weekly, or monthly resolution;-- current and previous-period Summary values;-- the two deterministic Top 5 rankings;-- Performance rows and comparisons per social account;-- the complete latest metric set for each analytics publication on the- individual post page, REST API, and MCP;-- publication origin, provider publication time, permalink, content type, and- presentation metadata required by native-import detail cards;-- native-history coverage per social account, including progress, oldest- covered publication date, last successful sync, and complete,- provider-limited, partial-failure, or running state;-- freshness and availability metadata needed for tooltips and unavailable- states.--The frontend derives Bar and Growth from this normalized response instead of-requesting separate endpoints. Large date ranges may later be downsampled, but-daily resolution is the source resolution and is sufficient for this first-version.--The server aggregates the Posts dataset at the chosen bucket resolution and-returns both bucketed and range-total values. Every analytics-publication row-has its own immutable workspace ownership, including imported native posts-that have no parent TryPost post. A social-account id from the request is never-trusted as the tenancy boundary.--## Failure handling and observability--Failures are isolated per social account. One platform outage cannot prevent-other account jobs from succeeding.--Operational visibility must distinguish:--- successful actual observation;-- transient failure awaiting retry;-- rate-limited attempt and next eligible attempt time;-- permanent authentication/permission rejection;-- successful carried-forward fallback;-- unavailable account with no historical value;-- finalizer failure;-- post-performance collection success;-- post-performance metric unsupported;-- post-performance retry or permanent collection failure;-- post-performance publication leaving its refresh window with a final stored- value.-- native-history backfill start, page progress, completion, and oldest covered- publication date;-- native-history backfill or incremental-discovery retry and permanent- failure;-- provider-limited history distinguished from a complete 365-day import;-- native publication reconciliation and duplicate suppression.--Logs include workspace, social account, platform, observation date, attempt,-and error category, but never access tokens or raw sensitive responses.--The system must make it possible to alert on workspaces that repeatedly rely on-carried-forward values, even though defining an alerting product is outside-this first delivery.--## Account lifecycle--- **Connected:** dispatch an immediate first collection.-- **Connected on an included v1 platform:** also dispatch the resumable native- post-history backfill without delaying the connection response.-- **Active and connected:** participate in the daily follower,- post-performance, and native-post discovery sweeps.-- **Deactivated:** stop new collection and fallback; preserve history; exclude- from follower totals after its last eligible date; preserve imported and- TryPost publication history for ranges in which it exists.-- **Disconnected/deleted:** stop collection and fallback; preserve historical- observations and imported publications even if the account row is later- removed. Nullable live foreign keys plus immutable `social_account_key` and- presentation snapshots retain that identity.-- **Reconnected as the same provider identity:** reuse the historical- `social_account_key` without rewriting earlier observations, create fresh- operational checkpoints, and restart the idempotent native import. Existing- publications deduplicate by historical account key + provider post id.-- **New identity:** begins a new series even when its username matches an older- disconnected account.--## Security and privacy--- Analytics authorization follows the current workspace membership and policy- model.-- A social account id from another workspace must never affect collection or- read results.-- API tokens remain on `social_accounts` and are never copied into analytics- storage or job logs.-- Platform data-retention terms must be checked as each collector is- implemented; every network-specific constraint is recorded in its collector- tests and coverage status.--## Testing strategy--### Collector contract tests--Each included platform needs tests for:--- successful exact or approximate follower parsing;-- missing/null metric handling;-- malformed response handling;-- rate-limit classification;-- transient server/connection classification;-- permanent authentication/permission classification;-- no accidental conversion of failure or null to zero.--HTTP calls are faked. Tests must not call live social APIs.--Post-performance collector tests additionally cover:--- native-to-normalized reaction and comment names;-- cumulative metrics stored as one observation rather than summed across days;-- engagement numerator and exposure denominator mapping;-- content-type-specific metric availability;-- Instagram Reel watch-time units and experimental/estimated flags;-- YouTube Short watch time, average duration, average percentage viewed, and- subscriber-change mapping;-- YouTube post labels map likes to Reactions and views to Video Views while the- unavailable native engagement rate remains distinct from TryPost's derived- normalized rate;-- TikTok never fabricating unsupported retention metrics;-- Pinterest saves, comments, reactions, impressions, and native engagement- rate retain their distinct metric identities and time bases;-- Pinterest video Pins map average play time, 10-second plays, 95% plays, and- total play time with explicit units;-- unsupported, missing, malformed, and measured-zero distinctions.--### Queue and scheduling tests--- The daily command dispatches one job per eligible account and none for- LinkedIn, Telegram, Discord, Google Business Profile, inactive, disconnected,- or unsupported accounts.-- Jobs are isolated and idempotent by account, metric, and date.-- Retry delays cover the same UTC day and stop after a successful observation.-- Platform-provided retry timing is respected.-- A permanent analytics authentication or permission failure does not follow- the transient retry loop or invalidate an otherwise publishable account.-- Immediate collection is dispatched after a supported account is connected.-- Connecting an included v1 account dispatches a native-history backfill and- returns without waiting for that backfill to finish.-- Rollout dispatches bounded backfills for existing eligible accounts without- requiring reconnection and without placing every workspace in one job.-- No native-history backfill or incremental-discovery job is dispatched for- LinkedIn personal profiles, LinkedIn Pages, Telegram, Discord, or Google- Business Profile.-- Native-history pagination stops at the 365-day cutoff only for an ordered- provider feed; otherwise it follows cursors to provider exhaustion or a- documented provider limit and records which condition ended the import.-- A bounded page can re-dispatch continuation work without holding one worker- for the entire backfill.-- Cursor and high-water checkpoints resume safely after transient failure.-- Deleting an account cascades only its operational checkpoints; reconnecting- the same provider identity creates fresh checkpoints while deduplicating- already imported facts against the reused historical account key.-- Concurrent page jobs compare the captured checkpoint version and cannot move- a cursor backward.-- Daily native discovery overlaps the last completed window and remains- idempotent when a provider returns the same page or a late post twice.-- Backfill and discovery failures for one social account do not block any other- account.-- `withoutOverlapping()` and `onOneServer()` remain present on the schedule.-- Post-performance jobs are dispatched only for reconciled analytics- publications with a usable native id and access on an included v1 platform.-- No post-performance job is dispatched for LinkedIn personal profiles,- LinkedIn Pages, Telegram, Discord, or Google Business Profile.-- X destinations remain eligible through day 20; other supported destinations- remain eligible through day 30.-- The final eligible day receives a final collection and older destinations no- longer create provider jobs.-- Collection-window expiry never deletes an already stored value.-- A newly imported publication still inside the refresh window joins the- normal daily metric collection.-- An older backfilled publication receives at most the planned baseline metric- collection and is not enrolled in perpetual refresh.-- Unsupported metrics remain distinct from measured zero.-- Instagram Story jobs collect while insights are available and perform a- final pre-expiry collection even when the normal daily sweep would miss it.--### Fallback tests--- The finalizer carries forward the last known value after all daily attempts- fail.-- Carried-forward provenance is preserved.-- No historical value means no fabricated snapshot.-- Deactivated and disconnected accounts are not carried forward.-- A successful observation is never overwritten by the finalizer.-- Importing historical posts never creates historical follower observations or- follower carry-forward values before the first real collection.--### Native publication reconciliation tests--- Repeated provider pages create one analytics publication for each unique- workspace, social account, platform, and native post id.-- A native id matching an existing successful TryPost destination reconciles- to one analytics publication and retains `trypost` as its origin.-- A TryPost destination that receives its native id after discovery reconciles- with the imported publication rather than creating a duplicate.-- Reconnecting the same identity resumes the existing catalog; a genuinely new- platform identity starts a separate catalog even when the username matches.-- Pre-rollout TryPost destinations already orphaned from their social account- are reported and skipped instead of being guessed or grouped by username.-- Imported publications never create fake `Post` or `PostPlatform` lifecycle- records and cannot be edited, deleted, retried, or published from TryPost.-- The provider publication timestamp, rather than discovery time, controls- range inclusion and aggregation.-- Expired or unavailable preview media falls back to a stable placeholder- without removing the imported publication or its metrics.--### Read and UI tests--- Every response is workspace-scoped.-- The total sums each eligible account once on the selected end date.-- Multiple accounts on one network remain separate.-- Date bounds reflect the workspace's actual stored history.-- Line, Bar, and Growth derive the expected values from the same dataset.-- Growth handles negative values and a zero baseline.-- A later-connected account does not receive invented earlier points.-- Historical series remain available after disconnect/deactivation.-- No-data workspaces receive the collection-pending state.-- LinkedIn personal profiles, LinkedIn Pages, Telegram, Discord, and Google- Business Profile never appear or contribute anywhere in analytics v1.-- The Posts Bar mode counts one reconciled TryPost/native analytics publication- per social account in the selected range.-- The Posts Stacked Bar mode selects daily, weekly, and monthly buckets at the- documented range thresholds and zero-fills missing buckets.-- A multi-network post contributes once to every successful destination on an- included v1 platform and nothing to excluded, failed, rejected, pending, or- future-scheduled destinations.-- A destination that succeeds after retries counts only once.-- Direct/native social-network posts are included after discovery even though- no TryPost publication record exists for them.-- Native imports appear incrementally while backfill is running, and the UI- exposes oldest-covered date, last sync, and complete, provider-limited,- partial-failure, or running coverage state without promising unavailable- history.-- Publications for every excluded v1 platform are absent from both Posts widget- modes, Summary, Top 5, and Performance.-- Post aggregation is workspace-scoped through immutable analytics-publication- ownership for both TryPost and native imports.-- Historical publications retain presentable account information after the- social account is disconnected or deleted.-- Summary contains exactly Posts, Total Followers, Reactions, Comments, and- Engagement Rate.-- Summary compares against the immediately preceding inclusive range of equal- length and handles zero, unavailable, and partial previous data safely.-- Engagement Rate pools normalized engagement and exposure rather than- averaging per-post percentages.-- Posts without a valid exposure denominator are excluded only from the rate.-- Top 5 ranks reconciled analytics publications deterministically by Reactions- or Comments, includes eligible native imports, and excludes unsupported- values.-- Imported Top 5 and detail cards show `Published on <Platform>`, while- reconciled TryPost publications show `Published via TryPost`; origin is read- from persisted provenance rather than inferred from missing relations.-- Imported publication cards expose no fake TryPost edit, retry, or publishing- action.-- Performance returns one row per social account, keeps duplicate-network- accounts separate, includes reconciled native publications, supports sorting,- and uses the same aggregation rules as Summary.-- The individual post page, REST API, and MCP return the same persisted latest- observation and make no provider request during reads.-- The individual post page exposes no analytics block for a destination on an- excluded v1 platform.-- The individual post page shows the content-type-specific catalog, canonical- units, freshness, and metric stability/provenance.-- Date-picker bounds expand to the earliest eligible imported provider- publication date as backfill progresses.-- Expired Redis entries cannot remove or change persisted post analytics.--Database-dependent tests run on PostgreSQL and MySQL after the persistence-design is approved and implemented.--## Considered and rejected--- **Calling social APIs from `/analytics`.** Slow, rate-limit prone, impossible- to trend reliably, and couples page availability to every provider.-- **One queued job per workspace.** A single slow or broken account delays the- whole workspace and makes retries unnecessarily broad.-- **Fast retry loops.** Follower totals tolerate delay; four-hour spacing gives- providers time to recover and protects API quotas.-- **Writing zero on failure.** Produces false losses and corrupts totals.-- **Silently using an old observation without provenance.** Keeps the UI full- but makes stale data indistinguishable from measured data.-- **Deleting history when an account disconnects.** Removes valid workspace- history and breaks historical comparisons.-- **Persisting workspace totals.** Duplicates account facts and risks drift.-- **One generic analytics table.** Account snapshots, publication identity,- cumulative publication metrics, and resumable cursors have different- cardinality and lifecycle. Combining them creates sparse rows and weak- constraints. The four-table hybrid is the minimum safe design.-- **A fifth `analytics_accounts` dimension table.** It would normalize repeated- identity/presentation columns and is defensible at warehouse scale, but every- fact would then need another join and the application would maintain a shadow- account lifecycle solely for analytics. The current four-table design keeps- the minimum table count while repeating only small immutable snapshots.-- **Putting collector cursors in `social_accounts.meta`.** Multiple collectors- would contend on one account row and could overwrite independent JSON- branches. One checkpoint row per collector gives a narrow lock and a unique- owner without turning sync state into a general job log.-- **Persisting sync state for follower and publication-metric jobs.** Their fact- snapshots already prove successful work, while queue/Horizon records attempts- and failures. Duplicating that status would create drift and extra writes.-- **Preserving sync-state rows after account deletion.** Checkpoints are- operational, not historical facts. Cascading them prevents dead work from- appearing resumable; a reconnect safely restarts against idempotent facts.-- **Guessing pre-rollout orphan identity from username.** Usernames can change- or be reused, and existing orphaned `post_platforms` lack the provider account- id. Skipping and reporting those rows is more truthful than merging unrelated- accounts.-- **JSON-only post metrics.** Cross-network ranking and aggregation would depend- on engine-specific JSON queries. Common aggregate fields are first-class- nullable columns; provider/content-specific metrics remain structured JSON.-- **An EAV row for every metric.** It would multiply row volume and joins for- every post card. One daily publication snapshot keeps the metric set atomic.-- **Including LinkedIn, Telegram, Discord, or Google Business Profile in v1.**- LinkedIn requires the separately vetted product for a coherent implementation;- the other three are outside the chosen product scope and lack an industry- per-post analytics reference. LinkedIn is deferred as a whole to v2; the- others require a new future product decision.-- **Keeping Posts limited to TryPost deliveries.** It would make a newly- connected workspace look empty and omit the user's best historical content.- A native-history importer gives Summary, Top 5, Performance, and individual- post analytics useful data immediately while preserving publication origin.-- **Counting parent posts.** One parent can target several accounts and can- partially fail, so the successful destination is the only accurate unit.-- **Persisting daily post-count snapshots.** Publication rows are immutable- facts in the reconciled catalog and can be aggregated for the selected range- without introducing a second source of truth.-- **Reusing `PollRepurposeSource` and `RepurposeItem` for analytics.** Repurpose- imports selected media for a publishing workflow, currently reads one page- of 25, and has activation-watermark and media-download semantics that do not- represent a complete, read-only analytics catalog. Only suitable low-level- provider clients and parsers may be extracted and shared.-- **Creating fake `Post` or `PostPlatform` rows for native content.** Those- records imply TryPost publishing ownership and would expose invalid edit,- retry, delete, and repurpose actions. Native content remains an analytics- publication with explicit origin.-- **Claiming one year of coverage unconditionally.** Providers can impose- shallower history, pagination, permission, or metric-retention limits. The- importer targets 365 days but reports the actual oldest covered date and a- provider-limited or partial state when needed.-- **Using one fixed Posts bucket size.** A fixed daily view becomes noisy over- long ranges, while a fixed weekly or monthly view hides useful short-range- detail.-- **Refreshing every imported historical post forever.** Engagement changes- slow after publication, while an unbounded daily job set would continually- increase API cost and rate-limit pressure. Older backfilled posts receive a- bounded baseline collection; the last stored result remains available after- the 20/30-day refresh window closes.-- **Applying plan-based analytics retention.** TryPost has no free analytics- tier in this design; collection and permanent local retention are consistent- for every workspace.-- **Averaging individual engagement rates.** It overweights posts with little- exposure. Pooling the engagement and exposure totals produces a weighted- workspace/account rate.-- **Treating unsupported metrics as zero.** Zero means the provider measured no- activity; unsupported means no measurement was available and must remain- visibly different.-- **Keeping the individual post page on request-time API calls and Redis.** It- would give the post page a different source and freshness model from Summary,- Top 5 Posts, Performance, REST, and MCP. All consumers must converge on the- persisted observation.-- **Reducing post persistence to the five cross-network fields.** That would- discard high-value, content-specific metrics such as Reel/Short watch time- and make the individual post page less useful than the provider data already- available to TryPost.-- **Inferring TikTok retention from duration and views.** Video length describes- the asset, not how long viewers watched it; the approved integration exposes- no retention metric.--## External references checked--- Meta Instagram Media Insights, updated September 11, 2026:- <https://developers.facebook.com/documentation/instagram-platform/reference/instagram-media/insights>-- YouTube Analytics metrics and channel report combinations:- <https://developers.google.com/youtube/analytics/metrics> and- <https://developers.google.com/youtube/analytics/channel_reports>-- YouTube Analytics data freshness and Data API video statistics:- <https://developers.google.com/youtube/analytics/data_model>,- <https://developers.google.com/youtube/v3/docs/videos/list>, and- <https://developers.google.com/youtube/v3/docs/videos#statistics>-- TikTok Display API video list/query and Video Object fields:- <https://developers.tiktok.com/docs/en/tiktok-api-v2-video-list>,- <https://developers.tiktok.com/docs/en/tiktok-api-v2-video-query>, and- <https://developers.tiktok.com/docs/en/tiktok-api-v2-video-object>-- Pinterest organic reporting and metric definitions:- <https://developers.pinterest.com/docs/analytics-and-reports/organic-reporting/>- and- <https://developers.pinterest.com/docs/analytics-and-reports/metrics-glossary/>-- Pinterest's official generated API client, including `pin_metrics` lifetime- comments/reactions and Pin Analytics parameters:- <https://github.com/pinterest/pinterest-python-generated-api-client/blob/main/docs/PinsApi.md>--## Delivery gates--1. This written design must be reviewed and approved.-2. Before promising native-history import for a v1 platform, verify in that- platform's current official documentation the owned-post enumeration- endpoint, pagination, scopes, accessible content types, history depth,- metric-retention limits, and preview-media expiry. Record any shallower- provider limit in the coverage contract instead of weakening it silently.-3. The implementation plan must preserve the approved four-table hybrid,- reconciled TryPost/external publication identity, and resumable import- checkpoints.-4. Implementation begins only after that written plan is reviewed and its- execution method is selected.-5. LinkedIn follower and post analytics receive a separate v2 implementation- plan after the external Community Management API dependency is resolved.diff --git a/docs/superpowers/specs/2026-09-24-independent-social-posts-design.md b/docs/superpowers/specs/2026-09-24-independent-social-posts-design.mddeleted file mode 100644index 9f88536e6..000000000--- a/docs/superpowers/specs/2026-09-24-independent-social-posts-design.md+++ /dev/null@@ -1,93 +0,0 @@-# Independent social posts--**Date:** 2026-09-24-**Status:** proposed for review--## Goal--Create and manage one independent post per selected social account. A person may compose several posts in one dialog, but saving four destinations creates four `posts` rows, whether the result is a draft or a scheduled publication. Editing a card changes only its own post.--## Decisions from the product discussion--| Concern | Decision |-| --- | --- |-| Creation | Two-step dialog: shared caption/media/account selection, then expandable customization for each selected account. The browser holds one composition with account-keyed overrides until submission. |-| Persistence | One `posts` row for every selected account. No batch/group entity, no synchronized edits, and no grouping in the post list. All rows are created in one database transaction. |-| Drafts | “Save Draft” creates one draft per selected account, just as “Schedule” creates one scheduled post per account. A new post always has one selected destination. |-| Editing | The social account and network are fixed. Caption, media, crop, supported network settings, `content_type` (e.g. Instagram Post/Reel/Story), and schedule can change on that one post while its status permits editing. |-| Media upload | Reuse the existing workspace Asset Library and chunked upload. Assets may be uploaded while composing, before a post exists. The post rows are created at Save Draft/Schedule/Publish. |-| Navigation | The proposed sidebar and tabs (Todos, Agendados, Postados, Rascunhos) are deferred by the user's later “esquece isso por enquanto”. Keep current navigation/routes in this refactor. The screenshot informs the independent card/dialog pattern only. |-| Surfaces | Web, REST API, and MCP use the same post Actions and offer the same single-account and multi-account creation capabilities. |--## Physical model decision--Keep `posts` and `post_platforms` for this refactor. **New posts have exactly one enabled `post_platforms` row** and no disabled placeholder rows. Four selected accounts still create four actual `posts` rows. `posts` owns caption, media, schedule, labels, comments, and the post status; its one target owns the account snapshot, `content_type`, platform metadata, provider ID/URL, provider status, retry/review state, and errors.--This preserves the existing publisher contract (`publish(PostPlatform $postPlatform)`), queue checkpoints, Google Business review/derivative cleanup, analytics foreign key (`analytics_publications.post_platform_id`), and historical external IDs. Collapsing the physical tables now would require changing the publishers and every API/MCP, analytics, observer, webhook, recovery, and notification path before the new user flow could ship. The second table is a delivery record, not a user-visible group. Physical consolidation can be reconsidered after the one-destination invariant has run in production; it is not a prerequisite for this feature.--The application must never infer a one-account limit from the network name. Two Instagram accounts selected together produce two posts. `social_account_id` is the identity of a destination; `content_type` is mutable only among types compatible with that account's platform.--## Composition and media semantics--The dialog state is:--```ts-type DestinationDraft = {- social_account_id: string;- content_type: string;- meta: Record<string, unknown>;- content?: string;- media?: MediaItem[];-};--type PostComposition = {- content: string;- media: MediaItem[];- scheduled_at: string | null;- status: 'draft' | 'scheduled' | 'publishing';- label_ids: string[];- destinations: DestinationDraft[];-};-```--Overrides are keyed by **social account ID**, not network. An unset override inherits the current shared value. An explicit empty caption or empty media array replaces the shared value. Going back to step one changes only destinations still inheriting that field. Removing and re-adding an account starts with shared defaults, avoiding stale hidden overrides. The final request materializes one complete content/media/meta record per account; it never persists a shared parent post.--Each post may reference the same original uploaded asset, because `posts.media` stores media snapshots and the workspace owns the asset. A user-selected crop creates a new uploaded asset and changes only that destination's media snapshot. Reuse the existing `ImageCropperDialog`/`imageCrop` geometry and the existing asset upload endpoint, extending the cropper beyond its current square output. Crop only static raster images; video, PDF, GIF animation, and unsupported image formats keep the original. Previews display the exact asset URL that publishing will use. No publisher silently applies a second user crop; existing platform-required automatic fitting remains.--Drafts may be incomplete. Scheduling and immediate publishing validate each resulting post against its own `content_type`, media rules, caption limit after `ContentSanitizer`, and required platform metadata. An invalid destination rejects the **entire** batch with errors keyed by destination index; no partial set of post rows is committed. Uploaded assets remain available in the workspace library if the final request fails. Prevent double submission while the request is in flight.--## Shared Action contract--`CreateChannelPost::execute(Workspace $workspace, User $user, array $data): Post` creates **one** post with exactly one destination; it does not call `SyncPostPlatforms` or create disabled destinations. Internal callers (AI and repurpose) pass one destination. `CreatePosts::execute(Workspace $workspace, User $user, array $composition): Collection` validates the complete destination set, starts one transaction, materializes each destination with `CreateChannelPost`, attaches labels, sets the requested state, and returns posts in the same order as the input. Queue dispatch for immediate publication occurs after commit. The existing grouped `CreatePost` Action is retired once its callers have moved. `UpdatePost::execute(...)` edits one post and its one enabled target. It may change `content_type` and `meta` but may not replace `social_account_id` or enable a sibling target.--New writes require at least one account and reject duplicate account IDs. The account must be active, in the current workspace, and compatible with its `content_type`. An account disconnected after draft creation remains represented by its target snapshot; scheduling checks publishability and editing cannot switch it to another account.--`posts.scheduled_at` remains the schedule source. `ProcessScheduledPosts` claims each due post and `PublishPost` dispatches its single target. An error or retry on one post does not alter another post created from the same dialog. `FinalizePostPublication` remains the only settler; with one enabled target, a new post settles as published or failed. `partially_published` remains meaningful for untouched legacy multi-target history only.--## Web, API, MCP, and navigation--- Web: New Post opens the two-step dialog from Posts and Calendar. Edit opens the same dialog in single-destination mode, with its account fixed. Existing deep links to `/posts/create` and `/posts/{post}/edit` open or redirect into the dialog instead of rendering the old full editor. Read-only published detail, comments, metrics, AI functions, and duplication continue to work; duplication makes a new single-destination draft.-- Posts page: retain the current sidebar and status routes for now. Each card identifies one social account and has actions for that post only. The list and calendar include one item per new post. An old multi-target published/failed post is displayed as one **read-only card per enabled target**, using the target snapshot/status/URL, without rewriting its database history.-- API: existing `POST /posts` creates one destination and retains its single-resource response. Add `POST /posts/batch` to create several destinations and return an ordered `posts` array. An old request to `POST /posts` with multiple `platforms` returns a clear 422 directing the caller to the batch endpoint; it must not silently create a grouped post. Existing one-post GET/PUT/DELETE routes operate on one post and reject attempts to switch the destination. The batch input uses `destinations[]` and the composition shape above.-- MCP: `CreatePostTool` accepts one destination, `CreatePostsTool` accepts several and returns the ordered IDs. Both call the same Actions as web and API. `UpdatePostTool` and `PublishPostTool` operate on one post. Read/list/preview/metrics tools show one destination per new post and may still read legacy history.-- Webhooks/Echo/PostHog: the existing `PostCreated`/status/deleted events fire once per created post after commit. Four new posts produce four post IDs. The user-facing list refreshes from those events. No new group event is introduced.--## Production data and legacy behavior--Existing data has many disabled `post_platforms` placeholders because `SyncPostPlatforms` created one row for every active account. **Only enabled targets represent intended destinations.** Never convert a disabled placeholder into a post.--Before rollout, run a read-only production audit of post counts by status and enabled-target count, in-flight jobs, zero-target drafts/scheduled posts, target rows with null account snapshots, comments, labels, analytics references, and media paths. The local database is not evidence of production volume. Test the split command on a restored production snapshot in PostgreSQL and MySQL.--An idempotent `posts:split-legacy-active` command converts legacy `draft` and `scheduled` posts with more than one enabled target: keep the original post ID for its first target (stable order by target ID), clone the parent for every other enabled target, move each target's `post_id` to its clone, copy label links and the comment tree without sending new creation/mention/webhook events, and keep the common schedule and content/media snapshot. It does not duplicate uploaded files. It skips in-flight and settled posts. New clones are checked before commit so every active post has one enabled target. Re-running the command finds no multi-target active rows and changes nothing.--Legacy drafts with **zero** enabled targets are preserved and surfaced in Drafts as “choose an account” recovery items; saving from that dialog creates independent destination posts and removes the empty legacy draft after success. A legacy scheduled post with zero enabled targets is a release blocker: the audit must resolve it before switching the web flow, because the existing scheduler cannot publish it. Legacy in-flight posts finish through the current pipeline and become read-only history. Settled legacy posts remain intact, so comments, analytics FKs, webhook logs, URLs, and external post IDs are preserved. Their cards are flattened in the web list; their API/MCP historical resource remains readable. No deployed migration or historical row is deleted in this release.--The split must run while new post writes and `posts:process-scheduled` dispatch are paused and publishing workers have drained the affected scheduled rows. Deploy the code containing the audit/split command with the new editor disabled; perform the split and assertions before enabling the new write paths. Retain a database backup. If a cutover check fails, keep the old application active and resume its scheduler; the split does not destroy parent IDs or media and is safe to rerun. If new-format posts have already been written, use a forward fix rather than reverting the database to an old snapshot.--## Verification--- One, two, and four accounts; two accounts on the same network; duplicate/inactive/foreign-workspace accounts; one invalid destination in a batch; draft with incomplete media; scheduled validation; double submit.-- Each post can be edited, rescheduled, published, retried, duplicated, and deleted without changing siblings. Changing Instagram Post to Reel/Story revalidates media; changing its account is rejected.-- Per-destination crop and caption override, inheritance after returning to step one, media upload before any post exists, crop failure and unsupported media, previews matching persisted media.-- Legacy active split preserves schedules, IDs, target metadata, labels, nested comments, and media references; repeat run is no-op. Legacy zero-target drafts remain accessible, and settled history keeps analytics/old IDs.-- PostgreSQL and MySQL affected tests, narrow browser tests for dialog and existing navigation, API and MCP contract tests, Wayfinder generation, i18n parity, Pint, Vue typecheck/lint.