Compare commits
11 commits
10c1eeaeda
...
292369b2b0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
292369b2b0 | ||
|
|
9504c7ccf6 | ||
|
|
4522fe4b74 | ||
|
|
46038d5a6a | ||
|
|
dd61cb3985 | ||
|
|
a638a8acae | ||
|
|
a6c8ece2f5 | ||
|
|
ee31aeee4f | ||
|
|
12a4fe1005 | ||
|
|
a1a6160ed8 | ||
|
|
8c915e59fc |
61 changed files with 17207 additions and 764 deletions
|
|
@ -64,6 +64,16 @@ Branch protection on `main` (applied 2026-08-18, OPS61) requires only:
|
|||
every ci-pr job; on the server the rule matches it as a glob,
|
||||
`CI (PR) / checks*`)
|
||||
|
||||
OPS64: the rollup is structurally honest since OPS62 — ci-pr.yml is a SINGLE
|
||||
sequential job (`checks`), so its own status IS the cascade verdict (no
|
||||
matrix, no shards, no parent aggregation to lie). The historical bug (Forgejo
|
||||
9.0.3 reporting the LAST matrix shard's result as the parent's in `needs`,
|
||||
posting `checks` SUCCESS with an e2e shard red — runs 604/607/610) is gone by
|
||||
construction; the `needs.<job>.results` array of GitHub does not exist in this
|
||||
runner, so any future matrix must NOT aggregate via `needs`. The safety-net
|
||||
CLI pins the defense: it never trusts the rollup alone (scans individual
|
||||
statuses; run-607 scenario unit-tested in `forgejoApi.unit.spec.ts`).
|
||||
|
||||
(`migration-lock` removed 2026-08-12 — the CI validates migration chains via migrate + int on every PR/main.)
|
||||
|
||||
**There is no deploy from CI.** The `ci.yml` verifier on `main` runs the full suite and stops (production is self-hosted on the homeserver — `jorgesolla1313.com.br` — deployed via an ops runbook outside this repo). Do not add a Vercel/Git-integration deploy gate.
|
||||
|
|
@ -89,7 +99,10 @@ equivalente Forgejo do `gh pr merge --auto --rebase`). O wait exige o rollup
|
|||
`CI (PR) / checks` POSTADO e verde (OPS61) — o único contexto que só existe
|
||||
quando a cascata inteira do ci-pr assentou (jobs ainda não agendados não
|
||||
postam status; o próprio status do job do safety net é `pending` durante o run
|
||||
e **nunca** entra no veredito). A regra de branch protection no servidor
|
||||
e **nunca** entra no veredito). O CLI nunca confia no rollup sozinho: varre
|
||||
todos os statuses individuais e falha em qualquer `failure`/`error` — um shard
|
||||
de e2e vermelho bloqueia o merge mesmo com o rollup verde (OPS64; run 607).
|
||||
A regra de branch protection no servidor
|
||||
bloqueia o merge POST (405) enquanto o contexto exigido não estiver satisfeito
|
||||
— inclusive merges manuais via API: foi um merge manual que colocou a PR #52
|
||||
em main com o CI vermelho (o CLI nunca mergeou sozinho antes do OPS61; todo
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ description: Runs a Pass-style engineering audit of the Teqo codebase — code s
|
|||
|
||||
# Engineering Audit (Pass N)
|
||||
|
||||
**Audit solitário (não paralelizável):** quando esta skill roda, o desenvolvimento paralelo **pausa** — nenhum outro agente trabalhando no repo. O agente do audit também **executa as remediações P0/P1 na mesma sessão** para trazer o projeto aos trilhos (não só registra); P2/P3 seguem o fluxo normal de ledger. Se o **agent-pool** estiver ligado, pause-o no início do audit (`gh workflow run agent-pool.yml -f action=pause`) e retome ao final (`-f action=resume`); o tick recusa spawn enquanto `POOL_PAUSED=true`. Em **Cursor Cloud** o `gh` do agente é read-only e o pause por dispatch não está disponível — vale o precheck fail-closed da seção "Modo autônomo (Cursor Cloud)".
|
||||
**Audit solitário (não paralelizável):** quando esta skill roda, o desenvolvimento paralelo **pausa** — nenhum outro agente trabalhando no repo. O agente do audit também **executa as remediações P0/P1 na mesma sessão** para trazer o projeto aos trilhos (não só registra); P2/P3 seguem o fluxo normal de ledger. O **agent-pool está morto desde OPS65** (workflow removido; scripts/skills dormentes) — nada a pausar.
|
||||
|
||||
## Modo autônomo (Cursor Cloud)
|
||||
|
||||
|
|
|
|||
|
|
@ -89,4 +89,4 @@ Bipartir (`{id}-plan` Grok High → `{id}-exec` `kimi-k3-low`) só sob pedido ex
|
|||
- **`work-issue`:** **não verifica modelo** — a sessão nasce no modelo fixo do ambiente (máquina do humano: DeepSeek V4 Flash). `model:` da Issue é metadata consultiva (o pool spawna nele; o claim brief o imprime).
|
||||
- **`agent-work-issue`:** pool já fixou o modelo no spawn; sessão mais forte → informa e segue.
|
||||
- **`plan-issue`:** sugere via esta tabela (slug único completo com effort); bipartição só sob blast radius extremo / pedido explícito.
|
||||
- **`agent-pool` smoke:** Composer default; Grok com effort explícito / Kimi K3 Low em Issues de teste bipartidas.
|
||||
- ~~`agent-pool` smoke~~ — **dormente (OPS65)**: workflow removido; pool morto.
|
||||
|
|
|
|||
|
|
@ -1,69 +0,0 @@
|
|||
# Agent pool supervisor (docs/plans/agent-pool-orchestrator.md).
|
||||
#
|
||||
# Stateless tick: reconciles pool claims and spawns Cursor Cloud workers up to
|
||||
# POOL_MAX_SLOTS over `ready` autonomous-eligible issues. Three triggers:
|
||||
# - workflow_dispatch — the canonical human channel (start/stop/pause/resume)
|
||||
# - schedule */10min — the periodic reconcile (default branch only)
|
||||
# - pull_request closed on main — immediate slot replenish after a merge
|
||||
#
|
||||
# Secrets:
|
||||
# CURSOR_API_KEY — Cursor Cloud Agents API key
|
||||
# FORGEJO_API_TOKEN — optional PAT; the native GITHUB_TOKEN (full repo
|
||||
# access) covers issue/label/contents ops inside Forgejo Actions
|
||||
#
|
||||
# Forgejo port (OPS50): no `concurrency:`/`permissions:` blocks; pool state
|
||||
# lives in pool-state.json on the `pool-state` branch (variables API is
|
||||
# GET-only here), read/written by scripts/lib/agent-pool-forgejo.mjs.
|
||||
name: Agent pool supervisor
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '*/10 * * * *'
|
||||
pull_request:
|
||||
types: [closed]
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
action:
|
||||
description: 'Ação do pool'
|
||||
required: true
|
||||
type: choice
|
||||
options:
|
||||
- start
|
||||
- stop
|
||||
- pause
|
||||
- resume
|
||||
- tick
|
||||
- status
|
||||
maxSlots:
|
||||
description: 'Slots simultâneos (só com action=start; default 5, máx 8)'
|
||||
required: false
|
||||
type: string
|
||||
|
||||
jobs:
|
||||
tick:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.merged == true
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: agent:pool workflow
|
||||
env:
|
||||
FORGEJO_API_TOKEN: ${{ secrets.FORGEJO_API_TOKEN }}
|
||||
CURSOR_API_KEY: ${{ secrets.CURSOR_API_KEY }}
|
||||
ACTION: ${{ inputs.action }}
|
||||
MAX_SLOTS: ${{ inputs.maxSlots }}
|
||||
run: |
|
||||
if [ "$GITHUB_EVENT_NAME" = "workflow_dispatch" ]; then
|
||||
args=(--action "$ACTION" --actor "$GITHUB_ACTOR")
|
||||
if [ -n "$MAX_SLOTS" ]; then args+=(--max-slots "$MAX_SLOTS"); fi
|
||||
else
|
||||
args=(--action tick --actor "$GITHUB_ACTOR")
|
||||
fi
|
||||
node scripts/agent-pool.mjs workflow "${args[@]}"
|
||||
|
|
@ -1,23 +1,25 @@
|
|||
# PR gate: feature → main. Two-phase cascade:
|
||||
# Phase 1 (cheap, no Postgres): lint, format, typecheck, knip, cycles, unit
|
||||
# Phase 2 (expensive, Postgres; needs phase 1 green/skipped): int, build, e2e
|
||||
# Job-level skips come from the `scope` classifier (scripts/ci-scope.mjs). A
|
||||
# phase-1 failure skips phase 2 via `needs` + explicit if.
|
||||
# PR gate: feature → main. SINGLE sequential job (OPS62, X1): one container,
|
||||
# one checkout, one pnpm install, one runner slot. Fail-fast is STRUCTURAL —
|
||||
# a failed step skips every step after it, the job fails, the run fails and
|
||||
# the slot is released immediately. No cancel-run API (Forgejo 9.0.3 has
|
||||
# none), no watchdog job, no upgrades: with one job there are no siblings to
|
||||
# cancel. Steps keep their own logs, so diagnosis is intact after a failure.
|
||||
# The job id `checks` preserves the `CI (PR) / checks` status context the
|
||||
# automerger waitForChecks and branch protection rely on (OPS61).
|
||||
#
|
||||
# Job-level skips come from the `scope` classifier (scripts/ci-scope.mjs) run
|
||||
# as a step; its outputs drive `if:` on the heavy steps (same modes as the
|
||||
# former per-job cascade: none/changed/full).
|
||||
#
|
||||
# Schema migrations are NOT serialized across PRs (migration-lock removed
|
||||
# 2026-08-12): a stale chain is caught by `pnpm migrate` + `test:int` on every
|
||||
# PR and on main (ci.yml), incl. campaignMigrationReconciliation — the check's
|
||||
# hard fail deadlocked every open schema PR the moment two coexisted.
|
||||
#
|
||||
# High-risk diffs (schema, lockfile, classifiers — see
|
||||
# scripts/lib/test-affected-core.mjs) force full unit/int/e2e. Push to main
|
||||
# always runs the full suite in ci.yml (no affected skips).
|
||||
#
|
||||
# Forgejo port (OPS50): no `concurrency:`/`permissions:` (unsupported /
|
||||
# native token); Postgres services publish per-job ports (5433 int, 5434
|
||||
# build, 5435/5436 e2e shards) and jobs reach them through the bridge gateway
|
||||
# (DB_HOST from /proc/net/route). The GitHub fail-fast action was dropped
|
||||
# (Forgejo has no cancel-run plumbing); job timeouts cover that role.
|
||||
# Forgejo port (OPS50): Postgres services live on the job network and are
|
||||
# reached by NAME (postgres-int / postgres-build on 5432) — no host publish,
|
||||
# so concurrent runs never collide on host ports (OPS62 X1). Two isolated
|
||||
# services keep e2e from inheriting int fixture residue.
|
||||
name: CI (PR)
|
||||
|
||||
on:
|
||||
|
|
@ -29,17 +31,39 @@ env:
|
|||
NEXT_PUBLIC_SITE_URL: http://localhost:3000
|
||||
|
||||
jobs:
|
||||
scope:
|
||||
checks:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
outputs:
|
||||
code_mode: ${{ steps.classify.outputs.code_mode }}
|
||||
build_mode: ${{ steps.classify.outputs.build_mode }}
|
||||
test_mode: ${{ steps.classify.outputs.test_mode }}
|
||||
e2e_mode: ${{ steps.classify.outputs.e2e_mode }}
|
||||
e2e_specs: ${{ steps.classify.outputs.e2e_specs }}
|
||||
e2e_matrix: ${{ steps.classify.outputs.e2e_matrix }}
|
||||
e2e_shards: ${{ steps.classify.outputs.e2e_shards }}
|
||||
timeout-minutes: 50
|
||||
services:
|
||||
# Services are reached by NAME on the job network (no host publish —
|
||||
# OPS62 X1): concurrent runs never collide on host ports, which the
|
||||
# single long-lived job would hold for the whole run. Two isolated
|
||||
# services — int and build+e2e — keep e2e from inheriting int fixture
|
||||
# residue (same isolation the former jobs had). Forgejo 9 does not
|
||||
# expand expressions in `services.ports`, so a per-run port scheme was
|
||||
# dropped in favour of the job-network DNS.
|
||||
postgres-int:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
postgres-build:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
|
|
@ -50,11 +74,13 @@ jobs:
|
|||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Classify PR blast radius
|
||||
id: classify
|
||||
id: scope
|
||||
env:
|
||||
GITHUB_BASE_REF: ${{ github.base_ref }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
result=$(node scripts/ci-scope.mjs)
|
||||
echo "scope: $(echo "$result" | jq -c '{code:.code.mode,build:.build.mode,test:.test.mode,e2e:.e2e.mode,reason:{code:.code.reason,build:.build.reason,test:.test.reason,e2e:.e2e.reason}}')"
|
||||
echo "code_mode=$(echo "$result" | jq -r .code.mode)" >> "$GITHUB_OUTPUT"
|
||||
|
|
@ -62,317 +88,9 @@ jobs:
|
|||
echo "test_mode=$(echo "$result" | jq -r .test.mode)" >> "$GITHUB_OUTPUT"
|
||||
echo "e2e_mode=$(echo "$result" | jq -r .e2e.mode)" >> "$GITHUB_OUTPUT"
|
||||
echo "e2e_specs=$(echo "$result" | jq -r '[.e2e.specs[] | "tests/e2e/" + . + ".e2e.spec.ts"] | join(" ")')" >> "$GITHUB_OUTPUT"
|
||||
# OPS34: full runs split across shards (one runner per shard); selected
|
||||
# stays on a single runner (a second build for a handful of specs is
|
||||
# waste). Single source: e2eShardConfig in scripts/lib/test-affected-core.mjs.
|
||||
echo "e2e_matrix=$(echo "$result" | jq -c .e2e_shards.matrix)" >> "$GITHUB_OUTPUT"
|
||||
echo "e2e_shards=$(echo "$result" | jq -r .e2e_shards.total)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Check test file locations
|
||||
run: node scripts/check-test-locations.mjs
|
||||
- run: pnpm lint
|
||||
|
||||
format:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm format:check
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: [scope]
|
||||
if: needs.scope.outputs.code_mode != 'none'
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm typecheck
|
||||
|
||||
knip:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: [scope]
|
||||
if: needs.scope.outputs.code_mode != 'none'
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm knip
|
||||
|
||||
cycles:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
needs: [scope]
|
||||
if: needs.scope.outputs.code_mode != 'none'
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: pnpm check:cycles
|
||||
|
||||
unit:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
needs: [scope]
|
||||
if: needs.scope.outputs.test_mode != 'none'
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Unit tests (full suite)
|
||||
if: needs.scope.outputs.test_mode == 'full'
|
||||
run: pnpm test:unit
|
||||
|
||||
- name: Unit tests (changed since PR base)
|
||||
if: needs.scope.outputs.test_mode == 'changed'
|
||||
run: pnpm test:unit -- --changed origin/${{ github.base_ref }} --passWithNoTests
|
||||
|
||||
int:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
needs: [scope, lint, format, typecheck, knip, cycles, unit]
|
||||
if: |
|
||||
always()
|
||||
&& !cancelled()
|
||||
&& needs.scope.outputs.test_mode != 'none'
|
||||
&& needs.lint.result == 'success'
|
||||
&& needs.format.result == 'success'
|
||||
&& (needs.typecheck.result == 'success' || needs.typecheck.result == 'skipped')
|
||||
&& (needs.knip.result == 'success' || needs.knip.result == 'skipped')
|
||||
&& (needs.cycles.result == 'success' || needs.cycles.result == 'skipped')
|
||||
&& (needs.unit.result == 'success' || needs.unit.result == 'skipped')
|
||||
env:
|
||||
# Self-hosted runner has 8 CPUs; vitest forks ≈ CPUs and each fork holds
|
||||
# a Payload pool (max 10) → overflows the service Postgres' 100 clients
|
||||
# ("too many clients already", CI run 180). 4 forks stay well under.
|
||||
# GitHub's 2–4 vCPU runners keep the CPU-relative default (no env).
|
||||
VITEST_MAX_WORKERS: 4
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- 5433:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5433/teqo_test" >> "$GITHUB_ENV"
|
||||
# vitest/playwright re-load .env.test over the process env, so the
|
||||
# service URL must win through the .env.test.local layer (same
|
||||
# mechanism `pnpm worktree next` uses). OPS50.
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5433/teqo_test" > .env.test.local
|
||||
- run: pnpm migrate
|
||||
- run: pnpm db:seed:minimal
|
||||
|
||||
- name: Integration tests (full suite)
|
||||
if: needs.scope.outputs.test_mode == 'full'
|
||||
run: pnpm test:int
|
||||
|
||||
- name: Integration tests (changed since PR base)
|
||||
if: needs.scope.outputs.test_mode == 'changed'
|
||||
run: pnpm test:int -- --changed origin/${{ github.base_ref }} --passWithNoTests
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
needs: [scope, lint, format, typecheck, knip, cycles, unit]
|
||||
if: |
|
||||
always()
|
||||
&& !cancelled()
|
||||
&& needs.scope.outputs.build_mode != 'none'
|
||||
&& needs.lint.result == 'success'
|
||||
&& needs.format.result == 'success'
|
||||
&& (needs.typecheck.result == 'success' || needs.typecheck.result == 'skipped')
|
||||
&& (needs.knip.result == 'success' || needs.knip.result == 'skipped')
|
||||
&& (needs.cycles.result == 'success' || needs.cycles.result == 'skipped')
|
||||
&& (needs.unit.result == 'success' || needs.unit.result == 'skipped')
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- 5434:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5434/teqo_test" >> "$GITHUB_ENV"
|
||||
- name: Build (against the local service database)
|
||||
run: pnpm build
|
||||
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
needs: [scope, lint, format, typecheck, knip, cycles, unit]
|
||||
if: |
|
||||
always()
|
||||
&& !cancelled()
|
||||
&& needs.scope.outputs.e2e_mode != 'none'
|
||||
&& needs.lint.result == 'success'
|
||||
&& needs.format.result == 'success'
|
||||
&& (needs.typecheck.result == 'success' || needs.typecheck.result == 'skipped')
|
||||
&& (needs.knip.result == 'success' || needs.knip.result == 'skipped')
|
||||
&& (needs.cycles.result == 'success' || needs.cycles.result == 'skipped')
|
||||
&& (needs.unit.result == 'success' || needs.unit.result == 'skipped')
|
||||
# OPS34: full mode splits across 2 runners; selected mode stays on shard 1
|
||||
# (shard 2 skips build+test via step `if`). Static [1, 2] — Forgejo 1.22
|
||||
# does not pass job results into matrix expansion, so fromJson(needs.*)
|
||||
# yields an empty shard. Keep the literal in sync with e2eShardConfig in
|
||||
# scripts/lib/test-affected-core.mjs (ci.yml pins the same [1, 2] / 2).
|
||||
# fail-fast: false keeps both shards' logs.
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
env:
|
||||
# Explicit CI workers; the local default stays 2 (playwright.config.ts).
|
||||
PLAYWRIGHT_WORKERS: 2
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- ${{ matrix.shard == 1 && '5435' || '5436' }}:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
playwright-${{ runner.os }}-
|
||||
- name: Install Playwright chromium
|
||||
run: pnpm exec playwright install --with-deps chromium
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
DB_PORT=${{ matrix.shard == 1 && '5435' || '5436' }}
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:${DB_PORT}/teqo_test" >> "$GITHUB_ENV"
|
||||
# vitest/playwright re-load .env.test over the process env, so the
|
||||
# service URL must win through the .env.test.local layer (same
|
||||
# mechanism `pnpm worktree next` uses). OPS50.
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:${DB_PORT}/teqo_test" > .env.test.local
|
||||
- run: pnpm migrate
|
||||
- run: pnpm db:seed:minimal
|
||||
- name: Build for e2e
|
||||
# Selected mode only needs shard 1 (a second build for a handful of
|
||||
# specs is waste).
|
||||
if: needs.scope.outputs.e2e_mode == 'full' || matrix.shard == 1
|
||||
run: pnpm build
|
||||
env:
|
||||
# Same dir the Playwright webServer serves (playwright.config.ts
|
||||
# falls back to '.next-e2e'; gate-ci.mjs builds there too).
|
||||
NEXT_DIST_DIR: .next-e2e
|
||||
|
||||
- name: E2E tests (full suite, shard ${{ matrix.shard }})
|
||||
if: needs.scope.outputs.e2e_mode == 'full'
|
||||
# No `--` separator: pnpm would forward it verbatim to playwright and
|
||||
# the flag would be parsed as a file pattern ("No tests found").
|
||||
run: pnpm test:e2e --shard=${{ matrix.shard }}/${{ needs.scope.outputs.e2e_shards }}
|
||||
|
||||
- name: E2E tests (manifest-selected specs)
|
||||
# Selected specs run once, on shard 1; shard 2 skips (no test step).
|
||||
if: needs.scope.outputs.e2e_mode == 'selected' && matrix.shard == 1
|
||||
run: pnpm test:e2e -- ${{ needs.scope.outputs.e2e_specs }}
|
||||
|
||||
docs-guards:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
# Content guards are PR-scoped and cheap — run them before the suite so
|
||||
# a guard failure fails fast instead of after 20 minutes of tests.
|
||||
- name: Changelog is append-only
|
||||
env:
|
||||
GITHUB_BASE_REF: ${{ github.base_ref }}
|
||||
|
|
@ -384,44 +102,108 @@ jobs:
|
|||
env:
|
||||
GITHUB_BASE_REF: ${{ github.base_ref }}
|
||||
run: node scripts/check-docs-conflict-markers.mjs
|
||||
|
||||
plans-only-closes:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Block Closes/Fixes/Resolves on plans-only PRs
|
||||
env:
|
||||
GITHUB_BASE_REF: ${{ github.base_ref }}
|
||||
PR_BODY: ${{ github.event.pull_request.body }}
|
||||
run: node scripts/check-plans-only-pr-closes.mjs
|
||||
|
||||
checks:
|
||||
name: checks
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- scope
|
||||
- lint
|
||||
- format
|
||||
- typecheck
|
||||
- knip
|
||||
- cycles
|
||||
- unit
|
||||
- int
|
||||
- build
|
||||
- e2e
|
||||
- docs-guards
|
||||
- plans-only-closes
|
||||
if: always()
|
||||
steps:
|
||||
- name: All cascade checks green
|
||||
env:
|
||||
NEEDS: ${{ toJSON(needs) }}
|
||||
- name: Check test file locations
|
||||
run: node scripts/check-test-locations.mjs
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
- name: Format check
|
||||
run: pnpm format:check
|
||||
- name: Typecheck
|
||||
if: steps.scope.outputs.code_mode != 'none'
|
||||
run: pnpm typecheck
|
||||
- name: Knip
|
||||
if: steps.scope.outputs.code_mode != 'none'
|
||||
run: pnpm knip
|
||||
- name: Check cycles
|
||||
if: steps.scope.outputs.code_mode != 'none'
|
||||
run: pnpm check:cycles
|
||||
|
||||
- name: Unit tests (full suite)
|
||||
if: steps.scope.outputs.test_mode == 'full'
|
||||
run: pnpm test:unit
|
||||
- name: Unit tests (changed since PR base)
|
||||
if: steps.scope.outputs.test_mode == 'changed'
|
||||
run: pnpm test:unit -- --changed origin/${{ github.base_ref }} --passWithNoTests
|
||||
- name: Prepare database URL (int service)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "$NEEDS" | jq -e '
|
||||
to_entries
|
||||
| all(.value.result == "success" or .value.result == "skipped")
|
||||
'
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-int:5432/teqo_test" >> "$GITHUB_ENV"
|
||||
# vitest re-loads .env.test over the process env, so the service URL
|
||||
# must win through the .env.test.local layer (same mechanism
|
||||
# `pnpm worktree next` uses). OPS50.
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-int:5432/teqo_test" > .env.test.local
|
||||
- name: Migrate (int database)
|
||||
run: pnpm migrate
|
||||
- name: Seed minimal (int database)
|
||||
run: pnpm db:seed:minimal
|
||||
|
||||
- name: Integration tests (full suite)
|
||||
if: steps.scope.outputs.test_mode == 'full'
|
||||
env:
|
||||
# Self-hosted runner has 8 CPUs; vitest forks ≈ CPUs and each fork
|
||||
# holds a Payload pool (max 10) → overflows the service Postgres' 100
|
||||
# clients ("too many clients already", CI run 180). 4 forks stay
|
||||
# well under. The unit step above stays CPU-relative (no DB).
|
||||
VITEST_MAX_WORKERS: 4
|
||||
run: pnpm test:int
|
||||
- name: Integration tests (changed since PR base)
|
||||
if: steps.scope.outputs.test_mode == 'changed'
|
||||
env:
|
||||
VITEST_MAX_WORKERS: 4
|
||||
run: pnpm test:int -- --changed origin/${{ github.base_ref }} --passWithNoTests
|
||||
|
||||
- name: Prepare database URL (build/e2e service)
|
||||
if: steps.scope.outputs.build_mode != 'none' || steps.scope.outputs.e2e_mode != 'none'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-build:5432/teqo_test" >> "$GITHUB_ENV"
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-build:5432/teqo_test" > .env.test.local
|
||||
- name: Migrate (build/e2e database)
|
||||
if: steps.scope.outputs.build_mode != 'none' || steps.scope.outputs.e2e_mode != 'none'
|
||||
run: pnpm migrate
|
||||
- name: Seed minimal (build/e2e database)
|
||||
if: steps.scope.outputs.build_mode != 'none' || steps.scope.outputs.e2e_mode != 'none'
|
||||
run: pnpm db:seed:minimal
|
||||
|
||||
- name: Build (against the local service database)
|
||||
if: steps.scope.outputs.build_mode != 'none'
|
||||
run: pnpm build
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
if: steps.scope.outputs.e2e_mode != 'none'
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
restore-keys: |
|
||||
playwright-${{ runner.os }}-
|
||||
- name: Install Playwright chromium
|
||||
if: steps.scope.outputs.e2e_mode != 'none'
|
||||
run: pnpm exec playwright install --with-deps chromium
|
||||
- name: Build for e2e
|
||||
# Selected mode needs the build too (the Playwright webServer serves
|
||||
# .next-e2e; the fallback `.next-e2e` dir is what gate-ci.mjs builds).
|
||||
if: steps.scope.outputs.e2e_mode != 'none'
|
||||
run: pnpm build
|
||||
env:
|
||||
NEXT_DIST_DIR: .next-e2e
|
||||
- name: E2E tests (full suite, single job, 4 workers)
|
||||
if: steps.scope.outputs.e2e_mode == 'full'
|
||||
# Explicit CI workers; the local default stays 2 (playwright.config.ts).
|
||||
# 4 workers in one process replace the former 2 shards × 2 workers.
|
||||
# No `--` separator: pnpm would forward it verbatim to playwright and
|
||||
# the flag would be parsed as a file pattern ("No tests found").
|
||||
env:
|
||||
PLAYWRIGHT_WORKERS: 4
|
||||
run: pnpm test:e2e
|
||||
- name: E2E tests (manifest-selected specs)
|
||||
if: steps.scope.outputs.e2e_mode == 'selected'
|
||||
env:
|
||||
PLAYWRIGHT_WORKERS: 4
|
||||
run: pnpm test:e2e -- ${{ steps.scope.outputs.e2e_specs }}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,47 @@
|
|||
# Post-merge verifier on `main`: always the FULL suite (no affected skips).
|
||||
# Post-merge verifier on `main`, in a fixed 30-minute window (OPS65): the
|
||||
# workflow no longer fires on every push. The `schedule` trigger polls every
|
||||
# 30 min and a cheap gate (`gate`, runs-on host, no pnpm) classifies whether
|
||||
# anything that would enter the docker build context changed since the
|
||||
# revision running on the homeserver (the `org.opencontainers.image.revision`
|
||||
# label of the running container, read over ssh).
|
||||
# - Deployed == HEAD → suite + deploy skip; the run stays green.
|
||||
# - Anything else (production change, unknown deployed state, dispatch) →
|
||||
# full suite; deploy in the same window.
|
||||
# - `workflow_dispatch` always runs the full pipeline (explicit operator
|
||||
# intent); the deploy is idempotent via the "already deployed" guard in
|
||||
# scripts/deploy-homeserver.sh.
|
||||
#
|
||||
# Fail-open: an unreadable/unknown deployed revision makes the gate report
|
||||
# production=true, so the suite ALWAYS verifies main and a quiet day only
|
||||
# skips when we KNOW deployed == HEAD. A gate that cannot classify at all
|
||||
# (git/.dockerignore error) exits non-zero and turns the run RED — never a
|
||||
# silent green blackout. The deploy job only runs when the gate succeeded
|
||||
# AND production changed AND checks are green — never deploy blind.
|
||||
#
|
||||
# When the suite is green, the `deploy` job publishes teqo-1313 on the
|
||||
# homeserver (OPS53): it streams scripts/deploy-homeserver.sh to the homeserver
|
||||
# over SSH; the remote script builds the standalone image at the pushed SHA,
|
||||
# pushes it to the local registry (localhost:5000), applies pending migrations
|
||||
# through the compose maintenance service and rolls the container out.
|
||||
#
|
||||
# Forgejo port (OPS50): Postgres services publish to per-job HOST ports on the
|
||||
# runner machine (act/forgejo runner semantics — the canonical 5432 is the
|
||||
# workstation's own dev database), and jobs reach them through the bridge
|
||||
# gateway: DB_HOST = gateway IP from /proc/net/route. No `permissions:`
|
||||
# (Forgejo issues one native GITHUB_TOKEN) and no `concurrency:` (unsupported).
|
||||
# `gh workflow run` requeues became `node scripts/forgejo-dispatch.mjs`.
|
||||
# The GitHub fail-fast action was dropped (Forgejo has no cancel-run plumbing);
|
||||
# job timeouts cover that role.
|
||||
# SINGLE sequential job (OPS62, X1): one container, one checkout, one pnpm
|
||||
# install, one runner slot. Fail-fast is STRUCTURAL — a failed step skips
|
||||
# every step after it, the job fails, the run fails and the slot is released
|
||||
# immediately. No cancel-run API (Forgejo 9.0.3 has none), no watchdog job,
|
||||
# no upgrades. `deploy` (needs: [checks]) never starts on a red run.
|
||||
#
|
||||
# Forgejo port (OPS50): Postgres services live on the job network and are
|
||||
# reached by NAME (postgres-int / postgres-build on 5432) — no host publish,
|
||||
# so concurrent runs never collide on host ports (OPS62 X1). No
|
||||
# `permissions:` (Forgejo issues one native GITHUB_TOKEN) and no
|
||||
# `concurrency:` (unsupported). `gh workflow run` requeues became
|
||||
# `node scripts/forgejo-dispatch.mjs`.
|
||||
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
schedule:
|
||||
- cron: '*/30 * * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
env:
|
||||
|
|
@ -26,43 +49,74 @@ env:
|
|||
NEXT_PUBLIC_SITE_URL: http://localhost:3000
|
||||
|
||||
jobs:
|
||||
static:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
gate:
|
||||
name: gate production change
|
||||
# Host runner: needs `ssh homeserver` (same environment as the deploy
|
||||
# job — the key lives on the workstation host) and a full clone to diff
|
||||
# <deployed-rev>..HEAD. Main + dispatch only: a branch dispatch must not
|
||||
# run that branch's code on the host — the skipped gate makes the suite
|
||||
# run fail-open on ubuntu containers instead (test-only secrets).
|
||||
if: github.ref == 'refs/heads/main'
|
||||
runs-on: host
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
production: ${{ steps.classify.outputs.production }}
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- run: node scripts/check-test-locations.mjs
|
||||
- run: pnpm lint
|
||||
- run: pnpm format:check
|
||||
- run: pnpm typecheck
|
||||
- run: pnpm knip
|
||||
- run: pnpm check:cycles
|
||||
- run: pnpm test:unit
|
||||
package-manager-cache: false
|
||||
- name: Read deployed revision and classify production change
|
||||
id: classify
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# Truth = the RUNNING container's revision label (the compose file
|
||||
# can lie after a failed rollback — it is swapped before the
|
||||
# rollout). Empty/malformed = unknown deployed state → the
|
||||
# classifier reports production=true (full run, green).
|
||||
deployed_sha="$(ssh homeserver "docker inspect -f '{{index .Config.Labels \"org.opencontainers.image.revision\"}}' teqo-1313 2>/dev/null" || true)"
|
||||
if ! printf '%s' "$deployed_sha" | grep -Eq '^[0-9a-f]{40}$'; then
|
||||
deployed_sha=""
|
||||
fi
|
||||
echo "deployed_sha: ${deployed_sha:-<none>}"
|
||||
out="$(node scripts/ci-classify-production.mjs --deployed "$deployed_sha")"
|
||||
printf '%s\n' "$out"
|
||||
echo "production=$(printf '%s' "$out" | node -pe 'JSON.parse(require("fs").readFileSync(0,"utf8")).production')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
int:
|
||||
checks:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
env:
|
||||
# Self-hosted runner has 8 CPUs; vitest forks ≈ CPUs and each fork holds
|
||||
# a Payload pool (max 10) → overflows the service Postgres' 100 clients
|
||||
# ("too many clients already"). 4 forks stay well under. GitHub's 2–4
|
||||
# vCPU runners keep the CPU-relative default (no env).
|
||||
VITEST_MAX_WORKERS: 4
|
||||
timeout-minutes: 50
|
||||
needs: [gate]
|
||||
# Fail-open: an errored gate never skips the verifier; only a gate that
|
||||
# succeeded AND found no production change skips the suite.
|
||||
if: needs.gate.result != 'success' || needs.gate.outputs.production == 'true'
|
||||
services:
|
||||
postgres:
|
||||
# Services are reached by NAME on the job network (no host publish —
|
||||
# OPS62 X1): concurrent runs never collide on host ports, which the
|
||||
# single long-lived job would hold for the whole run. Two isolated
|
||||
# services — int and build+e2e — keep e2e from inheriting int fixture
|
||||
# residue. Forgejo 9 does not expand expressions in `services.ports`,
|
||||
# so a per-run port scheme was dropped in favour of the job-network DNS.
|
||||
postgres-int:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
postgres-build:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- 5433:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
|
|
@ -76,90 +130,56 @@ jobs:
|
|||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
|
||||
- name: Check test file locations
|
||||
run: node scripts/check-test-locations.mjs
|
||||
- name: Lint
|
||||
run: pnpm lint
|
||||
- name: Format check
|
||||
run: pnpm format:check
|
||||
- name: Typecheck
|
||||
run: pnpm typecheck
|
||||
- name: Knip
|
||||
run: pnpm knip
|
||||
- name: Check cycles
|
||||
run: pnpm check:cycles
|
||||
- name: Unit tests (full suite)
|
||||
run: pnpm test:unit
|
||||
|
||||
- name: Prepare database URL (int service)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5433/teqo_test" >> "$GITHUB_ENV"
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-int:5432/teqo_test" >> "$GITHUB_ENV"
|
||||
# vitest re-loads .env.test over the process env, so the service URL
|
||||
# must win through the .env.test.local layer (same mechanism
|
||||
# `pnpm worktree next` uses). OPS50.
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5433/teqo_test" > .env.test.local
|
||||
- run: pnpm migrate
|
||||
- run: pnpm db:seed:minimal
|
||||
- run: pnpm test:int
|
||||
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 25
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-int:5432/teqo_test" > .env.test.local
|
||||
- name: Migrate (int database)
|
||||
run: pnpm migrate
|
||||
- name: Seed minimal (int database)
|
||||
run: pnpm db:seed:minimal
|
||||
- name: Integration tests (full suite)
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- 5434:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
# Self-hosted runner has 8 CPUs; vitest forks ≈ CPUs and each fork
|
||||
# holds a Payload pool (max 10) → overflows the service Postgres' 100
|
||||
# clients ("too many clients already"). 4 forks stay well under. The
|
||||
# unit step above stays CPU-relative (no DB).
|
||||
VITEST_MAX_WORKERS: 4
|
||||
run: pnpm test:int
|
||||
|
||||
- name: Prepare database URL (build/e2e service)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:5434/teqo_test" >> "$GITHUB_ENV"
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-build:5432/teqo_test" >> "$GITHUB_ENV"
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@postgres-build:5432/teqo_test" > .env.test.local
|
||||
- name: Migrate (build/e2e database)
|
||||
run: pnpm migrate
|
||||
- name: Seed minimal (build/e2e database)
|
||||
run: pnpm db:seed:minimal
|
||||
|
||||
- name: Build (against the service database)
|
||||
run: pnpm build
|
||||
|
||||
e2e:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
# Main always runs the full suite: split it across 2 jobs (OPS34), each
|
||||
# building its own `.next-e2e` (measured 2026-08-10: build 172s + tests
|
||||
# 196s + ~54s fixed → ≈ 5.5 min per shard vs 435s serial). `fail-fast:
|
||||
# false` so one shard's failure keeps the other's diagnostics. Keep the
|
||||
# [1, 2] / 2 literal in sync with `e2eShardConfig` in
|
||||
# scripts/lib/test-affected-core.mjs (ci-pr pins the same literal).
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1, 2]
|
||||
env:
|
||||
# Explicit CI workers; the local default stays 2 (playwright.config.ts).
|
||||
PLAYWRIGHT_WORKERS: 2
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17-alpine
|
||||
env:
|
||||
POSTGRES_USER: teqo
|
||||
POSTGRES_PASSWORD: teqo
|
||||
POSTGRES_DB: teqo_test
|
||||
ports:
|
||||
- ${{ matrix.shard == 1 && '5435' || '5436' }}:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U teqo"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 12
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: pnpm/action-setup@v6
|
||||
- uses: actions/setup-node@v5
|
||||
with:
|
||||
node-version: 24
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
|
|
@ -169,55 +189,36 @@ jobs:
|
|||
playwright-${{ runner.os }}-
|
||||
- name: Install Playwright chromium
|
||||
run: pnpm exec playwright install --with-deps chromium
|
||||
- name: Prepare database URL (service via bridge gateway)
|
||||
run: |
|
||||
set -euo pipefail
|
||||
DB_HOST=$(awk '$2 == "00000000" {a=$3; print strtonum("0x" substr(a,7,2)) "." strtonum("0x" substr(a,5,2)) "." strtonum("0x" substr(a,3,2)) "." strtonum("0x" substr(a,1,2)); exit}' /proc/net/route)
|
||||
DB_PORT=${{ matrix.shard == 1 && '5435' || '5436' }}
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:${DB_PORT}/teqo_test" >> "$GITHUB_ENV"
|
||||
# playwright re-loads .env.test over the process env, so the service
|
||||
# URL must win through the .env.test.local layer (same mechanism
|
||||
# `pnpm worktree next` uses). OPS50.
|
||||
echo "DATABASE_URL=postgresql://teqo:teqo@${DB_HOST}:${DB_PORT}/teqo_test" > .env.test.local
|
||||
- run: pnpm migrate
|
||||
- run: pnpm db:seed:minimal
|
||||
- name: Build for e2e
|
||||
# Same dir the Playwright webServer serves (playwright.config.ts
|
||||
# falls back to '.next-e2e'; gate-ci.mjs builds there too).
|
||||
run: pnpm build
|
||||
env:
|
||||
# Same dir the Playwright webServer serves (playwright.config.ts
|
||||
# falls back to '.next-e2e'; gate-ci.mjs builds there too).
|
||||
NEXT_DIST_DIR: .next-e2e
|
||||
- name: E2E tests (full suite, shard ${{ matrix.shard }})
|
||||
- name: E2E tests (full suite, single job, 4 workers)
|
||||
# Explicit CI workers; the local default stays 2 (playwright.config.ts).
|
||||
# 4 workers in one process replace the former 2 shards × 2 workers.
|
||||
# No `--` separator: pnpm would forward it verbatim to playwright and
|
||||
# the flag would be parsed as a file pattern ("No tests found").
|
||||
run: pnpm test:e2e --shard=${{ matrix.shard }}/2
|
||||
|
||||
checks:
|
||||
name: checks
|
||||
runs-on: ubuntu-latest
|
||||
needs: [static, int, build, e2e]
|
||||
if: always()
|
||||
steps:
|
||||
- name: All main verifier checks green
|
||||
env:
|
||||
NEEDS: ${{ toJSON(needs) }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "$NEEDS" | jq -e '
|
||||
to_entries
|
||||
| all(.value.result == "success" or .value.result == "skipped")
|
||||
'
|
||||
PLAYWRIGHT_WORKERS: 4
|
||||
run: pnpm test:e2e
|
||||
|
||||
deploy:
|
||||
name: deploy homeserver (teqo-1313)
|
||||
# OPS53. Runs directly on the runner HOST (not a job container): the
|
||||
# deploy needs the workstation's SSH key to reach the homeserver
|
||||
# (`ssh homeserver`) and streams the whole remote build/migrate/rollout
|
||||
# to this job's logs. Deliberately wired ONLY here — push to main +
|
||||
# to this job's logs. Deliberately wired ONLY here — main window +
|
||||
# workflow_dispatch — never in ci-pr.yml: a host job is code execution as
|
||||
# `fsolla` on the workstation, and main only ever moves through a merged
|
||||
# PR whose full suite was already green.
|
||||
needs: [checks]
|
||||
# OPS65: double-gated — the verifier must be green AND the gate must have
|
||||
# found a production change. The explicit `if` prevents both "deploy
|
||||
# blind on a failed gate" and "deploy with a red suite" (a bare output
|
||||
# condition would run despite failed needs).
|
||||
needs: [checks, gate]
|
||||
if: needs.checks.result == 'success' && needs.gate.outputs.production == 'true'
|
||||
runs-on: host
|
||||
timeout-minutes: 60
|
||||
steps:
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ These are product/architecture constraints — not a ban on editing existing cod
|
|||
|
||||
- Single Next.js app, three route groups: `(frontend)` public site, `(payload)` admin, `(campaign)` internal campaign tool. No separate Rust service or frontend app for `/campanha`; it is modeled with Payload collections. The campaign roles are `coordinator` (label "Coordenador Geral"), `advisor` ("Assessor"), `leader` ("Liderança"), and `candidate` ("Candidato", unrestricted visibility), all on the separate auth collection `campaignUser` (see "Campaign auth" below). An advisor sees and manages ONLY the municipalities they administer; a leader is locked down to the supporter contact tool.
|
||||
- **2026-07-23 remodel (DEPLOYED to production 2026-07-23): "Município" is the operational unit** (it replaced "Praça", which replaced "Núcleo Eleitoral"). Municípios are PREDEFINED (seeded, geography read-only): 435 rows — one per Bahia municipality (416), except Salvador (19 zone Municípios, ZE 1–19); Camaçari is a single whole municipality (ZE 170/171 aggregated); shared/leaky TSE zones are cut at the municipal boundary. Code identifier: `municipality`. Leaderships are one record per person (`contact` UNIQUE) linked to N municipalities and N organizations; vote pledges are per leadership×municipality with `declaredVotes` (staff-entered, leader-visible) vs `estimatedVotes` (three scenarios, staff-only, hidden from the leader). Campaign production data was reset by the remodel migrations (public-site data untouched). Master plan: `docs/plans/remodelagem-municipios.md` (supersedes `remodelagem-pracas.md`). Details: "Campaign Municípios model" below.
|
||||
- Production is self-hosted on the homeserver (`jorgesolla1313.com.br`, behind the Cloudflare tunnel; container/database `teqo-1313`/`teqo_1313`). **There is no Vercel deploy anymore** — the Vercel deploy job, `vercel-promote.yml`, the Vercel scripts/`vercel.json` and the `VERCEL_*` repo secrets were removed in OPS50 (2026-08-17). The CI (`ci.yml` on `main`) is the verifier — full suite green — **plus the deploy step (OPS53, 2026-08-17)**: the `deploy` job (runs-on `host` on the workstation runner) streams `scripts/deploy-homeserver.sh` to the homeserver over SSH; the remote script builds the standalone image at the pushed SHA (BuildKit secrets from `~/stack/teqo-1313.env`), pushes it to the local registry (`localhost:5000`), applies pending migrations through the compose maintenance service `teqo-1313-migrate` **before** the rollout, and recreates the container. Merge em `main` verde == site atualizado. Runbook (rollback, falhas conhecidas): `docs/ops/teqo-1313-deploy.md`. **The production database lives on the homeserver Postgres (`teqo_1313`, migrated from Neon in OPS51, 2026-08-17)** — the full production content (contacts, signatures, subscriptions, campaign) was restored there via `pg_dump`/`pg_restore` (dump in `/srv/hdd/backups/teqo-neon-pre-migracao/`); Neon remains alive and untouched as the documented rollback (re-point `DATABASE_URL` in `~/stack/teqo-1313.env`). Media moved to the homeserver Garage S3 in OPS52 (2026-08-18): the `media` collection uploads via `@payloadcms/storage-s3` when the `S3_*` envs are set, and Payload proxies the files through `/api/media/file/...` (the bucket stays private). Production env lives in `~/stack/teqo-1313.env` (bucket `teqo-media`, endpoint `http://host.docker.internal:3900` — o container alcança o Garage no host via `extra_hosts: host-gateway` + regras ufw `allow from 10.0.11.0/24 to any port 3900` (INPUT e route/FWD); a workstation/tailnet usa `http://100.119.220.31:3900`, key `teqo-key`); a partial `S3_*` config aborts the boot, and no `S3_*` means local disk (dev/test). The 40 pre-existing media rows are RECOVERED (OPS52-media, 2026-08-18): 38/40 objects restaurados no bucket a partir do WordPress (38 capas servindo 200 em `/api/media/file/...`; exceções sem fonte: `fim-escala-6x1.jpg` e `jorgesolla.jpg`) — re-executar via `pnpm media:recover` (restaura objetos sem tocar no DB; runbook em `docs/plans/ops52-media-recuperar-arquivos-impl.md`; desde OPS52-media-guard o reconcile exige `MEDIA_RECOVER_CONFIRM=1` — guard de intenção explícita para escrita no bucket, `--dry-run`/`--verify` seguem sem flag); the URLs themselves are the same contract the proxy now serves. Never point dev/test databases at the homeserver prod DB either — the local guards (`guard-dev-db`, `assertTestDatabase`) still enforce `localhost`/`_test`-suffixed targets.
|
||||
- Production is self-hosted on the homeserver (`jorgesolla1313.com.br`, behind the Cloudflare tunnel; container/database `teqo-1313`/`teqo_1313`). **There is no Vercel deploy anymore** — the Vercel deploy job, `vercel-promote.yml`, the Vercel scripts/`vercel.json` and the `VERCEL_*` repo secrets were removed in OPS50 (2026-08-17). The CI (`ci.yml` on `main`) is the verifier — full suite green — **plus the deploy step (OPS53, 2026-08-17; windowed since OPS65, 2026-08-18)**: `ci.yml` no longer fires on every push — it runs in a **fixed 30-minute window** (`schedule */30` + `workflow_dispatch`), where a cheap gate job (`check`, host runner, no pnpm) reads the SHA deployed on the homeserver from `~/stack/docker-compose.yml` over SSH, diffs it against `main` HEAD and classifies "production change" using `.dockerignore` as the source of truth (docs/`.agents`/`.env*` changes skip; `scripts/`, `tests/`, `.forgejo/`, `AGENTS.md` count as production — conservative). No production change → suite + deploy skipped, run stays green; production change → full suite + deploy in the same window; dispatch always runs the full pipeline. The `deploy` job (runs-on `host` on the workstation runner) streams `scripts/deploy-homeserver.sh` to the homeserver over SSH; the remote script is idempotent ("already deployed" → skip), builds the standalone image at the pushed SHA (BuildKit secrets from `~/stack/teqo-1313.env`), pushes it to the local registry (`localhost:5000`), applies pending migrations through the compose maintenance service `teqo-1313-migrate` **before** the rollout, and recreates the container. Merge em `main` com mudança de produção verde == site atualizado em até ~1 h (janela de 30 min + suite + deploy). Runbook (rollback, falhas conhecidas): `docs/ops/teqo-1313-deploy.md`. **The agent-pool supervisor workflow was killed in OPS65** (the `*/10` tick cost 144 full `pnpm install`/day on the workstation; `agent-pool.yml` is gone, pool scripts/skills stay dormant). **The production database lives on the homeserver Postgres (`teqo_1313`, migrated from Neon in OPS51, 2026-08-17)** — the full production content (contacts, signatures, subscriptions, campaign) was restored there via `pg_dump`/`pg_restore` (dump in `/srv/hdd/backups/teqo-neon-pre-migracao/`); Neon remains alive and untouched as the documented rollback (re-point `DATABASE_URL` in `~/stack/teqo-1313.env`). Media moved to the homeserver Garage S3 in OPS52 (2026-08-18): the `media` collection uploads via `@payloadcms/storage-s3` when the `S3_*` envs are set, and Payload proxies the files through `/api/media/file/...` (the bucket stays private). Production env lives in `~/stack/teqo-1313.env` (bucket `teqo-media`, endpoint `http://host.docker.internal:3900` — o container alcança o Garage no host via `extra_hosts: host-gateway` + regras ufw `allow from 10.0.11.0/24 to any port 3900` (INPUT e route/FWD); a workstation/tailnet usa `http://100.119.220.31:3900`, key `teqo-key`); a partial `S3_*` config aborts the boot, and no `S3_*` means local disk (dev/test). The 40 pre-existing media rows are RECOVERED (OPS52-media, 2026-08-18): 38/40 objects restaurados no bucket a partir do WordPress (38 capas servindo 200 em `/api/media/file/...`; exceções sem fonte: `fim-escala-6x1.jpg` e `jorgesolla.jpg`) — re-executar via `pnpm media:recover` (restaura objetos sem tocar no DB; runbook em `docs/plans/ops52-media-recuperar-arquivos-impl.md`; desde OPS52-media-guard o reconcile exige `MEDIA_RECOVER_CONFIRM=1` — guard de intenção explícita para escrita no bucket, `--dry-run`/`--verify` seguem sem flag); the URLs themselves are the same contract the proxy now serves. Never point dev/test databases at the homeserver prod DB either — the local guards (`guard-dev-db`, `assertTestDatabase`) still enforce `localhost`/`_test`-suffixed targets.
|
||||
- Donations are NOT handled in this app — they run through QueroApoiar (`apoiar.me/jorgesolla`, TSE-homologated). The site only needs a "Doar" link/CTA out to that URL.
|
||||
|
||||
- **Embasamento de produto/domínio:** `docs/research/` guarda o compêndio de literatura (campanha de DF na Bahia, geografia do voto, cartografia eleitoral) e o relatório de discovery aprovado (2026-07-21) com o playbook dado→decisão. Para métricas, análises territoriais, mapa e priorização em `/campanha`, consulte-o antes de inventar — o kernel: a disputa de DF é conta de quociente fragmentada; leitura útil é relativa e local (captura, LQ, quantis, cobertura de meta por pledges), nunca % estadual absoluto.
|
||||
|
|
@ -80,7 +80,7 @@ curl -X POST "https://<prod-domain>/api/revalidate?tag=global_privacy-policy" \
|
|||
|
||||
- **Auth:** send the secret via `x-revalidate-secret` or `Authorization: Bearer <secret>`; it is compared to `REVALIDATE_SECRET` with a constant-time check.
|
||||
- `REVALIDATE_SECRET` must be set in the **production** env (and in your local env if you want to test the endpoint). It is documented in `.env.example`.
|
||||
- **Tag:** optional `?tag=` query or JSON body `{ "tag": "..." }` (query wins). Allowlist: `posts` (default), `global_privacy-policy`, `election-tse` (bust after re-running `pnpm db:seed:tse` so the cached elections-tab reads refresh), `municipality-catalog` (bust after a migration/seed that adds or renames a município so chip indexes and `unstable_cache` loaders refresh), `social-feed` (bust after a direct-DB write to the `social-feed-settings` global — e.g. an admin-less seed of the YouTube feed config; admin edits self-revalidate). Unknown tag → `400`.
|
||||
- **Tag:** optional `?tag=` query or JSON body `{ "tag": "..." }` (query wins). Allowlist: `posts` (default), `global_privacy-policy`, `election-tse` (bust after re-running `pnpm db:seed:tse` so the cached elections-tab reads refresh), `municipality-catalog` (bust after a migration/seed that adds or renames a município so chip indexes and `unstable_cache` loaders refresh), `social-feed` (bust after a direct-DB write to the `social-feed-settings` global — e.g. an admin-less seed of the YouTube/Instagram feed config; admin edits self-revalidate). Unknown tag → `400`.
|
||||
- **Responses:** `200 { revalidated: true, tag: '...' }` on success; `401` if the secret is missing/wrong; `500` if `REVALIDATE_SECRET` is not configured on the server.
|
||||
- This POST is the required last step of the post-seed / direct-DB-change runbook.
|
||||
|
||||
|
|
@ -158,7 +158,7 @@ The artifact is at **v3**: v2 added E8's `campoFederalVotesByYear` / `federalTal
|
|||
|
||||
1. Confirm `DATABASE_URL` is `postgresql://teqo:teqo@localhost:5432/teqo` and `.env.test` points to `teqo_test`; never use Neon for development, tests, E2E, or local builds. In a provisioned worktree (`pnpm worktree next`) the values come from its `.env.local` / `.env.test.local` (`teqo_wt<slot>` / `teqo_wt<slot>_test`, dev port `3100+slot`) — read them there instead of assuming the main-repo names.
|
||||
2. Run `pnpm db:start`, `pnpm migrate:status`, and `DATABASE_URL=postgresql://teqo:teqo@localhost:5432/teqo_test pnpm migrate:status`; every migration must show `Ran: Yes`.
|
||||
3. Run `pnpm generate:types`, `pnpm generate:importmap` when components changed, `pnpm exec tsc --noEmit`, `pnpm lint` (zero warnings — the script enforces `--max-warnings=0`), `pnpm format:check` (Prettier is the formatting authority; `pnpm format` fixes), `pnpm exec knip` (dead files/dependencies are CI-blocking; delete what your change orphaned), `pnpm check:cycles` (madge — zero circular imports), `pnpm test` (unit + int), and `pnpm build` against the local database. Payload CLI scripts (`migrate`, `generate:*`, `payload`) and the build migrate step use `--conditions=react-server` so `server-only` modules load correctly outside Next.js. **O e2e não roda mais no gate local (OPS59):** ele roda **uma vez, no CI** (PR e main — gateia merge e deploy); local opcional para feedback antecipado: `pnpm test:e2e:affected`.
|
||||
3. Run `pnpm generate:types`, `pnpm generate:importmap` when components changed, `pnpm exec tsc --noEmit`, `pnpm lint` (zero warnings — the script enforces `--max-warnings=0`), `pnpm format:check` (Prettier is the formatting authority; `pnpm format` fixes), `pnpm exec knip` (dead files/dependencies are CI-blocking; delete what your change orphaned), `pnpm check:cycles` (madge — zero circular imports), `pnpm test` (unit + int), and `pnpm build` against the local database. Payload CLI scripts (`migrate`, `generate:*`, `payload`) and the build migrate step use `--conditions=react-server` so `server-only` modules load correctly outside Next.js. **O e2e não roda mais no gate local (OPS59):** ele roda **uma vez, no CI** (PR e main — gateia merge e deploy); local opcional para feedback antecipado: `pnpm test:e2e:affected` (gera `--no-deps` para runs filtrados — S6-FOLLOWUP: no dev mode a cadeia de dependencies dos projects arrasta os arquivos das dependências via closure; filtros manuais locais: `pnpm test:e2e --no-deps -- <path>` ou `--no-deps --project=<família>`).
|
||||
- Never run `knip --fix` blind: when knip's module graph is incomplete (it still cannot load `payload.config.ts` — ledgered as P3), `--fix` deletes exports that migrations/tests still reference. Verify each removal (e.g. `git grep -w <symbol>`) before deleting.
|
||||
- Run gate commands bare — never piped (`pnpm test | tail` swallows the exit code, and a real failure was masked exactly this way during Pass 2). Large outputs are captured by the terminal; read them from there.
|
||||
4. Scan every edited runtime source file with Aikido and resolve new findings before handoff. Do not expand hardening work into unrelated pre-existing findings without an explicit scope change.
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ Agentes **nunca** recebem `DATABASE_URL` de prod e nunca setam `ALLOW_REMOTE_DB`
|
|||
|
||||
```text
|
||||
claim → feature branch → PR --base main → CI PR green (cascade + skips) → auto-merge em main
|
||||
main → ci.yml full suite verde → job `deploy` (homeserver, OPS53 — merge em main == site atualizado)
|
||||
main → ci.yml (janela de 30 min, OPS65) full suite verde → job `deploy` (homeserver, OPS53 — merge com mudança de produção == site atualizado em ~30 min + suite/deploy)
|
||||
```
|
||||
|
||||
**Skills:** `plan-issue` (intenção + Issues) → `work-issue` (humano: Issue já claimada → impl plan → confirmação → execução) ou `agent-work-issue` (pool: já claimada → impl plan → execução sem pausa) → `/simplify` → `capture-review-debts` → PR `--base main` → `project-status`. `docs/roadmap.md` = legado congelado; fonte canônica = GitHub Issues.
|
||||
|
|
@ -34,19 +34,19 @@ main → ci.yml full suite verde → job `deploy` (homeserver, OPS53 — merge e
|
|||
|
||||
## Comandos
|
||||
|
||||
| Comando | Faz |
|
||||
| ------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| `pnpm agent:claim [-- --dry-run]` | Fila ready+unblocked por prio → `in-progress` + brief |
|
||||
| `pnpm worktree next [--issue N] [--stay]` | Claim determinístico (mesma fila/lock do claim) → worktree + provisionamento |
|
||||
| `pnpm agent:register -- --id X --title T [--prio P1] [--depends A,B] [--plan docs/plans/x.md] [--model slug]` | Cria Issue (`--plan` ⇒ `blocked` até `agent:ready`; sem plano ⇒ `ready`) |
|
||||
| `pnpm agent:ready -- --issue N[,N…]` | Pós-merge do plano: `blocked`→`ready` (só Issues com link `docs/plans/`) |
|
||||
| `pnpm agent:status` | Overview / fila / mermaid |
|
||||
| `pnpm agent:prioritize -- <issue> <P0..P3>` | Troca `prio:*` |
|
||||
| `pnpm agent:file-miss -- --title ...` | Issue `kind:agent-miss` |
|
||||
| `pnpm agent:pool -- status\|tick --dry-run\|doctor` | Pool Cloud; start/stop via `gh workflow run agent-pool.yml` |
|
||||
| `pnpm push [-- -u origin HEAD …]` | Canônico: ensure-deps + gate:push + push |
|
||||
| `pnpm configure:branch-protection [-- --dry-run]` | Proteção de `main`: required status check `CI (PR) / checks` (rollup do ci-pr; idempotente — cria/atualiza/no-op) |
|
||||
| `pnpm db:seed:minimal` | DB mínimo sintético |
|
||||
| Comando | Faz |
|
||||
| ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `pnpm agent:claim [-- --dry-run]` | Fila ready+unblocked por prio → `in-progress` + brief |
|
||||
| `pnpm worktree next [--issue N] [--stay]` | Claim determinístico (mesma fila/lock do claim) → worktree + provisionamento |
|
||||
| `pnpm agent:register -- --id X --title T [--prio P1] [--depends A,B] [--plan docs/plans/x.md] [--model slug]` | Cria Issue (`--plan` ⇒ `blocked` até `agent:ready`; sem plano ⇒ `ready`) |
|
||||
| `pnpm agent:ready -- --issue N[,N…]` | Pós-merge do plano: `blocked`→`ready` (só Issues com link `docs/plans/`) |
|
||||
| `pnpm agent:status` | Overview / fila / mermaid |
|
||||
| `pnpm agent:prioritize -- <issue> <P0..P3>` | Troca `prio:*` |
|
||||
| `pnpm agent:file-miss -- --title ...` | Issue `kind:agent-miss` |
|
||||
| `pnpm agent:pool -- status\|tick --dry-run\|doctor` | Pool Cloud **dormente (OPS65)** — o workflow `agent-pool.yml` foi removido; dispatch falha 404; scripts/skill ficam para histórico |
|
||||
| `pnpm push [-- -u origin HEAD …]` | Canônico: ensure-deps + gate:push + push |
|
||||
| `pnpm configure:branch-protection [-- --dry-run]` | Proteção de `main`: required status check `CI (PR) / checks` (rollup do ci-pr; idempotente — cria/atualiza/no-op) |
|
||||
| `pnpm db:seed:minimal` | DB mínimo sintético |
|
||||
|
||||
Labels: `ready|in-progress|blocked|done|in-prod`, `prio:*`, `kind:*`, `needs:*`.
|
||||
|
||||
|
|
@ -69,14 +69,15 @@ Arquivos de "lista" que N agentes escrevem em paralelo (changelog, plans, migra
|
|||
|
||||
## CI por alvo
|
||||
|
||||
| Workflow | Trigger | Banco | Passos |
|
||||
| ------------------------------------ | -------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci-pr.yml` | PR → `main` | service Postgres 17 | Fase 1 barata → fase 2 cara; skips via `ci-scope.mjs`; fail-fast cancela o run no 1º job vermelho; rollup `checks` |
|
||||
| `ci.yml` | push / dispatch `main` | service Postgres | Full sempre; fail-fast cancela o run no 1º job vermelho; rollup `checks`; job `deploy` (runs-on `host`) publica no homeserver via `scripts/deploy-homeserver.sh` (OPS53) |
|
||||
| `issue-done-on-main-merge.yml` | PR merged → `main` (same-repo) | — | `Closes`/`Fixes` → `done` + `in-prod` (PAT `FORGEJO_API_TOKEN`; `GITHUB_TOKEN` 403 em Issues) |
|
||||
| `plan-issue-ready-on-main-merge.yml` | PR merged → `main` (same-repo) | — | `Related #N` aguardando plano → `ready` (OPS18; soft-skip; mesmo PAT) |
|
||||
| `agent-pr-ready-automerge.yml` | PR same-repo → `main` (open/sync/…) | — | Safety net via `forgejo-pr-automerge.mjs` (plain Node): espera o rollup `checks` e mergea por rebase com `FORGEJO_API_TOKEN` (o `GITHUB_TOKEN` nativo não tem write no repo — o push do merge é rejeitado com 409); draft `cursor/*` → Ready; draft não-`cursor/*` = veto, skip |
|
||||
| `agent-pool.yml` | schedule / PR closed `main` / dispatch | — | Supervisor do pool (`POOL_GITHUB_TOKEN`) |
|
||||
| Workflow | Trigger | Banco | Passos |
|
||||
| ------------------------------------ | ----------------------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `ci-pr.yml` | PR → `main` | 2× service Postgres 17 | Job único `checks` sequencial (OPS62 X1): guards → lint→format→typecheck→knip→cycles→unit→int→build→e2e; skips via `ci-scope.mjs` (step `scope`); **fail-fast estrutural** — step vermelho interrompe o job, o run falha e o slot é liberado; e2e 1 processo com `PLAYWRIGHT_WORKERS=4`; 2 services por nome na rede do job (`postgres-int`/`postgres-build`, sem publish host) |
|
||||
| `ci.yml` | schedule `*/30` / dispatch `main` | 2× service Postgres 17 | Janela fixa (OPS65): gate `gate` (host, main-only, sem pnpm) classifica mudança de produção desde a **revision do container rodando** no homeserver (`.dockerignore` = fonte da verdade; fail-open; incapaz de classificar → run **vermelho**); sem mudança → suite + deploy skipped, run verde; com mudança → job único `checks` sequencial (mesma mecânica X1) + job `deploy` (runs-on `host`) publica no homeserver via `scripts/deploy-homeserver.sh` (OPS53, guard "already deployed") |
|
||||
| `issue-done-on-main-merge.yml` | PR merged → `main` (same-repo) | — | `Closes`/`Fixes` → `done` + `in-prod` (PAT `FORGEJO_API_TOKEN`; `GITHUB_TOKEN` 403 em Issues) |
|
||||
| `plan-issue-ready-on-main-merge.yml` | PR merged → `main` (same-repo) | — | `Related #N` aguardando plano → `ready` (OPS18; soft-skip; mesmo PAT) |
|
||||
| `agent-pr-ready-automerge.yml` | PR same-repo → `main` (open/sync/…) | — | Safety net via `forgejo-pr-automerge.mjs` (plain Node): espera o rollup `checks` e mergea por rebase com `FORGEJO_API_TOKEN` (o `GITHUB_TOKEN` nativo não tem write no repo — o push do merge é rejeitado com 409); draft `cursor/*` → Ready; draft não-`cursor/*` = veto, skip |
|
||||
|
||||
`agent-pool.yml` foi **removido no OPS65** (pool dormente; o tick `*/10` custava 144 `pnpm install`/dia na workstation).
|
||||
|
||||
Action runtimes: `actions/checkout@v5`, `actions/setup-node@v5`, `pnpm/action-setup@v6` e `styfle/cancel-workflow-action@0.13.1` usam Node 24 nativo — sem `FORCE_JAVASCRIPT_ACTIONS_TO_NODE24`.
|
||||
|
||||
|
|
@ -90,9 +91,9 @@ Fast gate: `pnpm gate:fast`. Push: `pnpm push`.
|
|||
| `CURSOR_API_KEY` | Supervisor do pool (Cursor Cloud) |
|
||||
| `POOL_GITHUB_TOKEN` | PAT `actions:write` + `issues:write` (variables do pool; `GITHUB_TOKEN` costuma 403) |
|
||||
|
||||
Branch protection de `main` (aplicada em 2026-08-18, OPS61): required status check `CI (PR) / checks` (o rollup do `ci-pr.yml` — único contexto que cobre a cascata inteira), `strict=false`, 0 reviews. O `waitForChecks` do safety net espera esse mesmo rollup antes de mergear (o próprio status do job é `pending` durante o run e nunca entra no veredito); a regra no servidor é o gate real — o Forgejo bloqueia o merge POST com 405 se o contexto exigido não estiver verde, inclusive merges manuais via API (a PR #52 entrou em main com CI vermelho por merge manual). Reaplicar/consertar drift: `pnpm configure:branch-protection` (idempotente).
|
||||
Branch protection de `main` (aplicada em 2026-08-18, OPS61): required status check `CI (PR) / checks` (o rollup do `ci-pr.yml` — único contexto que cobre a cascata inteira), `strict=false`, 0 reviews. O `waitForChecks` do safety net espera esse mesmo rollup antes de mergear (o próprio status do job é `pending` durante o run e nunca entra no veredito); a regra no servidor é o gate real — o Forgejo bloqueia o merge POST com 405 se o contexto exigido não estiver verde, inclusive merges manuais via API (a PR #52 entrou em main com CI vermelho por merge manual). **OPS64:** o CLI nunca confia no rollup sozinho — varre os statuses individuais e falha em qualquer `failure`/`error` (pin em `forgejoApi.unit.spec.ts`, cenário run 607: rollup verde com shard de e2e vermelho → throw). Com o desenho de job único do OPS62 (sem matrix, sem shards) o status do job `checks` já é o veredito honesto da cascata — o bug de agregação do parent de matrix deixou de existir estruturalmente. Reaplicar/consertar drift: `pnpm configure:branch-protection` (idempotente).
|
||||
|
||||
Deploy (OPS53): o job `deploy` do `ci.yml` roda no host do runner (workstation) e streama `scripts/deploy-homeserver.sh` para o homeserver via SSH — build no homeserver (secrets de `~/stack/teqo-1313.env`), registry `localhost:5000`, migrate pelo serviço de maintenance `teqo-1313-migrate` antes do rollout, smoke pós-deploy. Nenhum secret novo no Forgejo. Runbook (rollback, falhas conhecidas): `docs/ops/teqo-1313-deploy.md`. O deploy Vercel (`vercel-promote.yml`, scripts, `vercel.json`) foi removido no OPS50.
|
||||
Deploy (OPS53 + OPS65): o `ci.yml` do main roda em **janela fixa de 30 min** (`schedule */30` + `workflow_dispatch` — não dispara mais a cada push). O job `gate` (host, sem pnpm) lê a **revision do container rodando** no homeserver (label `org.opencontainers.image.revision` — o compose pode mentir após rollback falho) e classifica "mudança de produção" pelos padrões do `.dockerignore` (fonte da verdade do artefato; `docs/`, `.agents/`, `.env*` viram skip; `scripts/`, `tests/`, `.forgejo/`, `AGENTS.md` contam como produção — conservador). Deployed == HEAD → suite e deploy skipped (run verde); estado desconhecido (sem revision) → suite roda fail-open; gate incapaz de classificar → suite roda e o run fica **vermelho** (nunca blackout). Com mudança → suite full verde → job `deploy` (runs-on `host`) streama `scripts/deploy-homeserver.sh` para o homeserver via SSH — build no homeserver (secrets de `~/stack/teqo-1313.env`), registry `localhost:5000`, migrate pelo serviço de maintenance `teqo-1313-migrate` antes do rollout, smoke pós-deploy; o script é idempotente (revision do container já no SHA → skip verde "already deployed"). Nenhum secret novo no Forgejo. Runbook (rollback, falhas conhecidas): `docs/ops/teqo-1313-deploy.md`. O deploy Vercel (`vercel-promote.yml`, scripts, `vercel.json`) foi removido no OPS50.
|
||||
|
||||
## Cursor Cloud
|
||||
|
||||
|
|
@ -100,7 +101,11 @@ Deploy (OPS53): o job `deploy` do `ci.yml` roda no host do runner (workstation)
|
|||
|
||||
## Agent pool
|
||||
|
||||
Supervisor remoto (`agent-pool.yml`): schedule + replenish em merge → `main` + dispatch. Workers PR `--base main`. Default model `composer-2.5`. **Secret `POOL_GITHUB_TOKEN`** obrigatório se `GITHUB_TOKEN` 403 em `/actions/variables`. Doctor: `pnpm agent:pool -- doctor`. Skill: `agent-pool`.
|
||||
**Dormente (OPS65)** — o workflow `agent-pool.yml` foi removido e o dispatch
|
||||
via CLI falha 404; scripts/skills ficam para histórico. O que foi:
|
||||
Supervisor remoto (`agent-pool.yml`): schedule + replenish em merge → `main` +
|
||||
dispatch. Workers PR `--base main`. Default model `composer-2.5`. Doctor:
|
||||
`pnpm agent:pool -- doctor`. Skill: `agent-pool`.
|
||||
|
||||
## Guardrails / leitura
|
||||
|
||||
|
|
|
|||
|
|
@ -4,8 +4,14 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
---
|
||||
|
||||
**S6-FOLLOWUP** — CLI Playwright 1.58.2 e filtros e2e locais: `pnpm test:e2e:affected` rodava a suíte completa silenciosamente em runs selecionados. Causa raiz (medida com o binário do repo, config real): o commander parseia posicionais e `-g`/`--list` funcionam — quem arrastava a suíte era o closure de dependências dos projects no dev mode (`setup ← campaign ← frontend ← admin` em `playwright.config.ts`): `collectProjectsAndTestFiles` filtra os arquivos por project, mas `buildProjectsClosure` repõe todos os arquivos de cada project-dependência — filtrar um spec do `frontend` puxava `campaign` (160) + `setup` (2), 177 no total com o próprio arquivo (15); `admin` puxava a suíte inteira. Em prod mode (`CI=1`) os projects não têm deps e o filtro sempre funcionou (por isso o CI selecionado estava correto). Fix: `run-e2e-affected.mjs` agora gera `test:e2e <passthrough verbatim> --no-deps -- <paths>` via helpers puros novos em `scripts/lib/playwright-e2e-args.mjs` (unit-testados, `tests/unit/playwrightE2eArgs.unit.spec.ts`) — `--no-deps` desliga o closure em runs filtrados (suíte completa mantém a cadeia OPS34 de prewarm); de quebra, o passthrough do script foi corrigido (`pnpm test:e2e:affected -- tests/x.spec.ts` descartava o path — pnpm consome o `--` e o argv nunca o continha; agora `parsePassthroughArgs` só remove um `--` líder e repassa o resto verbatim, preservando `-g grade`). Hardening: `scripts/run-e2e-affected.mjs` entrou em `HIGH_RISK_EXACT` (era o espelho local do job e2e sem gate — um PR só de runner não rodaria e2e). Docs: receitas de filtro no `playwright.config.ts` (posicional exige `--no-deps`; `--project=<família> --no-deps`; `-g`/`--list` funcionam), header do script e nota no AGENTS.md. Sem mudança de specs, CI (`--shard`) ou `gate:ci`. Verificação: unit 2343+ verdes; contagem por `--list` do binário com a forma final (18); CI do PR roda o e2e completo (o diff toca `playwright.config.ts` e `run-e2e-affected.mjs`, high-risk). Débito absorvido: hang do `pnpm test:e2e` via pnpm neste worktree (pré-existente, ambiente — binário direto funciona; não escopo). Impl plan: `docs/plans/s6-followup-playwright-filtros-cli-ignorados-impl.md`.
|
||||
|
||||
**S2** — seção "Acompanhe de perto" da home de campanha (jorgesolla1313.com.br) passa a incluir os vídeos do canal oficial do YouTube (`@JorgeSollaDep`), estendendo o board da S1. Fonte automática servidor-side: global `SocialFeedSettings` nova (grupo `Configurações`, read/update admin-only — a chave da API nunca vaza pelo REST), com kill switch `enabled` ("Pausar feed"), toggle `youtubeEnabled`, chave + channel ID, `youtubeMaxItems` (1–5, default 3) e `excludedItems` (platform+id+motivo opcional — mesmo mecanismo/lugar da S3), migration `20260818_111748_add_social_feed_settings` não destrutiva (editada para conter só o DDL — o `migrate:create` regenerava drift de migrations hand-written sem sidecar JSON de 20260811). Loader `src/utilities/youtubeFeed.ts` (irmão de `posts.ts`, pinado no spec de convenções): parsers/format puros (`formatYouTubeViews` pt-BR "12,4 mil"/"1,2 mi", thumbnails maxres??high??medium), fetch Data API v3 em dois passos (search → statistics, `fetchImpl`/`YOUTUBE_API_BASE_URL` injetáveis), `unstable_cache` tag `social-feed` + `revalidate: 300` (TTL da entrada, não da página — o bug do S1 era page-level); **fail-closed com snapshot persistido por SQL direto** (`payload.db.drizzle`, sem hooks — `revalidateTag` dentro de `unstable_cache` LANÇA no Next 15.4, verificado no source; o snapshot cru pré-exclusão sobrevive a edições de settings por merge do update), exclusões aplicadas na leitura. Card generalizado `CampaignArticleCard` → `CampaignContentCard` (git mv; `external?: boolean` → `<a target="_blank" rel="noopener noreferrer">`); a seção mescla artigos visíveis + vídeos elegíveis por recência (grande = mais recente — aceite S2; degrade para o comportamento S1 sem config), meta "há X · N visualizações" (relativa < 48h, absoluta além), link "YouTube →" derivado do channelId; carrossel mobile renomeado para "Conteúdos recentes". next.config ganha `i.ytimg.com` + host local do stub no remotePatterns. Testes: 15 units novas (formatters, parsers, eligibility, fetch com fetchImpl fake); e2e com stub HTTP node (`tests/e2e/youtube-stub.mjs`, webServer do Playwright vira array, porta = dev+1000; `POST /__stub/state` alterna ok/fail; thumbnails servidas localmente) — 4 testes novos no describe serial da seção (full-state com exclusão + link externo + carrossel, fail-closed sem snapshot, snapshot persistente com maxItems mudando na API down, kill switch) + reset de settings no beforeAll; conventions specs atualizados (pin do youtubeFeed, settle após about:blank). Verificação: unit 2306 + int 791 verdes; e2e frontend 14/14 dev e 6/6 prod-mode (`E2E_PROD=1` — valida TTL+tags+snapshot no build real); lint/format/tsc/knip/cycles/build verdes. `/simplify` 3 reviewers (sem P0): P1 corrigido — label do kill switch invertido ("Pausar feed" marcado = ativo → "Feed ativo"); P2 absorvidos (className do link do header extraída, `Promise.all` posts+feed no cache frio, comentário do sentinela 0 do merge, helper único `tests/helpers/youtubeStub.ts` para a porta do stub, `waitForHomeSectionState` fundido no `waitForHomeHTML` com orçamento 12s do S1, precondição do persist documentada); débito REGISTRADO (#40, prio:P2, depends #18): o `validate` do `itemId` lê `data.platform` que é sempre undefined (Payload passa o doc inteiro; verificado no source) — produção sem validação de ID de vídeo, e o e2e depende dessa mortandade (ids do stub de 20 chars); correção em dupla documentada na issue. Descartados com justificativa: ramo maxres do search (pinned por teste), tag `social-feed` fora da convenção `global_*` (precedente election-tse/municipality-catalog), remotePattern `localhost/thumbs` incondicional (decisão deliberada dos 3 modos e2e), persist não-atômico (comentado); achados visuais do design-vision mapeados para a Issue #33 (separação visual branco-sobre-branco, fora de escopo por decisão do gate).
|
||||
|
||||
**S6** — home de campanha (jorgesolla1313.com.br) sem carrossel no desktop: as seções "Por que essa eleição importa" (3 cards) e "Nossa caminhada" (6 cards) mostram agora todo o conteúdo de uma vez em ≥1024px — grade estática 3 colunas (problem: 3×437px, bandeiras: 3×2 com altura por conteúdo, padding `p-4`), sem auto-avanço, sem chips/indicadores e sem `aria-current`. Mobile (<1024px) 100% preservado: carrossel com auto-avanço ~4s, chips sincronizados, swipe — componente e geometria mobile intocados. Padrão S1 (renderização-irmã com toggle CSS `hidden lg:grid`/`lg:hidden`): grade server-rendered (zero JS no desktop) + carrossel client embrulhado; os dois cards extraídos do `CampaignCarousel` para `CampaignProblemCard`/`CampaignFlagCard` (presentacionais, fonte única do markup, `size='spacious'` só na grade) e o contrato da grade (data-grid + aria-label + 3 colunas) vive num `CampaignCardGrid` local do page. O carrossel ficou byte-equivalente (só re-roteia os cards; unit tests intocados) e ganhou guard de `display:none` no auto-avanço — o timer nunca roda no desktop (chain morto numa subárvore oculta). Geometria: a seção flags recalibrada no desktop (`height: clamp(418px, calc(807.7px - 28.13vw), 520px)`, âncoras medidas em 1024/1280/1440+, respiro ≥30px, `overflow: hidden` para zoom de texto ≥125% não pintar sobre o footer); a seção problem manteve a geometria (respiro ~31px). Zero schema/migration/Consent; mesma copy/imagens/ordem; S1 e o resto da home intocados. Verificação: unit 2318 + int 791 verdes, e2e frontend 11/11 (novo teste de grade desktop com invariantes 3×1/3×2, ausência de regiões/chips/`aria-current`, respiro ≥24 e `scrollHeight ≤ clientHeight` em 1024/1280/1440/1920; teste de carrossel migrado para viewport mobile 390px com auto-avanço + chips; swipe/mobileSpacing intactos), lint/format/typecheck/knip/cycles/build verdes. `/simplify` 3 reviewers: `lg:` órfãos removidos do carrossel, grade extraída em `CampaignCardGrid`, `overflow: hidden` (zoom ≥125%), guard do timer, `document.fonts.ready` + eixo x + pino de clip no e2e, âncoras no comentário do clamp. Débitos: Issue #58 registrada (S6-FOLLOWUP — CLI do Playwright 1.58.2 ignora `--grep`/posicionais e o `test:e2e:affected` roda a suíte completa; `depends: [S6]`); defer com gatilho para os literais de gap da grade (recalibração Penpot do carrossel); descartados contratos de tipo dos cards (armadilha knip), aria-labels duplicados (copy pinada no e2e) e pino de tablet 768–1023. Impl plan: `docs/plans/home-campanha-sem-carrossel-desktop-impl.md`.
|
||||
|
||||
**S3** — seção "Acompanhe de perto" da home de campanha (jorgesolla1313.com.br) passa a incluir os posts do Instagram oficial, completando o board do plano-site §4.2 (artigos S1 + YouTube S2 + Instagram). Fonte automática servidor-side: loader irmão `src/utilities/socialFeed/instagramFeed.ts` (os feeds externos ganharam o subfolder `socialFeed/` — o pin da S2 predizia exatamente isso quando a segunda plataforma entrasse; `git mv` do youtubeFeed + imports atualizados): Graph API (`GET /{ig-user-id}/media` com `children{media_url,thumbnail_url}` p/ carrossel + `GET /{ig-user-id}?fields=username`), `unstable_cache` tag `social-feed` + `revalidate: 300`, snapshot cru (`{ username, posts }`, pré-exclusão) persistido via SQL direto (padrão anti-`revalidateTag`-no-cache da S2), exclusões aplicadas na leitura, **refresh de token automático** (refresh-on-failure + retry 1x, token renovado persistido por SQL direto; nota honesta no admin: o refresh endpoint só renova tokens de Instagram Login — page tokens business caem no fail-closed + rotação manual). Global `SocialFeedSettings` ganha `instagramEnabled/AccessToken/UserId/MaxItems` + `instagramFeedSnapshot` (hidden) — `excludedItems` já cobria `platform: 'instagram'` desde a S2, sem migration no mecanismo; migration `20260818_192948_add_instagram_social_feed_fields` não destrutiva (DDL revisado, sem o drift do `migrate:create` da S2). **Picker de exclusão no admin** (requisito nº 1 da intenção — posts de grade): primeiro componente custom do repo (`src/components/admin/InstagramPostExclusionPicker.tsx`, campo `ui` na global, path string + importmap regenerado — o import direto de `@payloadcms/ui` na config quebra o `generate:importmap` no tsx por causa do `.css` do react-image-crop; com path string o scanner resolve sem carregar o módulo); lista os posts do snapshot (thumbnail + legenda + data + ID) com toggle "Não exibir"/"Reexibir" + motivo opcional que escreve em `excludedItems` via `useField`. UI: `CampaignContentCardData.coverAspect` (`'video'` default — S1/S2 intactos; `'square'` 1:1 do rascunho aprovado para IG), badge "Instagram", título = legenda (fallback "Publicação no Instagram" para post sem legenda — entra no automático para exclusão manual), meta = data relativa, clique no `permalink` (nova aba, `noopener`), link do header "Seguir no Instagram →" (copy do rascunho aprovado; username derivado da API — com API fora e sem snapshot o link some junto com os cards, divergência documentada do "YouTube →" que sobrevive por ter o channelId configurado). next.config ganha `https://*.cdninstagram.com/**`. Testes: 16 units novas (parsers com caption null/carrossel/item sem permalink, thumbnail por media_type, eligibility, fetch + refresh-retry com `fetchImpl`); e2e: stub irmão `tests/e2e/instagram-stub.mjs` (porta dev+2000; a derivação da porta virou `tests/helpers/socialStub.ts` — rename do youtubeStub.ts mantendo UMA spelling), 3 testes novos no describe serial (full-state com exclusão + fallback de legenda + aspect 1:1 + link do perfil + carrossel, fail-closed sem snapshot, snapshot persistente com maxItems mudando na API down) + kill switch estendido com IG configurado + smoke do picker no admin (seed do snapshot via REST, toggle, Salvar, verificação do `excludedItems`). Verificação: unit 2351 + int 791 verdes; gate:fast/lint/format/tsc/knip (exit 0 — o erro de load do payload.config segue o ledger P3)/cycles/build verdes; e2e local: describe serial 9/9 + smoke admin 1/1 (rodando os projetos em sequência — em paralelo com `--no-deps` o `seedTestUser` dos dois beforeAll colide no mesmo usuário e quebra o run, artefato da invocação local, não do produto; o CI roda na cadeia de dependências). Detalhe do debug: o clique via CDP do MCP de browser não dispara eventos de input (ambiente do MCP, não do app — `el.click()` e o runner real funcionam).
|
||||
|
||||
**S2** — seção "Acompanhe de perto" da home de campanha (jorgesolla1313.com.br) passa a incluir os vídeos do canal oficial do YouTube (`@JorgeSollaDep`), estendendo o board da S1. Fonte automática servidor-side: global `SocialFeedSettings` nova (grupo `Configurações`, read/update admin-only — a chave da API nunca vaza pelo REST), com kill switch `enabled` ("Pausar feed"), toggle `youtubeEnabled`, chave + channel ID, `youtubeMaxItems` (1–5, default 3) e `excludedItems` (platform+id+motivo opcional — mesmo mecanismo/lugar da S3), migration `20260818_111748_add_social_feed_settings` não destrutiva (editada para conter só o DDL — o `migrate:create` regenerava drift de migrations hand-written sem sidecar JSON de 20260811). Loader `src/utilities/youtubeFeed.ts` (irmão de `posts.ts`, pinado no spec de convenções): parsers/format puros (`formatYouTubeViews` pt-BR "12,4 mil"/"1,2 mi", thumbnails maxres??high??medium), fetch Data API v3 em dois passos (search → statistics, `fetchImpl`/`YOUTUBE_API_BASE_URL` injetáveis), `unstable_cache` tag `social-feed` + `revalidate: 300` (TTL da entrada, não da página — o bug do S1 era page-level); **fail-closed com snapshot persistido por SQL direto** (`payload.db.drizzle`, sem hooks — `revalidateTag` dentro de `unstable_cache` LANÇA no Next 15.4, verificado no source; o snapshot cru pré-exclusão sobrevive a edições de settings por merge do update), exclusões aplicadas na leitura. Card generalizado `CampaignArticleCard` → `CampaignContentCard` (git mv; `external?: boolean` → `<a target="_blank" rel="noopener noreferrer">`); a seção mescla artigos visíveis + vídeos elegíveis por recência (grande = mais recente — aceite S2; degrade para o comportamento S1 sem config), meta "há X · N visualizações" (relativa < 48h, absoluta além), link "YouTube →" derivado do channelId; carrossel mobile renomeado para "Conteúdos recentes". next.config ganha `i.ytimg.com` + host local do stub no remotePatterns. Testes: 15 units novas (formatters, parsers, eligibility, fetch com fetchImpl fake); e2e com stub HTTP node (`tests/e2e/youtube-stub.mjs`, webServer do Playwright vira array, porta = dev+1000; `POST /__stub/state` alterna ok/fail; thumbnails servidas localmente) — 4 testes novos no describe serial da seção (full-state com exclusão + link externo + carrossel, fail-closed sem snapshot, snapshot persistente com maxItems mudando na API down, kill switch) + reset de settings no beforeAll; conventions specs atualizados (pin do youtubeFeed, settle após about:blank). Verificação: unit 2306 + int 791 verdes; e2e frontend 14/14 dev e 6/6 prod-mode (`E2E_PROD=1` — valida TTL+tags+snapshot no build real); lint/format/tsc/knip/cycles/build verdes. `/simplify` 3 reviewers (sem P0): P1 corrigido — label do kill switch invertido ("Pausar feed" marcado = ativo → "Feed ativo"); P2 absorvidos (className do link do header extraída, `Promise.all` posts+feed no cache frio, comentário do sentinela 0 do merge, helper único `tests/helpers/youtubeStub.ts` para a porta do stub, `waitForHomeSectionState` fundido no `waitForHomeHTML` com orçamento 12s do S1, precondição do persist documentada); débito REGISTRADO (#40, prio:P2, depends #18): o `validate` do `itemId` lê `data.platform` que é sempre undefined (Payload passa o doc inteiro; verificado no source) — produção sem validação de ID de vídeo, e o e2e depende dessa mortandade (ids do stub de 20 chars); correção em dupla documentada na issue. Descartados com justificativa: ramo maxres do search (pinned por teste), tag `social-feed` fora da convenção `global_*` (precedente election-tse/municipality-catalog), remotePattern `localhost/thumbs` incondicional (decisão deliberada dos 3 modos e2e), persist não-atômico (comentado); achados visuais do design-vision mapeados para a Issue #33 (separação visual branco-sobre-branco, fora de escopo por decisão do gate).
|
||||
|
||||
**S5** — separação visual da seção "Acompanhe de perto" da prova social na home de campanha: o `<section>` sai de `bg-white` (idêntico à faixa de números, seções coladas) para `border-y border-(--campaign-line) bg-(--campaign-band)` — banda `#ebe9e9` da paleta + hairlines de 12%, o desenho aprovado no wireframe (seção 7: zona de cor própria com `border-top/bottom: 1px solid var(--line)`) e no rascunho UI do gate (Cena 1/3 recomendadas). Zero mudança de conteúdo/dados/comportamento: cards continuam brancos e saltam na banda; fail-closed intacto (sem posts visíveis a seção some e Prova → Problema voltam contíguos — teste e2e existente segue verde); nenhum token novo; sem migration/Consent/access. Única mudança de runtime: 1 linha de className; + asserções `toHaveCSS` no e2e full-state da seção (fundo `#ebe9e9` exato — pega token quebrado em vez de só "≠ branco", hairline top `1px` com cor `rgb(0 0 0 / 12%)` exata, cards brancos) — sem screenshot diff (repo não usa regressão visual). Verificação: tsc/lint/format/unit 2318 verdes; e2e frontend: empty-state (contiguidade) e bento passaram com as asserções novas (2/2 runs que as alcançaram); o teste full-state falhou localmente no clique pós-minhas-asserções por cold-compile dev sob load ~68 — baseline com as mudanças stashed falha idêntico (falha pré-existente do ambiente, não regressão); build verde (migrations ok). knip local = limitação P3 conhecida (não carrega `payload.config.ts`); CI valida.
|
||||
|
|
@ -38,17 +44,18 @@ Conteúdo movido do `AGENTS.md` em 2026-07-30 (fatiamento do paradigma de agente
|
|||
|
||||
**Recently resolved (2026-08-18):** **OPS59** — o pre-push local não roda mais e2e: ele roda **uma vez, no CI** (PR e main — gateia merge e deploy). O espelho `scripts/gate-ci.mjs` cortou o bloco e2e da cascata (playwright install, build `.next-e2e`, `test:e2e`) e o preflight de DB passou a depender só de test/build; o readout do classificador mantém `e2e=<mode>` e imprime o que o CI rodará ("e2e runs in CI, not in this gate — OPS59"), com o check `unmapped` duplicado removido (`ci-scope.mjs` já o imprime no stderr). `package.json`, `.husky/pre-push`, `git-push.mjs` e os workflows `.forgejo/*` intocados (CI verificado, não alterado: `ci-pr.yml` e2e → `checks`; `ci.yml` e2e → `checks` → `deploy`). `tests/unit/ciSkipInvariants.unit.spec.ts` tirou `gate-ci.mjs` da lista de arquivos que devem conter `.next-e2e` (o gate local não builda mais e2e; `run-e2e-affected.mjs`/`playwright.config.ts` seguem cobertos — e2e local opcional intacto). Docs sincronizadas: `AGENTS.md` (checklist local item 3 — `test:e2e`/`test:all` saem da obrigatória; "e2e = CI, local opcional `pnpm test:e2e:affected`"), `.agents/rules/engineering-standards.mdc` e `agent-pr-workflow.mdc` (gate descrito como "espelho do ci-pr.yml sem e2e"). Verificado por grep: `AGENT-OPS.md` e skills (`work-issue`, `agent-work-issue`, `worktree-next-issue`, `local-database`) não citavam e2e no pre-push — sem mudança. Anti-goals respeitados: sem flag de "pular e2e" (bypass continua só via `--no-verify` documentado), política "Dono do PR, dono do CI" inalterada. Sem migration/access/Consent/UI. Verificação: `pnpm gate:ci` local (cascata nova full — lint/format/typecheck/knip/cycles/unit/int/build em `teqo_test`; e2e vira print), unit 2286+ verdes; o e2e desta PR roda full no CI por HIGH_RISK (`gate-ci.mjs`).
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS60** — o sync do `pnpm db:seed:posts` ganhou guard de intenção explícita para escrita no bucket (achado do /simplify da #37): com as envs `S3_*` ativas, o modo sync exige `SEED_MEDIA_CONFIRM=1` (mesmo padrão `isTruthyEnv` do `MEDIA_RECOVER_CONFIRM` da OPS52-media-guard) e recusa com exit 1 antes de qualquer escrita sem a flag — o risco fechado: um worktree com cópia de credenciais `S3_*` de prod (all-or-nothing do `worktree-env.mjs`) rodando sync contra DB local sobrescrevia covers no bucket de **prod** (o seed é idempotente por slug e sobrescreve o key determinístico). Storage local (sem `S3_*` → disk) e `--dry-run` seguem sem flag (não escrevem); echo do alvo ganhou `Bucket`/`Endpoint` quando S3 ativo (paridade com o `media:recover`). Implementação no dono: `isTruthyEnv` (já existente da #37) + `resolveS3StorageEnv` — sem twin. Runbook do OPS58 atualizado com o comando real; nota no AGENTS.md.
|
||||
**Recently resolved (2026-08-18):** **OPS61** — contratos de merge/flip do Forgejo consertados. **(S1)** Os workflows pós-merge (`issue-done-on-main-merge.yml`, `plan-issue-ready-on-main-merge.yml`) rodavam com o `GITHUB_TOKEN` nativo, que 403 em escrita de Issues — o flip `Closes #N → done+in-prod` (PRs #42/#48) quebrava em silêncio (o script engolia o 403 e o job terminava success; flip manual necessário). Agora injetam `FORGEJO_API_TOKEN` (o PAT que o pool já usa para o mesmo tipo de escrita) via `env:` no job, e o `forgejo-issue-transition.mjs` sai **exit 1** se qualquer flip falhar — o job vermelha em vez de mentir. **Fork guard** nos dois workflows (`head.repo.full_name == github.repository`, a mesma classe do `agent-pr-ready-automerge`): PR de fork mergeada faria checkout do script do fork rodando com o PAT do repo (RCE). **(S3)** A branch protection de `main` **não existia no servidor** (0 regras no `GET /branch_protections` — o `pnpm configure:branch-protection` era passo humano pendente do OPS50 e nunca rodou; as docs diziam "aplicado" e mentiam), e o valor `checks` do script **nunca casaria** os contextos reais do Forgejo (casamento por glob contra `CI (PR) / checks (pull_request)` — o sufixo ` (evento)` faz parte do contexto; literal `checks` = todo merge bloqueado). Script corrigido: contexto `CI (PR) / checks*`, idempotente (GET → POST/PATCH/no-op, verifica após aplicar, dry-run honesto) com decisão pura em `scripts/lib/branch-protection.mjs` + spec nova. **(2b, raça do waitForChecks — evidência PR #52:** mergeou com o CI vermelho porque um snapshot com statuses verdes mas jobs ainda não-agendados (sem status) parecia completo; o `docs-guards` postou failure depois): `waitForChecks` passa a exigir o rollup `CI (PR) / checks` **presente e verde** (o único contexto que só existe quando a cascata inteira do ci-pr assentou), `mergeable === false` só conta como conflito após a cascata assentar, timeouts sobem (CLI 30→45 min, workflow 40→55 min — o wait agora cobre e2e/int/build de verdade). A regra no servidor é a defesa final (o merge POST é bloqueado com 405 enquanto o contexto exigido não estiver verde — confirmado na fonte do Forgejo). **Validação ao vivo na própria entrega:** a PR desta entrega (`Closes #53`) mergeou pelo novo gate do rollup com a regra recém-aplicada no servidor, e o `issue-done` flipou a #53 para `done`+`in-prod` com o PAT. Sem migration/access/Consent/UI. Testes: `forgejoApi.unit.spec.ts` (raça do rollup, rollup failure, mergeable pré-settle — fixtures dos waitForChecks/autoMerge existentes atualizados para o contexto real), `branchProtection.unit.spec.ts` nova (create/update/noop, glob casa o contexto observado). (ops(OPS61): flip de issues pós-merge com PAT + gate do rollup checks + branch protection real no Forgejo)
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS61** — contratos de merge/flip do Forgejo consertados. **(S1)** Os workflows pós-merge (`issue-done-on-main-merge.yml`, `plan-issue-ready-on-main-merge.yml`) rodavam com o `GITHUB_TOKEN` nativo, que 403 em escrita de Issues — o flip `Closes #N → done+in-prod` (PRs #42/#48) quebrava em silêncio (o script engolia o 403 e o job terminava success; flip manual necessário). Agora injetam `FORGEJO_API_TOKEN` (o PAT que o pool já usa para o mesmo tipo de escrita) via `env:` no job, e o `forgejo-issue-transition.mjs` sai **exit 1** se qualquer flip falhar — o job vermelha em vez de mentir. **Fork guard** nos dois workflows (`head.repo.full_name == github.repository`, a mesma classe do `agent-pr-ready-automerge`): PR de fork mergeada faria checkout do script do fork rodando com o PAT do repo (RCE). **(S3)** A branch protection de `main` **não existia no servidor** (0 regras no `GET /branch_protections` — o `pnpm configure:branch-protection` era passo humano pendente do OPS50 e nunca rodou; as docs diziam "aplicado" e mentiam), e o valor `checks` do script **nunca casaria** os contextos reais do Forgejo (casamento por glob contra `CI (PR) / checks (pull_request)` — o sufixo ` (evento)` faz parte do contexto; literal `checks` = todo merge bloqueado). Script corrigido: contexto `CI (PR) / checks*`, idempotente (GET → POST/PATCH/no-op, verifica após aplicar, dry-run honesto) com decisão pura em `scripts/lib/branch-protection.mjs` + spec nova. **(2b — achado ao vivo na própria entrega, PR #67)** O gate antigo do `waitForChecks` (`pending.length === 0`) era **insatisfazível**: o Forgejo posta o status do próprio job do safety net como `pending` durante o run inteiro, então o CLI **nunca auto-mergeou nenhuma PR** — todo merge Forgejo até aqui foi manual (`merged_by` do dono), inclusive o da PR #52 com o CI vermelho (a narrativa da "raça do snapshot" da intenção estava errada: o merge vermelho foi manual, não do script). O gate novo espera o rollup `CI (PR) / checks` presente+verde (único contexto que só existe quando a cascata inteira do ci-pr assentou) e **ignora o próprio contexto** do safety net; `mergeable === false` só conta como conflito após a cascata assentar; timeouts sobem (CLI 30→45 min, workflow 40→55 min). A regra no servidor é o gate real para todo mundo: o merge POST é bloqueado com 405 enquanto o contexto exigido não estiver verde — inclusive merges manuais via API (a PR #52 não teria entrado vermelha). **Validação ao vivo na própria entrega:** a regra foi criada e verificada no servidor (re-run = no-op), e a PR #67 (`Closes #53`) mergeou pelo novo gate do rollup com a regra aplicada; o `issue-done` flipou a #53 para `done`+`in-prod` com o PAT. Sem migration/access/Consent/UI. Testes: `forgejoApi.unit.spec.ts` (rollup não-posto continua poll, rollup failure lança, próprio status do safety net não bloqueia, mergeable pré-settle — fixtures dos waitForChecks/autoMerge existentes atualizados para o contexto real), `branchProtection.unit.spec.ts` nova (create/update/noop, glob casa o contexto observado).
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS60** — o sync do `pnpm db:seed:posts` ganhou guard de intenção explícita para escrita no bucket (achado do /simplify da #37): com as envs `S3_*` ativas, o modo sync exige `SEED_MEDIA_CONFIRM=1` (mesmo padrão `isTruthyEnv` do `MEDIA_RECOVER_CONFIRM` da OPS52-media-guard) e recusa com exit 1 antes de qualquer escrita sem a flag — o risco fechado: um worktree com cópia de credenciais `S3_*` de prod (all-or-nothing do `worktree-env.mjs`) rodando sync contra DB local sobrescrevia covers no bucket de **prod** (o seed é idempotente por slug e sobrescreve o key determinístico). Storage local (sem `S3_*` → disk) e `--dry-run` seguem sem flag (não escrevem); echo do alvo ganhou `Bucket`/`Endpoint` quando S3 ativo (paridade com o `media:recover`). Implementação no dono: `isTruthyEnv` (já existente da #37) + `resolveS3StorageEnv` — sem twin. Runbook do OPS58 atualizado com o comando real; nota no AGENTS.md.
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS61** — contratos de merge/flip do Forgejo consertados. **(S1)** Os workflows pós-merge (`issue-done-on-main-merge.yml`, `plan-issue-ready-on-main-merge.yml`) rodavam com o `GITHUB_TOKEN` nativo, que 403 em escrita de Issues — o flip `Closes #N → done+in-prod` (PRs #42/#48) quebrava em silêncio (o script engolia o 403 e o job terminava success; flip manual necessário). Agora injetam `FORGEJO_API_TOKEN` (o PAT que o pool já usa para o mesmo tipo de escrita) via `env:` no job, e o `forgejo-issue-transition.mjs` sai **exit 1** se qualquer flip falhar — o job vermelha em vez de mentir. **Fork guard** nos dois workflows (`head.repo.full_name == github.repository`, a mesma classe do `agent-pr-ready-automerge`): PR de fork mergeada faria checkout do script do fork rodando com o PAT do repo (RCE). **(S3)** A branch protection de `main` **não existia no servidor** (0 regras no `GET /branch_protections` — o `pnpm configure:branch-protection` era passo humano pendente do OPS50 e nunca rodou; as docs diziam "aplicado" e mentiam), e o valor `checks` do script **nunca casaria** os contextos reais do Forgejo (casamento por glob contra `CI (PR) / checks (pull_request)` — o sufixo ` (evento)` faz parte do contexto; literal `checks` = todo merge bloqueado). Script corrigido: contexto `CI (PR) / checks*`, idempotente (GET → POST/PATCH/no-op, verifica após aplicar, dry-run honesto) com decisão pura em `scripts/lib/branch-protection.mjs` + spec nova. **(2b — achado ao vivo na própria entrega, PR #67)** O safety net tinha **dois** bloqueios independentes. (1) O gate antigo do `waitForChecks` (`pending.length === 0`) era **insatisfazível**: o Forgejo posta o status do próprio job do safety net como `pending` durante o run inteiro. (2) O merge POST faz um push do branch rebaseado para `main` e o hook pre-receive do Forgejo rejeita esse push quando o usuário do token não tem write no repo — o `GITHUB_TOKEN` nativo age como o usuário sistema do Actions (o mesmo que 403 em Issues), então o merge do CLI morria com 409 "User permission denied for writing" (confirmado na fonte 9.0.3: o hook cai no `AssertCanWriteCode` antes do caminho de merge). Resultado: o CLI **nunca auto-mergeou nenhuma PR** — todo merge Forgejo até aqui foi manual (`merged_by` do dono), inclusive o da PR #52 com o CI vermelho (a narrativa da "raça do snapshot" da intenção estava errada: o merge vermelho foi manual; e runs que "exitaram 0" eram leituras de PR já mergeada). Gate novo: espera o rollup `CI (PR) / checks` presente+verde (único contexto que só existe quando a cascata inteira do ci-pr assentou) e **ignora o próprio contexto** do safety net; `mergeable === false` só conta como conflito após a cascata assentar; timeouts sobem (CLI 30→45 min, workflow 40→55 min); e o workflow do safety net agora injeta `FORGEJO_API_TOKEN` (mesmo PAT dos pós-merge) — o merge com o PAT (admin) passa no hook. A regra no servidor é o gate real para todo mundo: o merge POST é bloqueado com 405 enquanto o contexto exigido não estiver verde — inclusive merges manuais via API (a PR #52 não teria entrado vermelha). **Validação ao vivo na própria entrega:** a regra foi criada e verificada no servidor (re-run = no-op), e a PR #67 (`Closes #53`) mergeou pelo novo gate do rollup com a regra aplicada; o `issue-done` flipou a #53 para `done`+`in-prod` com o PAT. Sem migration/access/Consent/UI. Testes: `forgejoApi.unit.spec.ts` (rollup não-posto continua poll, rollup failure lança, próprio status do safety net não bloqueia, mergeable pré-settle — fixtures dos waitForChecks/autoMerge existentes atualizados para o contexto real), `branchProtection.unit.spec.ts` nova (create/update/noop, glob casa o contexto observado).
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS62** — fail-fast estrutural do CI: `ci-pr.yml` e `ci.yml` deixaram de ter jobs irmãos. Cada workflow agora tem **um único job `checks` sequencial** (ci-pr: guards de conteúdo → lint → format → typecheck → knip → cycles → unit → int → build → e2e, com skips do `ci-scope.mjs` agora como step com outputs; ci.yml: mesma mecânica full + deploy OPS53 intacto), então **step vermelho interrompe o job, o run falha e o slot do runner é liberado imediatamente** — sem API de cancel (o Forgejo 9.0.3 não tem), sem watchdog, sem upgrade do Forgejo no homeserver (decisão X1 do gate de execução substitui o watchdog+upgrade da intenção; o aceite "API de cancel/upgrade" e "mesmos jobs, mesma cascata" foi revisado pelo humano — o que o CI _verifica_ permanece idêntico, só o envelope muda). Diagnóstico preservado: steps têm logs próprios. O job id `checks` mantém o contexto `CI (PR) / checks` que o automerger/`waitForChecks` e a branch protection esperam (OPS61). Paralelismo do e2e recuperado por `PLAYWRIGHT_WORKERS=4` num único processo (substitui os 2 shards × 2 workers; mesma carga); **2 services Postgres por nome na rede do job** (`postgres-int`/`postgres-build`, **sem publish host** — o job único seguraria portas fixas pelo run inteiro e runs concorrentes colidiriam; o Forgejo 9 não expande expressões em `services.ports`, medido ao vivo no run 730 falhando em 1s com a string literal; o DNS da rede do job mata a colisão de raiz — os guards fail-closed `LOCAL_HOSTS`/`assertTestDatabase` admitem os nomes dos services, ainda rejeitando hosts remotos) preservam a topologia de hoje (e2e nunca herda resíduo de fixtures do int); 1 checkout + 1 `pnpm install` por run (antes ~10). Plumbing morto removido: `e2eShardConfig` e o output `e2e_shards` do classifier (sem consumidor). Guards de conteúdo movidos para o início do pipeline (falham rápido e são PR-scoped). `/simplify` (3 reviewers): P1 aplicados — `set -euo pipefail` no step `scope` (crash do classifier com outputs vazios silenciaria skips → false green) e services por nome (acima); P2 aplicados — pins de invariantes ancorados em chaves YAML (comentários não satisfazem `needs: [checks]`/`matrix:`/`fail-fast:`), pin do wiring crítico `id: scope` + `if: e2e_mode == 'full'` (perdê-lo pula a suíte em silêncio), comentário morto do sharding em `playwright.config.ts` e `docs/TESTING.md` corrigidos (ainda citavam `.github/workflows` e jobs paralelos); P3 — JSDoc do `ci-scope.mjs` e redação do impl plan; o P2 do `waitForChecks` (timeout 30 min vs job 50 min) fica como débito de CI anotado no impl. Docs: tabela CI do AGENT-OPS reescrita + linha morta do `styfle/cancel-workflow-action` (removida no OPS50) apagada. Sem migration/access/Consent/UI. Testes: invariantes novos em `ciSkipInvariants.unit.spec.ts` (um único job `checks`, sem `matrix:`/`fail-fast:`/`runs-on: host` no ci-pr, `PLAYWRIGHT_WORKERS: 4`, guards antes do lint, deploy gated em `needs: [checks]`, services por nome sem `ports:`); `localHosts.unit.spec.ts` com os nomes dos services; `testAffected.unit.spec.ts` sem o describe do shard config. **Validação ao vivo na própria entrega:** o ci-pr deste PR já é o envelope novo — o primeiro run (730) pegou a expressão de porta não suportada (achado → corrigido para DNS de service), o run verde prova a suíte inteira no job único; a medição do tempo de parede fica registrada no run. Custo aceito (X1): run verde ~21 min esperados (vs ~15–18 com jobs paralelos) e e2e vermelho é o caso mais lento de veredito; débito registrado no impl plan (matrix fail-fast Y) se a fila do runner apertar. Impl: `docs/plans/ops62-ci-fail-fast-forgejo-impl.md` (a intenção fica como histórico do gate).
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS63** — os `docs-guards` (OPS44) rodam também no pre-push local: o espelho `scripts/gate-ci.mjs` ganhou os três checks na fase 1 (changelog append-only, agregado sync `--check`, marcadores de conflito em markdown) como chamadas diretas dos mesmos scripts do CI — labels espelhando os steps do job `docs-guards`; header do arquivo e linha final atualizados. `package.json`, `.husky/pre-push`, `git-push.mjs` e workflows `.forgejo/*` intocados: `gate:push` = `gate:ci` continua a cadeia única, o job `docs-guards` segue dono do escape `changelog-rewrite:` (body do PR — CI-only; restauração legítima D8 falha local com a mesma mensagem do CI e usa o bypass documentado `git push --no-verify`, com o CI como via do escape). Docs sincronizadas: `.agents/rules/engineering-standards.mdc` e `agent-pr-workflow.mdc` (gate descrito como "espelho do ci-pr.yml sem e2e, com docs-guards locais"), `docs/AGENT-OPS.md` (contrato item 4 — OPS44: checks no pre-push + nota do escape CI-only). Verificado por grep: `AGENTS.md` e skills não descreviam o gate sem os checks de docs — sem mudança. Anti-goals respeitados: sem bypass novo (falha local honesta), sem `plans-only-closes` local (contrato de PR body). Sem migration/access/Consent/UI/schema. Verificação: três checks green na branch; caminho de falha validado (commit descartável removendo linha do agregado → append-only falha com mensagem acionável); `pnpm gate:ci` local full; CI roda full nesta PR por HIGH_RISK (`gate-ci.mjs`).
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS65** — CI do `main` em **janela fixa de 30 min** + **agent-pool morto**. O `ci.yml` não dispara mais a cada push: roda por `schedule */30` + `workflow_dispatch`, e um gate barato (`gate`, runs-on `host`, main-only, sem pnpm — `scripts/ci-classify-production.mjs` + matcher puro `scripts/lib/dockerignore.mjs`) lê a **revision do container rodando** no homeserver (label `org.opencontainers.image.revision` — o compose pode mentir após rollback falho), diffa contra o HEAD de `main` e classifica "mudança de produção" usando o `.dockerignore` como fonte da verdade (o que não entra no build context não justifica build novo; `docs/`/`.agents`/`.env*` viram skip; `scripts/`/`tests`/`.forgejo`/`AGENTS.md` contam como produção — conservador, qualquer dúvida roda a suite). Deployed == HEAD → suite e deploy skipped, run verde (o rollup `checks` já aceita skipped); qualquer outra coisa → suite full + deploy na mesma janela; dispatch sempre roda tudo; o `deploy-homeserver.sh` ganhou guard de idempotência "already deployed" (revision do container já no SHA → skip verde). Fail-open: revision desconhecida → suite roda (main sempre verificada); gate incapaz de classificar → suite roda e o run fica **vermelho** (nunca blackout silencioso); deploy duplo-gated (`needs: [checks, gate]` + `if` explícito — nunca deploy às cegas nem com suite vermelha). `agent-pool.yml` removido (o tick `*/10` custava 144 `pnpm install`/dia na workstation; scripts/skills do pool ficam dormentes). Testes: `dockerignoreMatch` + `ciClassifyProduction` unit novos (matcher contra o `.dockerignore` real, fail-open, dispatch, caminho git com repo scratch, exit codes), pins do `ciSkipInvariants` (janela 30, sem `push`, ref guard, ifs fail-open) e do `deployScript` (guard), `HIGH_RISK_EXACT` += classificador. Docs: runbook `docs/ops/teqo-1313-deploy.md` (janela/gate/"already deployed"/falhas), `AGENTS.md`, `docs/AGENT-OPS.md`.
|
||||
|
||||
**Recently resolved (2026-08-18):** **OPS64** — o safety net `ready-automerge` deixa de se auto-bloquear e o gate do merge fica estruturalmente honesto. O sintoma primário da Issue (deadlock: o `waitForChecks` contava o próprio status `pending` do job → timeout 30 min → merge nunca acontecia) **já tinha sido entregue pelo OPS61** (filtro do próprio contexto + gate do rollup + PAT; provado vivo: runs 710/712 mergearam os PRs #67/#70). O secundário — o rollup `checks` reportava SUCCESS com um shard de e2e vermelho porque o Forgejo 9.0.3 reporta o resultado do **último** shard como o resultado do parent de matrix no contexto `needs` (runs 604/607/610: e2e (1) vermelho + e2e (2) verde → `checks` verde; o `needs.<job>.results` do GitHub não existe neste runner) — **foi eliminado estruturalmente pelo OPS62** (mergeado em main durante a execução deste item): o ci-pr.yml e o ci.yml viraram **jobs únicos sequenciais** (sem matrix, sem shards), então o status do job `checks` já é o veredito honesto da cascata inteira. Este item entregou o que restava de valor: (a) **teste-pino no `waitForChecks`** (`forgejoApi.unit.spec.ts`, cenário run 607) — o CLI **nunca confia no rollup sozinho**: varre os statuses individuais e lança "Checks falharam" com rollup verde + shard vermelho (invariante de defesa que continua válido e pegaria qualquer matrix que volte); (b) **docs honestas** (`agent-pr-workflow.mdc`, `AGENT-OPS.md`) registrando o veredito do rollup, o pin do CLI e a eliminação estrutural do bug pelo OPS62. O script `ci-rollup-check.mjs` e os edits de workflow planejados foram **descartados na execução** (redundantes pós-OPS62 — decisão do gate com o humano; os workflows em main são os do OPS62, intocados). Sem migration/access/Consent/UI/schema. Verificação: unit 2360 verdes; lint/format/typecheck/knip/cycles no gate local; a própria PR prova o ciclo (o `ready-automerge` mergea no fim). Impl plan: `docs/plans/ops64-forgejo-pr-automerge-waitforchecks-impl.md`.
|
||||
|
||||
**Recently resolved (2026-08-17):** **OPS51** — o banco de produção saiu do Neon para o Postgres do homeserver (`teqo_1313`, container `teqo-1313`), sem mudança de config: o `~/stack/teqo-1313.env` já apontava para o banco preparado (criado 16/08 com role própria + cadeia completa de 56 migrations + zero conteúdo — verificado), então restaurar = a produção "apareceu" no container. **Divergência deliberada da intenção (questão A/B validada como B):** rejeitado criar `teqo_prod` novo — o argumento "o banco do 1313 tem vida própria" não se sustenta (o site 1313 É a produção deste repo) e o OPS53 já trata `teqo_1313` como produção. Execução 100% no homeserver (PII nunca tocou a workstation): URL do Neon puxada do Vercel (`vercel env pull`, projeto `jorgesolla`, `DATABASE_URL_UNPOOLED` → `NEON_DATABASE_URL` em `~/stack/.env` chmod 600), `pg_dump -Fc` (Neon PG 17.10) → `/srv/hdd/backups/teqo-neon-pre-migracao/teqo-neon-full-20260817-204800.dump` (5,8 MB, sha256 `f12196f2…`), `pg_restore --no-owner --no-privileges` como a role `teqo_1313` (drop schema + grant, padrão do `db-pull`), verificado: contagens por tabela idênticas ao Neon (1919 contatos, 39 posts, 1487 assinaturas, 1484 subscrições, 35 campaign_users, 392 lideranças, 2 pledges, 435 municípios, 6 atividades; supporter segue 0 — blocker LGPD ainda de pé), sequences no topo (`last_value == max(id)`), objetos com dono `teqo_1313`, `payload migrate` no-op (56 = 56, serviço de maintenance `teqo-1313-migrate`), 3 credenciais WebAuthn + 34 sessions + 5 chaves Consent restauradas (RP ID não mudou — biometria segue valendo). Smoke sem deploy: `/`, artigo com conteúdo restaurado, `/campanha/login`, `/admin`, `POST /api/revalidate` (`posts` + `global_privacy-policy`), WebAuthn `login-options`, barreira 307 sem sessão — verdes; smoke de browser (login, biometria, convites) validado manualmente. **Rollback documentado:** Neon nunca foi escrito (só lido); voltar = re-apontar `DATABASE_URL` do `teqo-1313.env` para o Neon + `compose up -d`. **Débito registrado (→ OPS52):** as 40 rows de `media` têm URLs relativas (`/api/media/file/…`) sem arquivos em lugar nenhum — capas dão 500 no homeserver e **404 no próprio Vercel/produção atual** (estado pré-existente; migração manteve paridade). Repo: plano da intenção concluído, `AGENTS.md` e help de `db:pull`/`check-push-chain` sem a referência ao Neon; infra-solla `STATE.md` atualizado à parte.
|
||||
|
||||
**Recently resolved (2026-08-17):** **OPS53** — o deploy do site 1313 virou etapa do CI: mergir em `main` com a suite verde == site atualizado em `jorgesolla1313.com.br`, sem passo manual. O job `deploy` em `.forgejo/workflows/ci.yml` roda no host do runner (workstation, `runs-on: host`) e streama `scripts/deploy-homeserver.sh` para o homeserver via SSH (`ssh homeserver "bash -s -- <sha>"`); o script remoto (bash puro, homeserver sem dependências novas) faz: guard de HEAD (`git ls-remote` de `main` == SHA do job, senão skip "stale"), `flock` de serialização, workspace `~/teqo-deploy` (clone do Forgejo local), `docker login localhost:5000` (REGISTRY_USER/PASSWORD de `~/stack/.env`), build dos stages `runner`+`migrator` no homeserver (`--network stack_default` para a geração estática alcançar o `postgres:5432` do compose; secrets de `~/stack/teqo-1313.env` via BuildKit, sem camadas/logs), push no registry local, swap dos tags de imagem no compose (com backup `docker-compose.yml.pre-<sha>`), **migrate pelo serviço de maintenance `teqo-1313-migrate` antes do rollout**, `docker compose up -d`, espera do healthcheck e smoke (`/`, `/campanha/login`, `/admin`, barreira 307, WebAuthn `login-options` com body JSON, `POST /api/revalidate` com o secret real — rehearsal validado contra o site vivo). Falha pós-swap → rollback automático best-effort (restore do backup + `up -d` da imagem anterior) + job vermelho. **Divergência deliberada da intenção (fato novo):** a intenção assumia o runner no homeserver; verificado (`infra-solla/STATE.md` + ao vivo) que o runner é a `workstation-runner` na workstation e o stack de produção vive no homeserver — a abordagem A foi corrigida para "job `runs-on: host` na workstation + todo o deploy no homeserver via SSH", o que manteve **zero secrets novos no Forgejo** e zero mudança de infra no compose. Nenhum secret no repo; envs seguem chmod-600 no homeserver. Runbook (rollback manual, falhas conhecidas, decisão de segurança do host label): `docs/ops/teqo-1313-deploy.md` (novo). Guarda estrutural nova: `tests/unit/deployScript.unit.spec.ts` (bash -n + invariantes do pipeline: HEAD guard, BuildKit secrets, ordem migrate→rollout, smoke). AGENTS.md/AGENT-OPS.md atualizados. Primeiro deploy real = o merge deste próprio item (tracer bullet); infra-solla `STATE.md` anotado à parte.
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ Three layers, all local-database-only (see `local-database` skill; tests refuse
|
|||
- **Integration** (`tests/int/**/*.int.spec.ts`, 71 specs): real Payload + Postgres (`teqo_test`); campaign fixtures allocate seeded municipalities via a Postgres sequence so parallel spec files never share one, and purge residue on claim. Since the miss #73 guardrail (Pass 4), specs that mutate municipalities must use the allocator (no pinned slugs) — enforced by `testMunicipalityAllocatorConventions`. Shared consent rows with stable keys are leased (`tests/helpers/testDatabaseLease.ts`), never owned.
|
||||
- **E2E** (`tests/e2e`, Playwright, 17 specs / 51 cases (Pass 5, 2026-08-03; was 48 at Pass 4)): smoke-level; most campaign behavior is pinned at the int layer.
|
||||
|
||||
CI (`.github/workflows/ci-pr.yml`) runs parallel jobs — lint (zero warnings), format, typecheck, knip, cycles, unit/int (**affected by the PR diff**: `vitest --changed` against the PR base via `scripts/test-affected.mjs`, full-suite fallback on high-risk paths), e2e (manifest path→spec via `scripts/e2e-affected.mjs` + `scripts/lib/e2e-affected-manifest.mjs`, blocking; production build + `list`/`github` reporters in CI) and build — against a Postgres 17 service with **`db:seed:minimal`**. Push to `main` (`ci.yml`) always runs the full net including e2e.
|
||||
CI (`ci-pr.yml`) is a **single sequential job `checks`** (OPS62 X1): guards → lint (zero warnings) → format → typecheck → knip → cycles → unit/int (**affected by the PR diff**: `vitest --changed` against the PR base via `scripts/test-affected.mjs`, full-suite fallback on high-risk paths) → build → e2e (manifest path→spec via `scripts/e2e-affected.mjs` + `scripts/lib/e2e-affected-manifest.mjs`, blocking; production build + `list`/`github` reporters in CI) — against two isolated Postgres 17 services (int / build+e2e) with **`db:seed:minimal`**. Fail-fast is structural: a failed step stops the run; e2e runs with `PLAYWRIGHT_WORKERS=4`. Push to `main` (`ci.yml`) always runs the full net including e2e.
|
||||
|
||||
**Local e2e before push (same blast radius as PR CI):** `pnpm test:e2e:affected` — runs `e2e-affected.mjs` against `origin/stage`, migrates/seeds, then `pnpm test:e2e` with the selected specs (or the full suite on high-risk diffs). Forward extra Playwright args after `--` for a narrowed repro. Opt into production mode (after fixing the known municipalities-list prod client bug) with `E2E_PROD=1 pnpm test:e2e:affected`.
|
||||
|
||||
|
|
|
|||
1
docs/changelog/2026-08-18-ops62.md
Normal file
1
docs/changelog/2026-08-18-ops62.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**Recently resolved (2026-08-18):** **OPS62** — fail-fast estrutural do CI: `ci-pr.yml` e `ci.yml` deixaram de ter jobs irmãos. Cada workflow agora tem **um único job `checks` sequencial** (ci-pr: guards de conteúdo → lint → format → typecheck → knip → cycles → unit → int → build → e2e, com skips do `ci-scope.mjs` agora como step com outputs; ci.yml: mesma mecânica full + deploy OPS53 intacto), então **step vermelho interrompe o job, o run falha e o slot do runner é liberado imediatamente** — sem API de cancel (o Forgejo 9.0.3 não tem), sem watchdog, sem upgrade do Forgejo no homeserver (decisão X1 do gate de execução substitui o watchdog+upgrade da intenção; o aceite "API de cancel/upgrade" e "mesmos jobs, mesma cascata" foi revisado pelo humano — o que o CI _verifica_ permanece idêntico, só o envelope muda). Diagnóstico preservado: steps têm logs próprios. O job id `checks` mantém o contexto `CI (PR) / checks` que o automerger/`waitForChecks` e a branch protection esperam (OPS61). Paralelismo do e2e recuperado por `PLAYWRIGHT_WORKERS=4` num único processo (substitui os 2 shards × 2 workers; mesma carga); **2 services Postgres por nome na rede do job** (`postgres-int`/`postgres-build`, **sem publish host** — o job único seguraria portas fixas pelo run inteiro e runs concorrentes colidiriam; o Forgejo 9 não expande expressões em `services.ports`, medido ao vivo no run 730 falhando em 1s com a string literal; o DNS da rede do job mata a colisão de raiz — os guards fail-closed `LOCAL_HOSTS`/`assertTestDatabase` admitem os nomes dos services, ainda rejeitando hosts remotos) preservam a topologia de hoje (e2e nunca herda resíduo de fixtures do int); 1 checkout + 1 `pnpm install` por run (antes ~10). Plumbing morto removido: `e2eShardConfig` e o output `e2e_shards` do classifier (sem consumidor). Guards de conteúdo movidos para o início do pipeline (falham rápido e são PR-scoped). `/simplify` (3 reviewers): P1 aplicados — `set -euo pipefail` no step `scope` (crash do classifier com outputs vazios silenciaria skips → false green) e services por nome (acima); P2 aplicados — pins de invariantes ancorados em chaves YAML (comentários não satisfazem `needs: [checks]`/`matrix:`/`fail-fast:`), pin do wiring crítico `id: scope` + `if: e2e_mode == 'full'` (perdê-lo pula a suíte em silêncio), comentário morto do sharding em `playwright.config.ts` e `docs/TESTING.md` corrigidos (ainda citavam `.github/workflows` e jobs paralelos); P3 — JSDoc do `ci-scope.mjs` e redação do impl plan; o P2 do `waitForChecks` (timeout 30 min vs job 50 min) fica como débito de CI anotado no impl. Docs: tabela CI do AGENT-OPS reescrita + linha morta do `styfle/cancel-workflow-action` (removida no OPS50) apagada. Sem migration/access/Consent/UI. Testes: invariantes novos em `ciSkipInvariants.unit.spec.ts` (um único job `checks`, sem `matrix:`/`fail-fast:`/`runs-on: host` no ci-pr, `PLAYWRIGHT_WORKERS: 4`, guards antes do lint, deploy gated em `needs: [checks]`, services por nome sem `ports:`); `localHosts.unit.spec.ts` com os nomes dos services; `testAffected.unit.spec.ts` sem o describe do shard config. **Validação ao vivo na própria entrega:** o ci-pr deste PR já é o envelope novo — o primeiro run (730) pegou a expressão de porta não suportada (achado → corrigido para DNS de service), o run verde prova a suíte inteira no job único; a medição do tempo de parede fica registrada no run. Custo aceito (X1): run verde ~21 min esperados (vs ~15–18 com jobs paralelos) e e2e vermelho é o caso mais lento de veredito; débito registrado no impl plan (matrix fail-fast Y) se a fila do runner apertar. Impl: `docs/plans/ops62-ci-fail-fast-forgejo-impl.md` (a intenção fica como histórico do gate).
|
||||
1
docs/changelog/2026-08-18-ops64.md
Normal file
1
docs/changelog/2026-08-18-ops64.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**Recently resolved (2026-08-18):** **OPS64** — o safety net `ready-automerge` deixa de se auto-bloquear e o gate do merge fica estruturalmente honesto. O sintoma primário da Issue (deadlock: o `waitForChecks` contava o próprio status `pending` do job → timeout 30 min → merge nunca acontecia) **já tinha sido entregue pelo OPS61** (filtro do próprio contexto + gate do rollup + PAT; provado vivo: runs 710/712 mergearam os PRs #67/#70). O secundário — o rollup `checks` reportava SUCCESS com um shard de e2e vermelho porque o Forgejo 9.0.3 reporta o resultado do **último** shard como o resultado do parent de matrix no contexto `needs` (runs 604/607/610: e2e (1) vermelho + e2e (2) verde → `checks` verde; o `needs.<job>.results` do GitHub não existe neste runner) — **foi eliminado estruturalmente pelo OPS62** (mergeado em main durante a execução deste item): o ci-pr.yml e o ci.yml viraram **jobs únicos sequenciais** (sem matrix, sem shards), então o status do job `checks` já é o veredito honesto da cascata inteira. Este item entregou o que restava de valor: (a) **teste-pino no `waitForChecks`** (`forgejoApi.unit.spec.ts`, cenário run 607) — o CLI **nunca confia no rollup sozinho**: varre os statuses individuais e lança "Checks falharam" com rollup verde + shard vermelho (invariante de defesa que continua válido e pegaria qualquer matrix que volte); (b) **docs honestas** (`agent-pr-workflow.mdc`, `AGENT-OPS.md`) registrando o veredito do rollup, o pin do CLI e a eliminação estrutural do bug pelo OPS62. O script `ci-rollup-check.mjs` e os edits de workflow planejados foram **descartados na execução** (redundantes pós-OPS62 — decisão do gate com o humano; os workflows em main são os do OPS62, intocados). Sem migration/access/Consent/UI/schema. Verificação: unit 2360 verdes; lint/format/typecheck/knip/cycles no gate local; a própria PR prova o ciclo (o `ready-automerge` mergea no fim). Impl plan: `docs/plans/ops64-forgejo-pr-automerge-waitforchecks-impl.md`.
|
||||
1
docs/changelog/2026-08-18-ops65.md
Normal file
1
docs/changelog/2026-08-18-ops65.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**Recently resolved (2026-08-18):** **OPS65** — CI do `main` em **janela fixa de 30 min** + **agent-pool morto**. O `ci.yml` não dispara mais a cada push: roda por `schedule */30` + `workflow_dispatch`, e um gate barato (`gate`, runs-on `host`, main-only, sem pnpm — `scripts/ci-classify-production.mjs` + matcher puro `scripts/lib/dockerignore.mjs`) lê a **revision do container rodando** no homeserver (label `org.opencontainers.image.revision` — o compose pode mentir após rollback falho), diffa contra o HEAD de `main` e classifica "mudança de produção" usando o `.dockerignore` como fonte da verdade (o que não entra no build context não justifica build novo; `docs/`/`.agents`/`.env*` viram skip; `scripts/`/`tests`/`.forgejo`/`AGENTS.md` contam como produção — conservador, qualquer dúvida roda a suite). Deployed == HEAD → suite e deploy skipped, run verde (o rollup `checks` já aceita skipped); qualquer outra coisa → suite full + deploy na mesma janela; dispatch sempre roda tudo; o `deploy-homeserver.sh` ganhou guard de idempotência "already deployed" (revision do container já no SHA → skip verde). Fail-open: revision desconhecida → suite roda (main sempre verificada); gate incapaz de classificar → suite roda e o run fica **vermelho** (nunca blackout silencioso); deploy duplo-gated (`needs: [checks, gate]` + `if` explícito — nunca deploy às cegas nem com suite vermelha). `agent-pool.yml` removido (o tick `*/10` custava 144 `pnpm install`/dia na workstation; scripts/skills do pool ficam dormentes). Testes: `dockerignoreMatch` + `ciClassifyProduction` unit novos (matcher contra o `.dockerignore` real, fail-open, dispatch, caminho git com repo scratch, exit codes), pins do `ciSkipInvariants` (janela 30, sem `push`, ref guard, ifs fail-open) e do `deployScript` (guard), `HIGH_RISK_EXACT` += classificador. Docs: runbook `docs/ops/teqo-1313-deploy.md` (janela/gate/"already deployed"/falhas), `AGENTS.md`, `docs/AGENT-OPS.md`.
|
||||
1
docs/changelog/2026-08-18-s3.md
Normal file
1
docs/changelog/2026-08-18-s3.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S3** — seção "Acompanhe de perto" da home de campanha (jorgesolla1313.com.br) passa a incluir os posts do Instagram oficial, completando o board do plano-site §4.2 (artigos S1 + YouTube S2 + Instagram). Fonte automática servidor-side: loader irmão `src/utilities/socialFeed/instagramFeed.ts` (os feeds externos ganharam o subfolder `socialFeed/` — o pin da S2 predizia exatamente isso quando a segunda plataforma entrasse; `git mv` do youtubeFeed + imports atualizados): Graph API (`GET /{ig-user-id}/media` com `children{media_url,thumbnail_url}` p/ carrossel + `GET /{ig-user-id}?fields=username`), `unstable_cache` tag `social-feed` + `revalidate: 300`, snapshot cru (`{ username, posts }`, pré-exclusão) persistido via SQL direto (padrão anti-`revalidateTag`-no-cache da S2), exclusões aplicadas na leitura, **refresh de token automático** (refresh-on-failure + retry 1x, token renovado persistido por SQL direto; nota honesta no admin: o refresh endpoint só renova tokens de Instagram Login — page tokens business caem no fail-closed + rotação manual). Global `SocialFeedSettings` ganha `instagramEnabled/AccessToken/UserId/MaxItems` + `instagramFeedSnapshot` (hidden) — `excludedItems` já cobria `platform: 'instagram'` desde a S2, sem migration no mecanismo; migration `20260818_192948_add_instagram_social_feed_fields` não destrutiva (DDL revisado, sem o drift do `migrate:create` da S2). **Picker de exclusão no admin** (requisito nº 1 da intenção — posts de grade): primeiro componente custom do repo (`src/components/admin/InstagramPostExclusionPicker.tsx`, campo `ui` na global, path string + importmap regenerado — o import direto de `@payloadcms/ui` na config quebra o `generate:importmap` no tsx por causa do `.css` do react-image-crop; com path string o scanner resolve sem carregar o módulo); lista os posts do snapshot (thumbnail + legenda + data + ID) com toggle "Não exibir"/"Reexibir" + motivo opcional que escreve em `excludedItems` via `useField`. UI: `CampaignContentCardData.coverAspect` (`'video'` default — S1/S2 intactos; `'square'` 1:1 do rascunho aprovado para IG), badge "Instagram", título = legenda (fallback "Publicação no Instagram" para post sem legenda — entra no automático para exclusão manual), meta = data relativa, clique no `permalink` (nova aba, `noopener`), link do header "Seguir no Instagram →" (copy do rascunho aprovado; username derivado da API — com API fora e sem snapshot o link some junto com os cards, divergência documentada do "YouTube →" que sobrevive por ter o channelId configurado). next.config ganha `https://*.cdninstagram.com/**`. Testes: 16 units novas (parsers com caption null/carrossel/item sem permalink, thumbnail por media_type, eligibility, fetch + refresh-retry com `fetchImpl`); e2e: stub irmão `tests/e2e/instagram-stub.mjs` (porta dev+2000; a derivação da porta virou `tests/helpers/socialStub.ts` — rename do youtubeStub.ts mantendo UMA spelling), 3 testes novos no describe serial (full-state com exclusão + fallback de legenda + aspect 1:1 + link do perfil + carrossel, fail-closed sem snapshot, snapshot persistente com maxItems mudando na API down) + kill switch estendido com IG configurado + smoke do picker no admin (seed do snapshot via REST, toggle, Salvar, verificação do `excludedItems`). Verificação: unit 2351 + int 791 verdes; gate:fast/lint/format/tsc/knip (exit 0 — o erro de load do payload.config segue o ledger P3)/cycles/build verdes; e2e local: describe serial 9/9 + smoke admin 1/1 (rodando os projetos em sequência — em paralelo com `--no-deps` o `seedTestUser` dos dois beforeAll colide no mesmo usuário e quebra o run, artefato da invocação local, não do produto; o CI roda na cadeia de dependências). Detalhe do debug: o clique via CDP do MCP de browser não dispara eventos de input (ambiente do MCP, não do app — `el.click()` e o runner real funcionam).
|
||||
1
docs/changelog/2026-08-18-s6-followup.md
Normal file
1
docs/changelog/2026-08-18-s6-followup.md
Normal file
|
|
@ -0,0 +1 @@
|
|||
**S6-FOLLOWUP** — CLI Playwright 1.58.2 e filtros e2e locais: `pnpm test:e2e:affected` rodava a suíte completa silenciosamente em runs selecionados. Causa raiz (medida com o binário do repo, config real): o commander parseia posicionais e `-g`/`--list` funcionam — quem arrastava a suíte era o closure de dependências dos projects no dev mode (`setup ← campaign ← frontend ← admin` em `playwright.config.ts`): `collectProjectsAndTestFiles` filtra os arquivos por project, mas `buildProjectsClosure` repõe todos os arquivos de cada project-dependência — filtrar um spec do `frontend` puxava `campaign` (160) + `setup` (2), 177 no total com o próprio arquivo (15); `admin` puxava a suíte inteira. Em prod mode (`CI=1`) os projects não têm deps e o filtro sempre funcionou (por isso o CI selecionado estava correto). Fix: `run-e2e-affected.mjs` agora gera `test:e2e <passthrough verbatim> --no-deps -- <paths>` via helpers puros novos em `scripts/lib/playwright-e2e-args.mjs` (unit-testados, `tests/unit/playwrightE2eArgs.unit.spec.ts`) — `--no-deps` desliga o closure em runs filtrados (suíte completa mantém a cadeia OPS34 de prewarm); de quebra, o passthrough do script foi corrigido (`pnpm test:e2e:affected -- tests/x.spec.ts` descartava o path — pnpm consome o `--` e o argv nunca o continha; agora `parsePassthroughArgs` só remove um `--` líder e repassa o resto verbatim, preservando `-g grade`). Hardening: `scripts/run-e2e-affected.mjs` entrou em `HIGH_RISK_EXACT` (era o espelho local do job e2e sem gate — um PR só de runner não rodaria e2e). Docs: receitas de filtro no `playwright.config.ts` (posicional exige `--no-deps`; `--project=<família> --no-deps`; `-g`/`--list` funcionam), header do script e nota no AGENTS.md. Sem mudança de specs, CI (`--shard`) ou `gate:ci`. Verificação: unit 2343+ verdes; contagem por `--list` do binário com a forma final (18); CI do PR roda o e2e completo (o diff toca `playwright.config.ts` e `run-e2e-affected.mjs`, high-risk). Débito absorvido: hang do `pnpm test:e2e` via pnpm neste worktree (pré-existente, ambiente — binário direto funciona; não escopo). Impl plan: `docs/plans/s6-followup-playwright-filtros-cli-ignorados-impl.md`.
|
||||
|
|
@ -1,27 +1,53 @@
|
|||
# Runbook: deploy do site 1313 no homeserver (OPS53)
|
||||
# Runbook: deploy do site 1313 no homeserver (OPS53, janela OPS65)
|
||||
|
||||
O deploy de produção é uma etapa do CI (`ci.yml` no Forgejo): mergir em `main`
|
||||
com a suite verde publica o site em `jorgesolla1313.com.br` — sem passo manual.
|
||||
Merge **com mudança de produção** = site atualizado em ~30 min (janela) + tempo
|
||||
da suite/deploy (~15–25 min cada; tipicamente < 1 h no total).
|
||||
|
||||
## Gatilho e fluxo
|
||||
|
||||
1. `git push` para `main` (via PR merge) — ou `workflow_dispatch` no `ci.yml`
|
||||
para re-deployar a HEAD de `main` manualmente.
|
||||
2. Suite completa verde (static/int/build/e2e/checks).
|
||||
3. Job `deploy` (runs-on `host`, na **workstation**) roda
|
||||
1. `git push` para `main` (via PR merge) — o `ci.yml` **não dispara mais a cada
|
||||
push**: roda por **janela fixa de 30 min** (`schedule */30`) ou via
|
||||
`workflow_dispatch` (deploy manual, imediato, sempre full suite).
|
||||
2. Job `gate` (barato, host, sem pnpm): lê a **revision do container rodando**
|
||||
no homeserver (`docker inspect` → label `org.opencontainers.image.revision`
|
||||
do `teqo-1313` — a fonte de verdade; o compose pode mentir após rollback
|
||||
falho, pois é trocado antes do rollout) e classifica "mudança de produção"
|
||||
com o `.dockerignore` como fonte da verdade (o que não entra na imagem não
|
||||
justifica build novo; `docs/`, `.agents/`, `.env*` viram skip;
|
||||
`scripts/`, `tests/`, `.forgejo/`, `AGENTS.md` contam como produção —
|
||||
conservador, qualquer dúvida roda a suite).
|
||||
- Deployed == HEAD → suite e deploy **skipped**; run verde.
|
||||
- Sem revision conhecida (label ausente, container sem label) → fail-open:
|
||||
suite + deploy rodam na janela (run verde; comportamento conservador).
|
||||
- Gate incapaz de classificar (erro de git/`.dockerignore`) → suite roda e
|
||||
o run fica **vermelho** — nunca blackout silencioso.
|
||||
3. Com mudança de produção: suite completa verde (static/int/build/e2e/checks).
|
||||
4. Job `deploy` (runs-on `host`, na **workstation**) roda
|
||||
`ssh homeserver "bash -s -- <sha>" < scripts/deploy-homeserver.sh`.
|
||||
4. O script, no **homeserver**: guarda de HEAD (`main` remoto == SHA do job,
|
||||
senão skip) → `flock` (serializa) → build da imagem standalone + migrator
|
||||
(BuildKit, secrets do `~/stack/teqo-1313.env`, `--network host` com proxy
|
||||
socat `teqo-1313-build-proxy` na `stack_default` para o build alcançar o
|
||||
`postgres` — o proxy é criado idempotentemente pelo script) →
|
||||
push em `localhost:5000` → swap dos tags de imagem no
|
||||
`~/stack/docker-compose.yml` (backup antes) → **migrations**
|
||||
O script é **idempotente**: se o container rodando já tem a revision do SHA
|
||||
(ex.: dispatch duplicado), sai verde "already deployed" sem rebuild.
|
||||
5. O script, no **homeserver**: guarda de HEAD (`main` remoto == SHA do job,
|
||||
senão skip) → `flock` (serializa) → guard "already deployed" (revision do
|
||||
container) → build da imagem standalone + migrator (BuildKit, secrets do
|
||||
`~/stack/teqo-1313.env`, `--network host` com proxy socat
|
||||
`teqo-1313-build-proxy` na `stack_default` para o build alcançar o
|
||||
`postgres` — o proxy é criado idempotentemente pelo script) → push em
|
||||
`localhost:5000` → swap dos tags de imagem no `~/stack/docker-compose.yml`
|
||||
(backup antes) → **migrations**
|
||||
(`docker compose --profile maintenance run --rm teqo-1313-migrate </dev/null`) →
|
||||
`docker compose up -d teqo-1313` → healthcheck → smoke (`/`,
|
||||
`/campanha/login`, `/admin`, barreira 307, WebAuthn login-options,
|
||||
`api/revalidate` com o secret real).
|
||||
5. Falha = job vermelho no commit; nada é publicado pela metade.
|
||||
6. Falha = job vermelho no commit; nada é publicado pela metade.
|
||||
|
||||
**Primeira janela (verificação ao vivo):** após o merge do OPS65, acompanhe um
|
||||
run agendado — confira no log do job `gate` o `deployed_sha` lido do container e
|
||||
o veredito da classificação, e que um dispatch manual roda suite + deploy
|
||||
(idempotência: segundo dispatch no mesmo SHA sai "already deployed"). Isso
|
||||
prova ao vivo a paridade Forgejo de `needs.<gate>.outputs` com gate falho
|
||||
(suite roda; deploy pula; run vermelho).
|
||||
|
||||
## Onde roda cada coisa
|
||||
|
||||
|
|
@ -61,21 +87,27 @@ roda após build+push ok; rollout só após migrate ok).
|
|||
|
||||
## Falhas conhecidas
|
||||
|
||||
| Sintoma | Causa | Tratamento |
|
||||
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Job verde sem deploy ("stale run") | Push mais novo venceu; o deploy antigo saiu da fila | Nada a fazer — o run do SHA novo deploya |
|
||||
| Todo job docker quebra com `exec: "node": executable file not found in $PATH` | `runner.envs.PATH` do `~/.forgejo-runner/config.yaml` (workstation) com paths só de host (nvm/bun) — o container perde o node do toolcache (`/opt/acttoolcache`); edição do config exige o toolcache primeiro (ver comentário no próprio config) | Corrigir o PATH no config (toolcache primeiro — ver comentário no próprio arquivo) + `systemctl --user restart forgejo-runner` (incidente 2026-08-17) |
|
||||
| Deploy para logo após o migrate ("Done." e nada mais, EXIT=0) | `docker compose run` anexa stdin por padrão — o container consome o resto do script que vai no pipe do `bash -s`; o bash chega a EOF e termina sem rodar o rollout | O script já usa `< /dev/null` no `run --rm` do migrate (não remover); sintoma visto 2026-08-17 no primeiro deploy |
|
||||
| Build falha: `network mode "stack_default" not supported by buildkit` | BuildKit (drivers docker e docker-container) recusa rede bridge custom no `--network` | O script builda com `--network host` + proxy socat `teqo-1313-build-proxy` (na `stack_default`, publicado em 127.0.0.1:5433, criado idempotentemente com `restart: unless-stopped`) + `DATABASE_URL` reescrita para o loopback |
|
||||
| Build OOM no homeserver | Laptop 8c/16GB com o stack ativo (~12GB livres medidos) | Re-dispatch; se recorrente, item futuro: build na workstation com túnel |
|
||||
| `checkout@v5` falha no job `host` | Label host do act_runner | Fallback: baixar o script direto do Forgejo (`curl -s https://git.solla.dev/fsolla/teqo/raw/branch/main/scripts/deploy-homeserver.sh`) |
|
||||
| Migrate falha | Drift/erro de schema | Job vermelho; site segue no container antigo; corrigir e re-mergear |
|
||||
| Smoke falha pós-up | Regressão de runtime | Rollback automático (restore + `up -d`) + job vermelho; investigar |
|
||||
| Sintoma | Causa | Tratamento |
|
||||
| ----------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Job verde sem deploy ("stale run") | Push mais novo venceu; o deploy antigo saiu da fila | Nada a fazer — o run do SHA novo deploya |
|
||||
| Job verde sem deploy ("already deployed") | O container rodando já tem a revision do SHA do job (ex.: `workflow_dispatch` duplicado da mesma HEAD) | Nada a fazer — o site já roda esse SHA. Forçar rebuild da MESMA HEAD não é suportado via dispatch: edite o tag da imagem no compose (`image: teqo-1313:<sha>-rebuild`) e `docker compose up -d`, ou espere um commit novo |
|
||||
| Gate `gate` vermelho (erro de git/`.dockerignore`) | SHA deployado ilegível para o git (ex.: história reescrita) ou `.dockerignore` corrompido no checkout | Fail-open: suite roda; deploy pula (nunca deploy às cegas). Corrigir a causa e esperar a próxima janela (auto-cura). Se `ssh homeserver` estiver fora, o gate lê revision vazia e roda tudo (verde) — checar tailnet se a suite roda sem deploy recorrente |
|
||||
| Sem revision no container (label ausente no compose) | O compose do homeserver não define `org.opencontainers.image.revision` (deploy pré-OPS53 ou edição manual) | Degradação conservadora: toda janela roda suite + rebuild (verde). Corrigir adicionando o label ao serviço `teqo-1313` no compose e re-deployando |
|
||||
| Todo job docker quebra com `exec: "node": executable file not found in $PATH` | `runner.envs.PATH` do `~/.forgejo-runner/config.yaml` (workstation) com paths só de host (nvm/bun) — o container perde o node do toolcache (`/opt/acttoolcache`); edição do config exige o toolcache primeiro (ver comentário no próprio config) | Corrigir o PATH no config (toolcache primeiro — ver comentário no próprio arquivo) + `systemctl --user restart forgejo-runner` (incidente 2026-08-17) |
|
||||
| Deploy para logo após o migrate ("Done." e nada mais, EXIT=0) | `docker compose run` anexa stdin por padrão — o container consome o resto do script que vai no pipe do `bash -s`; o bash chega a EOF e termina sem rodar o rollout | O script já usa `< /dev/null` no `run --rm` do migrate (não remover); sintoma visto 2026-08-17 no primeiro deploy |
|
||||
| Build falha: `network mode "stack_default" not supported by buildkit` | BuildKit (drivers docker e docker-container) recusa rede bridge custom no `--network` | O script builda com `--network host` + proxy socat `teqo-1313-build-proxy` (na `stack_default`, publicado em 127.0.0.1:5433, criado idempotentemente com `restart: unless-stopped`) + `DATABASE_URL` reescrita para o loopback |
|
||||
| Build OOM no homeserver | Laptop 8c/16GB com o stack ativo (~12GB livres medidos) | Re-dispatch; se recorrente, item futuro: build na workstation com túnel |
|
||||
| `checkout@v5` falha no job `host` | Label host do act_runner | Fallback: baixar o script direto do Forgejo (`curl -s https://git.solla.dev/fsolla/teqo/raw/branch/main/scripts/deploy-homeserver.sh`) |
|
||||
| Migrate falha | Drift/erro de schema | Job vermelho; site segue no container antigo; corrigir e re-mergear |
|
||||
| Smoke falha pós-up | Regressão de runtime | Rollback automático (restore + `up -d`) + job vermelho; investigar |
|
||||
|
||||
## Segurança (decisão deliberada)
|
||||
|
||||
- O job `deploy` usa `runs-on: host` — executa como `fsolla` na workstation.
|
||||
Está **apenas** no `ci.yml` (push em `main` + dispatch), nunca no `ci-pr.yml`.
|
||||
Está **apenas** no `ci.yml` (janela `*/30` em `main` + dispatch), nunca no
|
||||
`ci-pr.yml`. O job `gate` tem o mesmo perfil e é restrito a
|
||||
`github.ref == 'refs/heads/main'` (dispatch em branch não roda código do
|
||||
branch no host — a suite roda fail-open em containers com secrets de teste).
|
||||
`main` só anda por PR mergeado com suite verde. Fork-PRs não disparam
|
||||
workflows no Forgejo (default off — verificado).
|
||||
- Segredos nunca ecoados: sem `set -x`, senhas via `--password-stdin` /
|
||||
|
|
|
|||
84
docs/plans/ops62-ci-fail-fast-forgejo-impl.md
Normal file
84
docs/plans/ops62-ci-fail-fast-forgejo-impl.md
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
# Impl: OPS62 — CI: fail-fast estrutural por job único sequencial (X1)
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #59
|
||||
Intenção: docs/plans/ops62-ci-fail-fast-forgejo.md
|
||||
Appetite restante: ~1 dia eng (corte: nada de watchdog/API/upgrade — decidido no gate de execução)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** um run de PR (ou de `main`) com **qualquer verificação vermelha** falha o run imediatamente — nada continua rodando depois da primeira falha; o runner é liberado cedo; `checks` vermelho sem esperar o fim dos demais; logs do que já rodou preservados; a suíte **verificada** não muda (mesmas ferramentas e conteúdo: lint, format, typecheck, knip, cycles, unit, int, build, e2e, guards); sem bypass novo além do `--no-verify` documentado.
|
||||
- **O que NÃO negociar:** anti-goals — não perder diagnóstico (steps preservam logs próprios), não mudar o que o CI _verifica_ (só o envelope de jobs muda), `checks` como gate único (contexto `CI (PR) / checks` preservado para waitForChecks/branch protection); aceitar a perda dos logs do segundo shard de e2e (o e2e perde o paralelismo de jobs — 4 workers num único processo; o gate aceitou perder o shard irmão, e aqui o sharding em si é compensado por workers).
|
||||
- **Divergência do aceite da intenção (aprovada pelo humano no gate de execução, 2026-08-18):** o aceite "Forgejo do homeserver roda versão com a API de cancel" e "mesmos jobs, mesma cascata" são **substituídos** — a arquitetura escolhida (X1: 1 job sequencial) torna a API de cancel e o upgrade **desnecessários** (fail-fast é estrutural) e muda o agrupamento de jobs (o que é verificado permanece idêntico). O plano de intenção fica como histórico; este impl plan é a forma aprovada.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart TB
|
||||
subgraph job[Um único job `checks` por workflow<br/>1 container runner · 1 checkout · 1 pnpm install · 1 slot]
|
||||
S1[scope classifier] --> S2[guards de conteúdo]
|
||||
S2 --> S3[check-test-locations] --> L[lint] --> F[format] --> T[typecheck]
|
||||
T --> K[knip] --> C[cycles] --> U[unit]
|
||||
U --> M1[migrate + seed 5433] --> I[int]
|
||||
I --> M2[migrate + seed 5434] --> B1[build] --> B2[build .next-e2e]
|
||||
B2 --> E[e2e · PLAYWRIGHT_WORKERS=4]
|
||||
end
|
||||
L -->|"falha em qualquer step<br/>(if: steps.scope.outputs …)"| FIM
|
||||
F -->|"steps seguintes não rodam"| FIM[run falha imediato<br/>slot liberado · checks vermelho<br/>logs dos steps rodados preservados]
|
||||
```
|
||||
|
||||
**Opções consideradas (gate de execução):** X1 | Y | Z
|
||||
**Recomendação (escolhida pelo humano):** **X1** — 1 job único por workflow, steps sequenciais, fail-fast **estrutural**: falhou um step → os seguintes nem começam → job falha → run falha → slot liberado. Zero dependência de API de cancel (a rota nem existe no Forgejo 9.0.3), zero watchdog (não há slot extra, token, upgrade, nem risco de infra no homeserver — o Forgejo **não** é atualizado). O paralelismo do e2e é recuperado por `PLAYWRIGHT_WORKERS=4` (o Playwright roda workers dentro de um processo — mesma carga de 2 shards × 2 workers de hoje).
|
||||
|
||||
**Rejeitadas:**
|
||||
|
||||
- **Y — fase 1 sequencial + fase 2 em matrix `fail-fast: true`:** preserva verde ≈ atual e cancela irmãos nativamente, mas depende de o Forgejo 9.0.3 cancelar de fato os irmãos de matrix (comportamento de servidor a verificar ao vivo; se falhasse, virava "tudo roda até o fim" na fase 2), mantém 2 slots em vez de 1, e o YAML de matrix por `mode` é mais complexo de manter que steps em série. **Rejeitada** por simplicidade máxima pedida.
|
||||
- **Z — watchdog + upgrade do Forgejo 16:** o risco de infra (upgrade de produção no homeserver, compatibilidade runner × v16) deixou de se justificar quando o fail-fast estrutural cobre o aceite com menos peças. **Rejeitada.**
|
||||
- **Watchdog em `runs-on: host`:** ci-pr jamais roda host (pin OPS53). **Rejeitada.**
|
||||
- **Paralelizar steps com processos `&`/`wait`:** logs interleaved + fail-fast manual = mini-watchdog em bash. **Rejeitada.**
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`.forgejo/workflows/ci-pr.yml`** (reescrito — X1): 1 job `checks` (nome default → contexto `CI (PR) / checks` preservado; **o nome do job é o contrato** do waitForChecks OPS61-2b e da branch protection). Steps em série, cada um com `if:` de skip do classifier: `scope` (`id: scope`; outputs `code_mode/build_mode/test_mode/e2e_mode/e2e_specs` via `$GITHUB_OUTPUT` — mesmo comando do job atual, com `set -euo pipefail`), guards de conteúdo (changelog append-only, aggregate, conflict markers, plans-only — movidos para o começo: falham rápido e são sobre o PR), `check-test-locations`, `lint`, `format:check`, `typecheck`/`knip`/`cycles` (`if: steps.scope.outputs.code_mode != 'none'`), `unit` (full/changed), `migrate`+`seed:minimal` (DB int), `int` (full/changed), `migrate`+`seed:minimal` (DB build/e2e), `build` (if `build_mode != 'none'`), `build .next-e2e` + `e2e` (if `e2e_mode != 'none'`; full = `pnpm test:e2e` sem shard com `PLAYWRIGHT_WORKERS=4`; selected = specs do output). **2 services Postgres alcançados por NOME na rede do job** (`postgres-int` / `postgres-build` na 5432, **sem publish host** — o OPS50 publicava portas no gateway; o X1 remove o publish: o job único seguraria as portas fixas pelo run inteiro e runs concorrentes colidiriam, e o Forgejo 9 não expande expressões em `services.ports` (medido ao vivo: run 730 falhou em 1s com a string literal da expressão) — o DNS da rede do job é a solução canônica e mata a colisão de raiz). Isolamento preservado (o e2e nunca herda a sujeira dos testes int; o build de prod e o de e2e compartilham o service build/e2e). `timeout-minutes: 50` (soma esperada ~21 min + margem; o run nunca segura o slot além disso). Sem `needs`/`if: always()`/matrix/jq de rollup (não há irmãos). Comentário de cabeçalho reescrito: OPS62 substitui o parágrafo "Forgejo has no cancel-run plumbing; job timeouts cover that role" — o fail-fast é estrutural (1 job), sem API de cancel. **Trade-off assumido:** `migrate`+`seed:minimal` do int rodam também em PR docs-only (mode none) — intencional (a cadeia stale é pega em todo PR), custo ~1–2 min por PR de docs.
|
||||
- **`.forgejo/workflows/ci.yml`** (reescrito — X1): mesma estrutura no `main`; `static` (já era job único sequencial) se funde ao job `checks` com int/build/e2e; `deploy` permanece `needs: [checks]` (inalterado — OPS53). `timeout-minutes: 50`. Services por nome, sem publish (mesma mecânica do ci-pr).
|
||||
- **`scripts/lib/cli.mjs` + `tests/helpers/assertTestDatabase.ts`** (editar — guards fail-closed): `LOCAL_HOSTS`/allowlist do teste ganham `postgres-int` e `postgres-build` (nomes dos services do CI na rede do job — hosts internos do runner, inalcançáveis de fora; o contrato continua rejeitando qualquer host remoto real; o gateway RFC1918 do OPS50 permanece por compatibilidade). Pin em `tests/unit/localHosts.unit.spec.ts`.
|
||||
- **`tests/unit/ciSkipInvariants.unit.spec.ts`** (editar — pin da arquitetura): invariantes novos — os dois workflows têm **exatamente um job** cujo id é `checks`; os steps-chave existem na ordem (lint antes de e2e; guards antes de lint); o ci-pr não contém `runs-on: host` (pin OPS53), nem `matrix:`, nem `fail-fast:`; `PLAYWRIGHT_WORKERS: 4` presente; `.next-e2e` continua pinado (invariante existente); o ci.yml mantém o job `deploy` com `needs: [checks]`.
|
||||
- **`docs/AGENT-OPS.md`** (editar): tabela de CI — ci-pr/ci agora 1 job `checks` sequencial com fail-fast estrutural; remover menção a "fase 1→2 em cascata" se houver; nota "Dono do PR, dono do CI" intacta (o próprio PR define seu CI).
|
||||
- **`docs/changelog/2026-08-18-ops62.md`** (novo) + `pnpm changelog:build`.
|
||||
- **Migration / Access / Consent / UI:** N/A (Impeccable A).
|
||||
- **Fora do repo:** nada — **o upgrade do Forgejo é cancelado** (decisão X1); o homeserver não é tocado.
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
N/A — chore de DX/processo.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Workflows X1** — reescrever `ci-pr.yml` e `ci.yml` (job único, 2 services, steps condicionais); `bash`/YAML válido (sem parser YAML no repo — validar por leitura + os invariantes). Gates parciais: `pnpm lint`, `format:check`, `typecheck`, `knip`, `check:cycles`.
|
||||
2. **Invariantes** — `ciSkipInvariants.unit.spec.ts` (pin da arquitetura: 1 job `checks`, ordem dos steps, sem host/matrix/fail-fast no ci-pr, deploy no ci.yml); `pnpm test:unit` (spec novo).
|
||||
3. **Docs + fechamento** — AGENT-OPS, changelog + `changelog:build`; gates completos (`pnpm test` int incluso, `pnpm build`); push via `pnpm push`.
|
||||
4. **Validação ao vivo (no próprio PR do OPS62)** — o ci-pr deste PR **já é o X1**: (a) run verde prova que a suíte inteira roda no envelope novo; (b) o CI do PR com um step quebrado (ex.: antes do merge, um push deliberado com `lint` quebrado) prova o fail-fast: run falha no primeiro vermelho, steps seguintes nem começam, logs preservados — verificação documentada no fechamento. Sem passo de infra pós-merge.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Watchdog, API de cancel, upgrade do Forgejo, token PAT:** fora — X1 não precisa de nenhum (a intenção fica como histórico).
|
||||
- **Mudar o que o CI verifica:** fora — mesmas ferramentas, mesmo conteúdo, mesma ordem de suíte; só o envelope muda.
|
||||
- **Rerun granular de steps** (re-tentar só o que falhou): o Forgejo não tem rerun por API (session-only); re-push continua sendo o caminho — como hoje.
|
||||
- **Voltar a shards de e2e em jobs separados:** se o tempo de e2e full com 4 workers incomodar (medida no run deste PR), o caminho é Y (matrix fail-fast), não o watchdog — registrar como débito se medir > ~10 min.
|
||||
- **Timeout do `waitForChecks` (30 min) × job `checks` (50 min)** — débito de CI (revisão /simplify P2): um run verde pode passar dos 30 min com fila do runner/retries de e2e e o automerger lançar "Timeout esperando checks" num PR verde. Gatilho para corrigir: primeiro timeout observado. Alternativa curta (1 linha) registrada: alinhar `timeoutMs` do `waitForChecks`/`autoMerge` no `forgejo-api.mjs` ao timeout do job (50–55 min).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Tempo de parede do run verde aumenta** (~15–18 → ~21 min esperados: perde a paralelização da fase 1 e os 2 shards de e2e; ganha 1 checkout/install e 1 migrate/seed). **Mitigação:** medido no run deste PR; e2e com 4 workers compensa os shards; o aceite X1 do humano cobre o custo.
|
||||
- **E2E vermelho é o caso mais lento** (veredito só após todos os steps anteriores). **Mitigação:** guards/lint/format/typecheck falham cedo (os casos comuns); e2e é a falha menos frequente e o report mostra o spec que falhou. Débito registrado (Y) se a frequência exigir.
|
||||
- **Step `scope` com outputs e steps condicionais** — troca `needs.scope.outputs` por `steps.scope.outputs`: mesma semântica, semântica de skip idêntica (none → steps skipped, não falham). Validado por um PR de docs (mode none) no próprio repo.
|
||||
- **1 service compartilhado int/e2e** — rejeitado no plano (2 services 5433/5434 preservam o isolamento; risco zero de fixture colidir).
|
||||
- **`checks` como job único muda o status check de "rollup que espera needs" para "o próprio run"** — contexto e nome preservados (`checks`), então waitForChecks (OPS61-2b) e branch protection continuam vendo o contexto certo; quando o job falha, o status do sha é `failure` — veredito mais direto ainda.
|
||||
- **Run de main (`ci.yml`)**: com deploy `needs: checks`, qualquer falha agora impede o deploy **imediatamente** (hoje também, mas só no fim dos irmãos) — mesma garantia, veredito mais cedo.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [x] Aceite de produto coberto (forma X1 aprovada pelo humano): qualquer verificação vermelha falha o run no ato; runner liberado cedo; `checks` vermelho sem esperar o fim dos demais; logs preservados (steps com logs próprios); suíte verificada idêntica; sem bypass novo.
|
||||
- [x] Invariantes AGENTS/engineering-standards: sem migration/access/Consent/UI; pin da arquitetura em spec (1 job `checks`, sem host no ci-pr, sem matrix/fail-fast); identifiers em inglês; copy pt-BR só em labels (inalterado).
|
||||
- [x] Testes previstos: unit dos invariantes de workflow (não há write path de app).
|
||||
103
docs/plans/ops64-forgejo-pr-automerge-waitforchecks-impl.md
Normal file
103
docs/plans/ops64-forgejo-pr-automerge-waitforchecks-impl.md
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
# Impl: OPS64 — forgejo-pr-automerge: waitForChecks conta o próprio status pendente (deadlock → timeout, merge nunca acontece) + rollup `checks` sem agregação de shards
|
||||
|
||||
Status: em execução (entregue — ver desfecho no final)
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #62
|
||||
Intenção: body da Issue (sem plano de intenção separado — body é a spec)
|
||||
Appetite restante: herdado (~1 dia de ops)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** (primário) o safety net `ready-automerge` deixa de se auto-bloquear no próprio status `pending` e mergea PRs com CI verde; (secundário) o rollup `checks` do `ci-pr.yml` (e o do `ci.yml`, que gateia o deploy) deixa de reportar SUCCESS com um shard de e2e vermelho — o gate do servidor (branch protection) e o UI param de mentir.
|
||||
- **O que NÃO negociar:** merge só com CI verde de verdade (a classe OPS52 — merge manual/automático com shard vermelho — não pode voltar); `waitForChecks` continua ignorando o próprio contexto; nada de fork rodando código com o PAT do repo (guarda do OPS61); sem edição de Issues `in-progress` de terceiros; nada de prod DB.
|
||||
- **O que reavaliar:** a intenção lista três correções possíveis para o primário (filtrar próprio context / `merge_when_checks_succeed` nativo / timeout > 40 min) — **a evidência mostra que o primário já foi entregue pelo OPS61** (issue criada antes do OPS61 subir); o trabalho real do OPS64 é o **secundário** (agregação de shards no rollup), que está vivo e medido.
|
||||
|
||||
## Achados da exploração (evidência ao vivo 2026-08-18)
|
||||
|
||||
1. **Primário (deadlock do próprio pending) — JÁ ENTREGUE pelo OPS61** (`8b989306`, em `main`): `waitForChecks` filtra contextos `PR Ready + auto-merge` (`verdicts`), gateia no rollup `CI (PR) / checks` presente + success, e o merge POST usa `FORGEJO_API_TOKEN` (409 do pre-receive). **Provado vivo:** runs 710 (PR #67) e 712 (PR #70) do `ready-automerge` terminaram `success` e os PRs foram mergeados no momento do fim do run (21:32:24/21:35:24 vs fim 21:32:27/21:35:31) — o CLI mergeou. O timeout já subiu para 45 min (CLI) / 55 min (workflow). A opção "timeout > 40 min" da intenção também já está entregue.
|
||||
2. **Secundário (rollup `checks` mente) — VIVO e medido em 5 runs:** o resultado do job-pai de matrix no contexto `needs` do Forgejo 9.0.3 (gitea-1.22.0) é o resultado do **último shard a reportar**, não um AND sobre os shards:
|
||||
- runs 604/607/610 (PR #55/#56/#57, ci-pr pré-OPS61 — mesmo jq de hoje): e2e (1)=failure, e2e (2)=success → `checks`=SUCCESS (shard vermelho mascarado);
|
||||
- run 716 (PR #71, pós-OPS61): e2e (1)=success, e2e (2)=failure → `checks`=failure (o vermelho era o último — pegou por acaso);
|
||||
- run 638: e2e (1)=failure, e2e (2)=success → `checks`=failure **só porque int e build também falharam** (o e2e vermelho continuou mascarado).
|
||||
Ou seja: o gate `CI (PR) / checks*` do servidor e o rollup jq (`all(.value.result == "success" or "skipped")`) passam com um shard vermelho quando o último shard é verde.
|
||||
3. **Por que o CLI ainda é seguro hoje:** `waitForChecks` varre **todos** os statuses individuais (`failed` inclui `CI (PR) / e2e (1)` = failure → throw). Foi por isso que no run 607 "só o waitForChecks pegou o vermelho". O buraco é o **gate do servidor** (branch protection satisfeita por rollup verde) + o UI — e o `deploy` do `ci.yml` (mesmo jq) rodaria com shard vermelho em main.
|
||||
4. **Não existe `needs.<matrix>.results` no runner do Forgejo 9.0.3:** o `Needs` do act (gitea/act `pkg/exprparser/interpreter.go`) tem só `Outputs` e `Result` — o contrato `.results` do GitHub não existe aqui. A correção do rollup **não pode** vir do contexto `needs`.
|
||||
5. **`merge_when_checks_succeed` existe neste servidor** (swagger + fonte gitea 1.22: `ScheduleAutoMerge` → `IsPullCommitStatusPass`), mas o OPS50/61 escolheu poll+merge e ele **funciona** (achado 1). Além disso o auto-merge nativo gateia nos contextos exigidos da branch protection — o mesmo rollup mentiroso — então **não** corrigiria o secundário; e o `mergeable` do servidor também usa o mesmo `MergeRequiredContextsCommitStatus`. Decisão: manter poll+merge; corrigir o rollup.
|
||||
6. **Shards já postam status individuais:** cada shard do e2e posta `CI (PR) / e2e (N) (pull_request)` (e `CI / e2e (N) (push)` no main) — o dado confiável é o status do commit, não o parent do `needs`. É a mesma fonte que o `waitForChecks` usa (`listCommitStatuses`).
|
||||
7. **Risco RCE ao colocar PAT no ci-pr.yml:** o `ci-pr.yml` roda em PRs de fork (repo público, sem guard no workflow). Injetar `FORGEJO_API_TOKEN` no job `checks` **sem** o guard same-repo seria código do fork rodando com o PAT (a mesma classe que o OPS61 guardou nos pós-merge). Qualquer uso de PAT no `ci-pr.yml` exige `if: head.repo.full_name == github.repository` no job.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[rollup checks: jq sobre needs parent de matrix MENTE] --> B[novo script ci-rollup-check.mjs lê statuses do sha via API]
|
||||
C[waitForChecks já varre statuses individuais - seguro] --> D[nada a mudar no CLI]
|
||||
B --> E[ci-pr: fork guard + FORGEJO_API_TOKEN + script]
|
||||
B --> F[ci.yml: FORGEJO_API_TOKEN + script - gate do deploy honesto]
|
||||
G[testes unit: veredito do script + waitForChecks com rollup verde e shard vermelho] --> H[PR Closes #62]
|
||||
```
|
||||
|
||||
**Opções consideradas:**
|
||||
|
||||
- **A — rollup lê os statuses do commit via API (`listCommitStatuses`), com o mesmo prefixo do workflow (`CI (PR) / `, `CI / `) e excluindo o próprio contexto (`…/ checks`):** veredito honesto por construção, mesma fonte do `waitForChecks`, funciona para o `ci-pr.yml` e o `ci.yml` (gate do deploy).
|
||||
- B — `needs.<matrix>.results` (contrato GitHub): **inexistente** no act do Forgejo 9.0.3 (fonte, achado 4).
|
||||
- C — `merge_when_checks_succeed` nativo (opção da intenção): existe no servidor, mas gateia nos contextos exigidos (rollup mentiroso) — não corrige o secundário; poll+merge atual já funciona (achado 1).
|
||||
- D — quebrar a matrix em jobs explícitos (e2e-1/e2e-2): mexe no contrato OPS34 (`e2eShardConfig` pinado por unit test `shard: [1, 2]`), refatora o classificador de escopo; não é o dono do problema (o dono é o veredito do rollup).
|
||||
- E — timeout > 40 min (opção da intenção): já entregue (45/55); não corrige a mentira do rollup.
|
||||
- F — deixar como está (rollup pode mentir, "o CLI pega"): deixa o gate do servidor e o `deploy` vulneráveis à classe OPS52.
|
||||
|
||||
**Recomendação:** A — porque é o único caminho que (a) usa a mesma fonte que o CLI já confia (statuses do commit — não o parent de matrix), (b) corrige os dois rollups (PR e main/deploy), (c) não mexe no contrato OPS34, (d) é testável como função pura. O PAT no `ci-pr.yml` entra **com o fork guard** no job `checks` (achado 7).
|
||||
|
||||
**Rejeitadas:** B (não existe no runner — falha silenciosa ou dependência de upgrade); C (não corrige o secundário — o auto-merge nativo confiaria no rollup mentiroso; e o poll+merge provado continua); D (refatora contrato OPS34 sem necessidade); E (já entregue, não é fix); F (classe OPS52 no gate do servidor + deploy vermelho em main).
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`scripts/lib/ci-rollup-check.mjs`** (novo, puro, zero-dep): `rollupVerdict(statuses, { prefix, ownPrefix })` → `{ ok, failed: string[], pending: string[] }` — falha (exit 1) se qualquer contexto com o prefixo do workflow (excluindo o próprio rollup) for `failure`/`error`; falha também se houver `pending` (cascata não assentada — fail-closed); falha se a lista vier vazia (API indisponível/estranho — nunca "verde por falta de dado"); success apenas quando todos os demais contextos do workflow estiverem `success` (skipped posta como success, observado). Reusa `listCommitStatuses` do `forgejo-api.mjs`.
|
||||
- **`scripts/ci-rollup-check.mjs`** (novo, CLI plain Node, padrão `forgejo-pr-automerge.mjs`): `--sha <head-sha> --prefix "CI (PR) / " --own-prefix "CI (PR) / checks"` (no `ci.yml`: `"CI / "` / `"CI / checks"`); imprime os contextos que falharam e sai 1; verde → 0.
|
||||
- **`.forgejo/workflows/ci-pr.yml`** (job `checks`): `if:` ganha o fork guard (`github.event.pull_request.head.repo.full_name == github.repository`, pré-checkout — mesmo padrão do `ready-automerge`); `env: FORGEJO_API_TOKEN`; steps ganham `actions/checkout@v5` + `actions/setup-node@v5` (node 24, `package-manager-cache: false`) + `node scripts/ci-rollup-check.mjs --sha "${{ github.event.pull_request.head.sha }}" --prefix "CI (PR) / " --own-prefix "CI (PR) / checks"`; o passo jq do `needs` sai (o script o substitui — fonte única). `needs` e `if: always()` permanecem (o job só roda depois da cascata toda — a ordenação que garante "assentou").
|
||||
- **`.forgejo/workflows/ci.yml`** (job `checks`): idem, sem fork guard (evento push/dispatch não tem fork); `--sha "${{ github.sha }}"`, prefixo `CI / `. Com isso o `deploy` (que `needs: [checks]`) nunca roda com shard de e2e vermelho em main.
|
||||
- **`tests/unit/forgejoApi.unit.spec.ts`**: novo caso pinando o cenário run-607 — rollup `CI (PR) / checks` = success **com** `CI (PR) / e2e (1)` = failure → `waitForChecks` lança "Checks falharam" (o CLI nunca confia no rollup sozinho).
|
||||
- **`tests/unit/ciRollupCheck.unit.spec.ts`** (novo): veredito puro — (a) shard vermelho + rollup próprio pending → fail (o run 607 do passado, agora no rollup); (b) shard (2) vermelho → fail (run 716); (c) tudo success → ok; (d) contexto do safety net (`PR Ready + auto-merge`) pending → ignorado (não casa o prefixo); (e) próprio contexto pending → ignorado; (f) lista vazia → fail; (g) variante `CI / ` do main; (h) `skipped` postado como success → ok.
|
||||
- **Docs:** `.agents/rules/agent-pr-workflow.mdc` (seção "Required checks": rollup agora verifica os statuses individuais via API — o parent de matrix do Forgejo não agrega; nota do fork guard: PRs de fork ficam sem o status `checks` → merges de fork bloqueados pelo servidor, hardening intencional), `docs/AGENT-OPS.md` (linha da branch protection + tabela de workflows), header dos dois workflows, `docs/changelog/2026-08-18-ops64.md` + `pnpm changelog:build`.
|
||||
- **Migration:** sem migration (não toca schema/DB).
|
||||
- **Access / Consent:** N/A.
|
||||
- **UI:** N/A (A).
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Script + veredito puro** — `scripts/lib/ci-rollup-check.mjs` + CLI + unit tests; `pnpm test:unit` local.
|
||||
2. **Workflows** — `ci-pr.yml` e `ci.yml` com o novo passo; diff completo no PR da entrega.
|
||||
3. **Gates** — `pnpm gate:fast` local (lint/format/typecheck/knip/cycles/unit); e2e roda no CI (OPS59). Push via `pnpm push`; PR `Closes #62`. **Verificação ao vivo na própria PR:** o run do `ready-automerge` da PR prova o primário de novo (já provado no OPS61); o novo rollup proof na PR — se um shard falhar, `checks` fica vermelho (e o servidor bloqueia), se tudo verde, mergea.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Não trocar poll+merge por `merge_when_checks_succeed` nativo (achado 5 — não corrige o secundário; poll+merge provado; trocar é item futuro se algum dia o upgrade do Forgejo mudar o contrato).
|
||||
- Não consertar o parent de matrix do Forgejo (bug upstream do runner; a correção é viver sem ele).
|
||||
- Não refatorar a matrix e2e (OPS34) nem o classificador de escopo.
|
||||
- Não adicionar o fork guard aos demais jobs do `ci-pr.yml` (não têm segredos; fora do escopo).
|
||||
- Não mexer no `waitForChecks` além do teste novo (o CLI já está correto — achado 3).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **PRs de fork perdem o status `checks`** (fork guard no job): merges de fork ficam bloqueados pelo servidor (contexto exigido nunca posta). Hardening intencional e alinhado à política atual ("a merged fork PR would deploy" — o `ready-automerge` já exclui forks); documentado no changelog. Se um dia um merge de fork for legítimo, é o escape documentado do OPS61 (ajustar a regra temporariamente).
|
||||
- **API indisponível no job `checks` → rollup vermelho:** fail-closed (nunca verde por falta de dado); o job vermelha e o PR fica bloqueado até a infra voltar — visível, não silencioso. O mesmo runner self-hosted que roda os jobs serve a API (mesma rede), e o `ready-automerge` já depende dela.
|
||||
- **Race status×rollup (status do último shard postado depois do `checks` começar):** o job `checks` só roda após `needs` da cascata toda (a ordenação do workflow garante "assentou"), e o runner posta o status no fim de cada job — o window é o mesmo que o jq atual já tinha; o `waitForChecks` (poll) continua sendo o backstop do merge.
|
||||
- **O script roda o código do head no job `checks` (same-repo):** mesmo nível de confiança do `ready-automerge` (que também roda script do head com o PAT) — same-repo tem write de qualquer forma.
|
||||
|
||||
## Desfecho (gate com o humano — OPS62 mergeou em main durante a execução)
|
||||
|
||||
O OPS62 (mergeado às 23:32Z enquanto este item rodava) reescreveu ci-pr.yml e
|
||||
ci.yml como **jobs únicos sequenciais** — sem matrix, sem shards. O bug de
|
||||
agregação do parent de matrix que este item atacava **deixou de existir
|
||||
estruturalmente**: o status do job `checks` agora É o veredito honesto da
|
||||
cascata. Decisão do gate: **descartar** os edits de workflow e o script
|
||||
`ci-rollup-check.mjs` (redundantes pós-OPS62), **manter** o teste-pino do
|
||||
`waitForChecks` (run 607: rollup verde + shard vermelho → CLI lança) e as docs
|
||||
honestas. Entregue: pin + docs + changelog.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [x] Aceite de produto da intenção ainda coberto (primário já entregue pelo OPS61; secundário eliminado estruturalmente pelo OPS62; o CLI segue com a defesa individual de statuses, pinada por teste)
|
||||
- [x] Invariantes AGENTS/engineering-standards (sem código morto — script descartado; docs honestas — a mentira do parent de matrix documentada)
|
||||
- [x] Testes de domínio previstos (waitForChecks run-607 pinado em `forgejoApi.unit.spec.ts`)
|
||||
- [x] Verificação: unit 2360 verdes; lint/format/typecheck/knip/cycles no gate local; a própria PR prova o ciclo (o `ready-automerge` mergea no fim)
|
||||
193
docs/plans/ops65-ci-main-janela-30min-e-matar-pool-impl.md
Normal file
193
docs/plans/ops65-ci-main-janela-30min-e-matar-pool-impl.md
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
# Impl: CI do main em janela de 30 min + matar o agent-pool
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #64
|
||||
Intenção: docs/plans/ops65-ci-main-janela-30min-e-matar-pool.md
|
||||
Appetite restante: herdado (~0,5–1 dia eng; um outcome verificável)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a workstation deixa de pagar a CI do main a cada merge e o tick
|
||||
do agent-pool. `ci.yml` roda por **janela fixa de 30 min** (`schedule */30` +
|
||||
`workflow_dispatch`), com um **gate barato (~segundos, sem pnpm)** que
|
||||
classifica "mudança de produção" comparando o HEAD de `main` com o SHA
|
||||
**deployado** no homeserver; sem mudança → suite + deploy skipped, run verde.
|
||||
Deploy manual (dispatch) continua imediato. `agent-pool.yml` é removido.
|
||||
- **O que NÃO negociar:** não remover a verificação pós-merge do main (o
|
||||
`ci.yml` continua o verificador); deploy continua gated pelo verificador
|
||||
verde; sem segundo mecanismo de deploy fora do pipeline; nada de requeue
|
||||
estilo cooldown (janela fixa é o corte).
|
||||
- **O que reavaliar:** a hipótese de "classificar por `.dockerignore`" é
|
||||
confirmada — e é a única abordagem que **falha fechado** (qualquer dúvida →
|
||||
suite roda; ver anti-goal "não remover a verificação do main"). O exemplo do
|
||||
aceite ("só docs/**scripts**/skills/AGENTS → skip") **não** vale literalmente
|
||||
sob `.dockerignore`: `scripts/`, `tests/`, `.forgejo/` e `AGENTS.md` **estão
|
||||
no build context** (o Dockerfile faz `COPY . .`) → contam como produção.
|
||||
Decisão resolvida pela direção explícita do plano (`.dockerignore` é a fonte
|
||||
da verdade) + anti-goal: a classificação é **conservadora** (mais runs, nunca
|
||||
menos). Só `docs/`, `.agents/`, `.env*`, artefatos etc. viram skip.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M[merge em main] --> S[schedule */30 ou workflow_dispatch]
|
||||
S --> C[check: runs-on host<br/>lê SHA deployado do compose no homeserver<br/>git diff --name-only <deployado> HEAD]
|
||||
C --> G{produção mudou?<br/>dockerignore do build context}
|
||||
G -->|não| SK[suite + deploy skipped<br/>run verde]
|
||||
G -->|sim| SU[suite full]
|
||||
SU --> CH[checks rollup]
|
||||
CH --> D[deploy: já deployado?<br/>guard idempotente]
|
||||
D -->|compose já no SHA| DONE[skip verde]
|
||||
D -->|SHA novo| DEP[build + migrate + rollout homeserver]
|
||||
```
|
||||
|
||||
**Opções consideradas:**
|
||||
|
||||
- **A) Gate `check` (runs-on `host`, ~segundos):** checkout com `fetch-depth: 0`
|
||||
→ `ssh homeserver` lê o SHA deployado do `~/stack/docker-compose.yml`
|
||||
(`image: teqo-1313:<sha>`) → `git diff --name-only <sha> HEAD` →
|
||||
`scripts/ci-classify-production.mjs` classifica pelos padrões do
|
||||
`.dockerignore` (semântica moby, matcher puro em Node stdlib, sem pnpm).
|
||||
Job `deploy` ganha guard de idempotência no script remoto ("compose já
|
||||
referencia o SHA → exit 0"). Recomendada.
|
||||
- **B) Gate comparando `HEAD` vs último SHA conhecido do run anterior**
|
||||
(estado em arquivo na workstation / Forgejo API). Rejeitada — o estado
|
||||
real da produção vive no homeserver; derivar de artefatos de CI mente
|
||||
quando um run falha no meio (compose restaurado no rollback = a verdade).
|
||||
- **C) Whitelist manual de "caminhos de produção"** (src/, public/, Dockerfile…).
|
||||
Rejeitada — drift e **falha aberto**: um caminho esquecido → suite pulada
|
||||
indevidamente → main não verificado, exatamente o anti-goal. `.dockerignore`
|
||||
é auto-mantido e é o que define o artefato.
|
||||
|
||||
**Decisões de engenharia (com rejeitadas):**
|
||||
|
||||
1. **Gate `check` em `runs-on: host`** (não container): precisa de `ssh
|
||||
homeserver` (a chave vive no host da workstation — mesmo padrão do job
|
||||
`deploy`, OPS53). Segurança: job só em `ci.yml` (main + dispatch), nunca em
|
||||
`ci-pr.yml` — mesma premissa já validada no OPS53.
|
||||
2. **Fail-open no gate:** o gate lê a **revision do container rodando** no
|
||||
homeserver (`docker inspect` → label `org.opencontainers.image.revision`;
|
||||
o compose pode mentir após rollback falho, pois é trocado antes do rollout).
|
||||
Revision desconhecida (label ausente/container sem label) → `production =
|
||||
true` (suite roda, run verde). Gate **incapaz de classificar** (erro de
|
||||
git/`.dockerignore`/sem input) → imprime `production=true` e sai com exit
|
||||
não-zero → o run fica **vermelho** (nunca blackout silencioso). Deploy
|
||||
nunca roda no escuro: condição dos jobs da suite é
|
||||
`needs.gate.result != 'success' || needs.gate.outputs.production == 'true'`.
|
||||
3. **Deploy condicionado duplo:** `needs: [checks, gate]` + `if:
|
||||
needs.checks.result == 'success' && needs.gate.outputs.production ==
|
||||
'true'` — sem isso, um `if` só no output rodaria deploy com suite vermelha
|
||||
(semântica do Actions: `if` verdadeiro vence `needs` falho).
|
||||
4. **Rollup `checks` intocado:** `if: always()` + `all(success or skipped)` já
|
||||
aceita jobs skipped → run verde com chips skipped quando nada a fazer.
|
||||
5. **Classificador:** matcher de `.dockerignore` (moby semantics: padrão sem
|
||||
`/` casa basename em qualquer profundidade; `!` negação; `/` ancorado à
|
||||
raiz; `/dir/` só diretório; `**`) + CLI `scripts/ci-classify-production.mjs`
|
||||
(`--deployed <sha>`/`--files-from`, `--value`; dispatch → produção forçada;
|
||||
exit 0 = classificou, exit 1 = não classificou). Sem pnpm, sem deps.
|
||||
6. **Guard "already deployed" no `deploy-homeserver.sh`:** após o HEAD guard +
|
||||
flock, antes de sourcear secrets: se o **container rodando** já tem a
|
||||
revision do SHA → `exit 0` ("nothing to do"). Mata o rebuild de ~15 min em
|
||||
dispatch duplicado. Container sem label/fora = "não deployado" (procede —
|
||||
direção segura). Sem flag FORCE (YAGNI; força = fluxo manual do runbook).
|
||||
7. **Remoção do `on: push`:** branch protection do main exige apenas
|
||||
`CI (PR) / checks*` (cascade do `ci-pr.yml`) — merges não dependem do
|
||||
`ci.yml` pós-merge (verificado em `scripts/configure-branch-protection.mjs`
|
||||
e `lib/branch-protection.mjs`). `agent-pr-ready-automerge` e
|
||||
`issue-done-on-main-merge` são eventos de PR — intocados.
|
||||
8. **`fetch-depth: 0` no job `gate`** — o diff `<deployado>..HEAD` precisa do
|
||||
histórico; custo de 1 clone full a cada 30 min é desprezível vs a suite.
|
||||
Overlap de janelas (suite > 30 min, sem `concurrency` no Forgejo):
|
||||
limitado e auto-dedup via revision deployada (a segunda janela vê
|
||||
deploy == HEAD → skip); flock serializa deploy. Documentado como limite
|
||||
conhecido.
|
||||
9. **Hardening pós-review:** job `gate` com `actions/setup-node@v5` (node 24
|
||||
explícito no host), restrito a `github.ref == 'refs/heads/main'` (dispatch
|
||||
em branch não roda código do branch no host — a suite roda fail-open em
|
||||
containers com secrets de teste), e invocação única do classificador
|
||||
(JSON capturado uma vez; `production` extraído via `node -pe`).
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`.forgejo/workflows/ci.yml`**: `on:` vira `schedule */30` +
|
||||
`workflow_dispatch` (remove `push`); job `gate` novo (host, main-only,
|
||||
output `production`); `static/int/build/e2e` ganham `needs: [gate]` + `if`
|
||||
fail-open; `deploy` ganha `needs: [checks, gate]` + `if` duplo. Cabeçalho
|
||||
atualizado.
|
||||
- **`.forgejo/workflows/agent-pool.yml`**: **removido** (scripts/skills/docs do
|
||||
pool ficam dormentes — aceite).
|
||||
- **`scripts/lib/dockerignore.mjs`** (novo): `parseDockerignore` /
|
||||
`isIgnoredPath` — matcher puro de `.dockerignore` (moby semantics), stdlib.
|
||||
- **`scripts/ci-classify-production.mjs`** (novo): CLI — dispatch → true;
|
||||
SHA deployado ausente → true; senão `git diff --name-only <sha> HEAD` →
|
||||
classifica; JSON no stdout (`--value` para o workflow); erro interno → true
|
||||
- stderr (fail-open), exit 0.
|
||||
- **`scripts/deploy-homeserver.sh`**: guard "already deployed" (compose já
|
||||
referencia o SHA → skip verde) após o flock, antes dos secrets.
|
||||
- **`scripts/lib/test-affected-core.mjs`**: `HIGH_RISK_EXACT` +=
|
||||
`scripts/ci-classify-production.mjs`, `scripts/lib/dockerignore.mjs`
|
||||
(mudar o classificador força suite full no PR — padrão existente).
|
||||
- **Migration:** sem migration.
|
||||
- **Access / Consent:** N/A.
|
||||
- **UI:** Impeccable A — sem UI.
|
||||
|
||||
### Dados → forma
|
||||
|
||||
N/A — política de infra/CI.
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Classificador core** — `lib/dockerignore.mjs` + `ci-classify-production.mjs`
|
||||
- specs unit (matcher contra o `.dockerignore` real; classify pure; CLI via
|
||||
`--files-from`; fail-open: sem SHA deployado / dispatch / erro → true).
|
||||
2. **Workflow + pool** — `ci.yml` (schedule + gate + ifs), delete
|
||||
`agent-pool.yml`, `HIGH_RISK_EXACT`, pins do `ciSkipInvariants` (janela 30,
|
||||
sem `push`, gate existe, ifs fail-open) e `deployScript` (guard
|
||||
"already deployed").
|
||||
3. **Docs + changelog** — runbook `docs/ops/teqo-1313-deploy.md` (janela,
|
||||
gate, "already deployed", falhas conhecidas: ssh do gate falha → fail-open;
|
||||
overlap), `AGENTS.md` (parágrafo CI/deploy), `docs/AGENT-OPS.md` (linhas de
|
||||
`ci.yml` e `agent-pool.yml`), `docs/changelog/2026-08-18-ops65.md` +
|
||||
`pnpm changelog:build`, status `entregue` no plano de intenção.
|
||||
4. **Gates** — `pnpm gate:fast`, `pnpm format:check`, `pnpm knip`,
|
||||
`pnpm check:cycles`, `pnpm build` local. Sem mudança em `src/` → e2e do PR
|
||||
skip por affected.
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Reimplementar cooldown GitHub (defer/requeue) — corte do plano; janela fixa.
|
||||
- Classificação fina por tipo de arquivo (whitelist) — corte do plano;
|
||||
`.dockerignore` é a fonte da verdade.
|
||||
- Flag FORCE no deploy / UI de deploy — runbook basta.
|
||||
- Limpar scripts/skills/docs do pool — dormentes por aceite.
|
||||
- Mover a CI para VPS/homeserver — fora de escopo do plano.
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **`ssh homeserver` falha no gate** → fail-open (suite roda); deploy fica para
|
||||
a próxima janela (≤30 min, auto-cura). Runbook documenta.
|
||||
- **Overlap de janelas** (suite > 30 min) → segunda suite no mesmo SHA
|
||||
(raro, limitado); flock serializa; SHA deployado dedupa a janela seguinte.
|
||||
- **Dispatch do mesmo SHA** → suite roda (intenção explícita), deploy skip
|
||||
verde "already deployed"; força via fluxo manual do runbook.
|
||||
- **Remoção do `push` → "merge != deploy imediato"** → aceite explícito da
|
||||
intenção (≤30 min); dispatch cobre urgência; falha de deploy continua
|
||||
vermelha e o site fica no container antigo.
|
||||
- **Deploy antigo sobrescrevendo push novo** → HEAD guard + flock intactos.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [x] Aceite de produto da intenção ainda coberto (janela 30 min; run verde
|
||||
com skipped; pool morto; dispatch imediato; deploy gated)
|
||||
- [x] Invariantes AGENTS/engineering-standards (sem segredos novos; guards de
|
||||
dev/test intocados; nada de Neon; host jobs só em ci.yml)
|
||||
- [x] Testes previstos (unit: matcher + classificador + pins de workflow e
|
||||
script de deploy)
|
||||
|
||||
Self-score decision-quality: 1) decisões caras com rejeitadas ✓ 2) cabe no
|
||||
appetite ✓ 3) rabbit holes nomeados ✓ 4) reusa padrões existentes (OPS53 host
|
||||
job + ssh, flock, HEAD guard, ciSkipInvariants/deployScript pins, HIGH_RISK) ✓ 5) aceite da intenção preservado, com uma divergência explícita de exemplo do
|
||||
aceite (scripts/tests/AGENTS contam como produção por `.dockerignore` —
|
||||
conservador, alinhado ao anti-goal) ✓ — 5/5.
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
# CI do main em janela de 30 min + matar o agent-pool
|
||||
|
||||
Status: rascunho
|
||||
Status: entregue
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #64
|
||||
Priority: P0
|
||||
|
|
|
|||
72
docs/plans/ops69-admin-branco-importmap-s3.md
Normal file
72
docs/plans/ops69-admin-branco-importmap-s3.md
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
# Admin do Payload abre em branco em produção (importMap sem o handler do storage S3)
|
||||
|
||||
Status: aguardando execução (blocked)
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #77
|
||||
Priority: P0
|
||||
Model: composer-2.5
|
||||
Impeccable: A — sem mudança de UI (corrige regressão que deixa o admin em branco)
|
||||
Rascunho UI: N/A — sem UI nova
|
||||
Appetite: ~0,25–0,5 dia eng; um outcome verificável (login do admin renderiza em prod)
|
||||
Responsável: —
|
||||
|
||||
## Intenção
|
||||
|
||||
O admin do Payload (`/admin`) está **em branco em produção** (jorgesolla1313.com.br): a página carrega (HTML 200, chunks 200, `/api/users/me` 200), o shell do app hidrata, mas o formulário de login nunca renderiza — nada aparece. Isso trava o time editorial e de campanha: sem admin não há CMS, não há gestão de conteúdo, não há import/export de contatos.
|
||||
|
||||
**Diagnóstico verificado (evidência abaixo):** a causa raiz é o `importMap` commitado (`src/app/(payload)/admin/importMap.js`) **sem** a entrada `@payloadcms/storage-s3/client#S3ClientUploadHandler`. O plugin `s3Storage` (OPS52) é ativado só quando as envs `S3_*` estão presentes — em produção elas estão, então o admin precisa resolver o handler do upload do `media` via importMap, e a entrada não existe → o admin falha ao montar a view. Em dev/test as `S3_*` não existem → plugin desligado → importMap consistente → admin funciona. É a divergência dev/prod exata.
|
||||
|
||||
O erro reportado no console ("Cross-Origin Request Blocked" + SRI mismatch do `beacon.min.js` do Cloudflare) é **ruído, não causa**: o hash `sha512` declarado no HTML bate com o arquivo real servido (verificado), e o "computed hash" de conteúdo vazio no erro do usuário indica apenas que o fetch do beacon foi bloqueado no browser dele. Bloquear o beacon não muda nada no admin. Não seguir por esse caminho.
|
||||
|
||||
## Persona e fluxo
|
||||
|
||||
- **Persona / contexto:** time editorial/campanha (staff com acesso ao `/admin`); hoje está parado — abriu o admin, página branca, sem erro aparente.
|
||||
- **Job principal:** entrar no `/admin` e fazer login.
|
||||
- **Fluxo desejado:** abrir `jorgesolla1313.com.br/admin` → redirecionar para `/admin/login` → formulário de login visível → logar e usar o CMS normalmente.
|
||||
- **Anti-goals de produto:** não é para redesenhar o admin, nem mudar o storage de media, nem mexer no contrato `/api/media/file/...`; é restaurar o comportamento que existia.
|
||||
|
||||
## Objetivo e aceite
|
||||
|
||||
- `/admin` e `/admin/login` renderizam o formulário de login em produção (não página branca), sem erros no console do browser.
|
||||
- Login no admin funciona de ponta a ponta em prod (autenticar e abrir uma collection/global).
|
||||
- O upload de media continua funcionando (Garage S3) — o fix não pode quebrar o fluxo OPS52.
|
||||
- O importMap commitado volta a ser consistente com o config ativado por envs de produção.
|
||||
- Dev/test continuam funcionando sem as envs `S3_*` (storage local, como hoje).
|
||||
|
||||
## Dados (intenção)
|
||||
|
||||
- **Vou apresentar dados?** Não — item de infra/regressão, sem superfície de dados.
|
||||
- **Decisões desbloqueadas:** nenhuma de produto; decisão de engenharia (ver Questões em aberto).
|
||||
|
||||
## Direção no codebase (hipótese)
|
||||
|
||||
- **Áreas prováveis:** `src/app/(payload)/admin/importMap.js` (arquivo gerado, commitado), `src/payload.config.ts` (plugin `s3Storage` condicional, linhas ~150–172), `src/utilities/mediaStorage.ts` (resolução das envs `S3_*`), `src/collections/Media.ts` (upload), `package.json` (`pnpm generate:importmap`).
|
||||
- **Precedente a olhar:** commit `dabc00f4` (OPS52 — trocou vercel-blob por s3 e regenerou o importMap **sem** as envs S3, removendo o handler do blob e não adicionando o do S3); o e2e do admin (`tests/e2e/admin.e2e.spec.ts`) não pega isso porque roda sem `S3_*` (mesma divergência dev/prod).
|
||||
- **Risco de acoplamento:** o importMap é regenerado inteiro por `pnpm generate:importmap` — regenerar com envs S3 altera só as entradas do storage (verificado: +2 linhas do `S3ClientUploadHandler`); não deve tocar nas entradas existentes do lexical/import-export.
|
||||
|
||||
## Dependências
|
||||
|
||||
- Soft: OPS52 (introduziu a regressão — contexto, não blocker).
|
||||
|
||||
## Fora de escopo
|
||||
|
||||
- Seguir o erro do beacon do Cloudflare (`static.cloudflareinsights.com`) — é ruído de console; registrar como nota para a equipe, não como trabalho.
|
||||
- Mudar o storage de media (S3→outro), o contrato de URL `/api/media/file/...`, ou o comportamento do plugin em dev/test.
|
||||
- Melhorias de build/deploy fora do fix mínimo (guard no CI pode entrar como item sucessor — ver Questões).
|
||||
|
||||
## Rabbit holes de produto
|
||||
|
||||
- **"Já que vou mexer no importMap, aproveito e atualizo tudo".** Regenerar sem envs de produção corretas introduz a MESMA classe de bug de novo. **Corte neste item:** regenerar com as envs S3 setadas (mesmo as de teste apontando para localhost/garage de teste), conferir o diff (só storage), e não tocar em mais nada.
|
||||
- **"O erro do beacon deve ser o problema, vamos mexer no Cloudflare".** Caminho morto: o beacon não bloqueia o admin (evidência: admin branco também via origem direta, sem Cloudflare no meio). **Corte:** registrar como ruído e focar no importMap.
|
||||
|
||||
## Questões em aberto (produto)
|
||||
|
||||
- **Como impedir que a divergência dev/prod volte a acontecer?** **Opções:** A) só regenerar e commitear o importMap (mínimo, risco de regressão futura quando um plugin condicional mudar de novo); B) regenerar + nota/documentação no `local-database` ou no AGENTS.md dizendo que `generate:importmap` precisa das envs de produção quando o config for condicional; C) regenerar + guard de CI (ex.: rodar `generate:importmap` com envs S3 de teste e falhar o gate se o arquivo commitado divergir). **Recomendação:** A agora (fix do incidente, mínimo e verificado) + **C como item sucessor** (evidência de que CI/e2e não pegam essa classe de bug — vale um guard, mas não bloqueia o P0). _(assumido — validar com produto)_
|
||||
- **Prioridade P0 confirmada?** **Recomendação:** sim — admin é a ferramenta central do time; cada dia em branco é dia sem CMS. _(assumido — validar com produto)_
|
||||
|
||||
## Referências
|
||||
|
||||
- GitHub Issue #77
|
||||
- Rascunho UI (gate): N/A
|
||||
- `src/payload.config.ts` (plugin condicional `s3Storage`), `src/app/(payload)/admin/importMap.js` (entrada ausente), `src/utilities/mediaStorage.ts`, commit `dabc00f4` (OPS52), `tests/e2e/admin.e2e.spec.ts` (por que CI não pega)
|
||||
- Evidência: logs do container prod (`getFromImportMap: PayloadComponent not found in importMap` para `@payloadcms/storage-s3/client#S3ClientUploadHandler`); reprodução local (admin branco com `S3_*` setadas + importMap atual; admin renderiza após regenerar o importMap com as envs e reverter o arquivo)
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
# Impl: S6-FOLLOWUP — CLI Playwright ignora filtros; `test:e2e:affected` roda a suíte completa
|
||||
|
||||
Status: em execução
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #58 (S6-FOLLOWUP, depends S6)
|
||||
Intenção: docs/plans/s6-followup-playwright-filtros-cli-ignorados.md
|
||||
Appetite restante: ~0,5 dia (herdado)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** `pnpm test:e2e:affected` roda SÓ os specs afetados (contagem verificada); comandos de iteração locais documentados e funcionando.
|
||||
- **O que NÃO negociar:** não mudar specs, CI (`--shard` ok), `gate:ci` nem trocar de runner.
|
||||
- **O que reavaliar:** a hipótese de mecanismo do plano de intenção está **errada** — evidência empírica nova desta sessão (mesmo binário 1.58.2, config real e config mínima):
|
||||
|
||||
| Invocação (config REAL do repo) | Resultado medido |
|
||||
| ------------------------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| `--list admin` / `--list frontend` / `--list campaign` | 180 / 177 / 162 (frontend 15 + closure campaign 160 + setup 2; admin 180 = suíte toda) |
|
||||
| `--list campaignHomeActions` | 20 (arquivo 18 + setup 2) |
|
||||
| `--list pwa` | 3 (campaign-pwa 1 + setup 2) |
|
||||
| `--list seedParity` | 1 (arquivo, sem setup) |
|
||||
| `--list zzz_nonexistente` | 0 ("No tests found" — filtro aplicado) |
|
||||
| `--list frontend --no-deps` (dev) | **15** (só o arquivo!) |
|
||||
| `CI=1 --list frontend` (prod mode) | **15** (só o arquivo!) |
|
||||
|
||||
- **Causa raiz (não é o parse de args):** o commander entrega os posicionais corretamente (`POSITIONALS: ['admin']` — probe) e o matcher de arquivo funciona (probe via `RegExp.prototype.test`: `/frontend/gi` casa só `frontend.e2e.spec.ts`). O que arrasta a suíte é o **closure de dependências entre projects no dev mode** (`setup ← campaign ← frontend ← admin` em `playwright.config.ts`): `collectProjectsAndTestFiles` filtra os arquivos por project, mas `buildProjectsClosure` repõe TODOS os arquivos de cada project-dependência. Filtrar um spec do `frontend` puxa `campaign` (160) + `setup` (2) — 177 no total com o próprio arquivo (15); filtrar `admin` puxa a suíte inteira. Em prod mode (`CI=1`/`E2E_PROD=1`) os projects não têm `dependencies` → filtro funciona (é por isso que o CI selecionado funciona).
|
||||
- **`-g` e `--list` NÃO estão quebrados** (evidência do plano desatualizada): `-g alpha` filtra por título (verificado em config mínima); `--list` respeita posicionais e `-g` (verificado: `zzz` → 0). A "quebra" era o closure arrastando o resto. Sem pin/upgrade upstream necessário.
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A[run-e2e-affected.mjs] --> B[buildPlaywrightE2eArgs<br/>scripts/lib/playwright-e2e-args.mjs]
|
||||
B --> C[test:e2e --no-deps<br/>flags antes do --<br/>-- paths posicionais]
|
||||
C --> D[playwright 1.58.2 dev mode<br/>closure desligado]
|
||||
D --> E[só os specs afetados rodam]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A (inserir `--` antes dos paths — a correção do plano) | B (`--no-deps` + `--` + correção do passthrough; builder puro em `scripts/lib/` com unit test) | C (forçar prod mode `CI=1` no local) | D (remover `dependencies` do config dev)
|
||||
|
||||
**Recomendação: B** — ataca a causa real (closure) com o mecanismo oficial do playwright (`--no-deps`, exatamente o workaround que o plano já apontava), mantém a cadeia de prewarm do dev mode para a suíte completa, e segue o padrão do repo (lógica pura derivada em `scripts/lib/` unit-testada, como `test-affected-core.mjs`).
|
||||
|
||||
**Rejeitadas:**
|
||||
|
||||
- **A** — o `--` não muda nada no config real: commander já parseia posicionais sem `--`; a evidência do plano (11 testes com `--`) foi medida em config mínima. Só `--` não corrige o sintoma de 173 testes.
|
||||
- **C** — `CI=1` muda `webServer` para `pnpm start` (exige build), `forbidOnly`, `retries` e o budget do servidor; é uma semântica de ambiente diferente, não um filtro.
|
||||
- **D** — remove a garantia de ordenação de cold-compile do dev mode (comentário OPS34 no config); afeta a suíte completa dev, não só seleção.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **`buildPlaywrightE2eArgs` + `parsePassthroughArgs`** (`scripts/lib/playwright-e2e-args.mjs`, novo): puros e síncronos. `parsePassthroughArgs(argv)` remove só um `--` líder (pnpm já consumiu o dele; invocação direta pode deixar um) e repassa o resto **verbatim** — valores de flag como `-g grade` não são reclassificados. `buildPlaywrightE2eArgs({ scopeSpecPaths, passthroughArgs })` → `['test:e2e', ...passthroughArgs]` + `--no-deps` quando o run é filtrado (paths de escopo, positional no passthrough ou flag de filtro `--project`/`-g`/`--grep`/`--grep-invert`) + `-- <scopeSpecPaths>` quando há paths de escopo. `--no-deps` condicional: suíte completa mantém a cadeia OPS34.
|
||||
- **`run-e2e-affected.mjs`**: (1) corrige o parse do passthrough — hoje `pnpm test:e2e:affected -- tests/x.spec.ts` perde o path (pnpm consome o `--`, argv fica sem `--` e `passthroughIndex === -1` → args descartados); novo contrato via `parsePassthroughArgs`. (2) usa o builder (remove o loop manual de paths).
|
||||
- **`tests/unit/playwrightE2eArgs.unit.spec.ts`** (novo): pina o parse (invocação nua, pnpm `--`, `--` direto, flags+valores) e a forma dos args — `--no-deps` só em runs filtrados (path de escopo, positional ou flag de filtro), flags de runner (`--shard`, `--reporter`) preservam a cadeia, sem duplicar `--no-deps` explícito.
|
||||
- **`test-affected-core.mjs`**: `scripts/run-e2e-affected.mjs` entra em `HIGH_RISK_EXACT` (+ invariant em `ciSkipInvariants.unit.spec.ts`) — é o espelho local do job e2e; um PR só de runner hoje escaparia do e2e (mode `none`).
|
||||
- **Migration:** sem migration (nenhum schema/collection).
|
||||
- **Access / Consent:** nenhum.
|
||||
- **UI:** nenhuma.
|
||||
|
||||
### Dados → forma
|
||||
|
||||
N/A (sem dados novos).
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Tracer (builder + wiring)** — criar `scripts/lib/playwright-e2e-args.mjs`, unit spec, ligar em `run-e2e-affected.mjs`. Verificação: unit green; forma final confirmada com `--list` direto no binário do repo (já medida: `--no-deps` → 15/18).
|
||||
2. **Docs** — comentário em `playwright.config.ts` (mecanismo do closure no dev mode + receitas de filtro: path posicional exige `--no-deps`; `--project=<família> --no-deps`; `-g`/`--list` funcionam, mas o closure arrasta dependências); header do `run-e2e-affected.mjs` (contrato de invocação corrigido); bullet curto em `AGENTS.md` (seção OPS59/test:e2e:affected); `docs/changelog/2026-08-18-s6-followup.md` + `pnpm changelog:build`.
|
||||
3. **Gates** — `pnpm gate:fast` (lint, typecheck, test:unit); CI do PR roda e2e completo (o diff toca `playwright.config.ts` e `scripts/run-e2e-affected.mjs` — ambos em `HIGH_RISK_EXACT`; o runner entrou no set nesta entrega).
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- **Não investigar o hang do `pnpm test:e2e` neste worktree** (invocação via pnpm congela após a fase de install do pnpm; o binário direto com a mesma `NODE_OPTIONS` funciona e é o veículo de verificação local — pré-existente, ambiente, não o bug). Verificação de contagem local via binário direto + unit; CI é o verifier.
|
||||
- Não reescrever o parse do commander do playwright, não fazer pin/upgrade de versão (`-g`/`--list` funcionam; evidenciado).
|
||||
- Não tocar `.forgejo/workflows/*` nem `gate-ci.mjs`.
|
||||
- Não "consertar" a evidência do plano de intenção retroativamente (a tabela do plano fica como está — docs histórica; o impl plan registra a divergência).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Dev mode sem prewarm do setup em runs selecionados** (o `--no-deps` pula o spec de setup): cold-compile mais lento do primeiro spec em máquina carregada. Mitigação: prod mode (CI) já roda sem prewarm e é o caminho gateado; budget de 60s/240s do webServer permanece.
|
||||
- **Flag com valor separado por espaço no passthrough** (`-g grade`): resolvido na implementação — passthrough verbatim (sem reclassificação flag/posicional); `-g grade` chega intacto ao playwright. Só sobra o caso do usuário passar um `--` interior explícito junto com paths de escopo gerados (o `--no-deps`/`--` gerados caem depois do `--` do usuário e viram padrão de arquivo → "No tests found", falha ruidosa; pnpm nunca produz isso).
|
||||
- **Regression na suíte completa dev**: o `--no-deps` só entra nos args gerados pelo builder; `pnpm test:e2e` puro (sem args) não muda — a cadeia de deps dev permanece intacta.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto: `run-e2e-affected` roda só os specs afetados (unit + `--list` do binário com a forma final); comandos de iteração documentados; `--project=<família> --no-deps` documentado como receita manual.
|
||||
- [ ] Invariantes AGENTS/engineering-standards: script puro em `scripts/lib/` (padrão test-affected-core); sem tocar CI/gate:ci/specs; identificadores em inglês, copy pt-BR.
|
||||
- [ ] Testes de domínio previstos: unit do builder (args), nada de access/write path muda.
|
||||
119
docs/plans/secao-conteudos-home-instagram-impl.md
Normal file
119
docs/plans/secao-conteudos-home-instagram-impl.md
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
# Impl: S3 — Seção de conteúdos na home de campanha — Instagram
|
||||
|
||||
Status: aprovado
|
||||
Atualizado em: 2026-08-18
|
||||
Issue: #20
|
||||
Intenção: docs/plans/secao-conteudos-home-instagram.md
|
||||
Appetite restante: ~1–2 dias eng (herdado)
|
||||
|
||||
## Leitura da intenção
|
||||
|
||||
- **Outcome:** a seção "Acompanhe de perto" (S1 artigos + S2 YouTube) passa a incluir os posts recentes do Instagram oficial (`@depjorgesolla`) via leitura servidor-side da Instagram Graph API (token long-lived com refresh, perfil Business/Creator) com cache — cards 1:1 com badge "Instagram", legenda (título) e data; clique abre o post **na plataforma** (nova aba, `noopener`); **exclusão por item é o requisito nº 1** (posts de grade que não são conteúdo real de campanha) e a interface de exclusão (admin vê os últimos posts com thumbnail + marca "não exibir") é parte desta fatia; fail-closed com último snapshot; sem credencial IG → cards IG simplesmente não aparecem (a seção vive com artigos + YouTube); kill switch `enabled` vale para o board como um todo; mobile segue o carrossel 1/tela.
|
||||
- **O que NÃO negociar:** sem embed/script do Instagram no load (LCP); nenhuma chave no cliente; clique na plataforma (sem lightbox); exclusão por item (o bento pula para o próximo elegível); fail-closed silencioso; zero mudança em schema de conteúdo público (migrações não destrutivas no máximo); convenções do repo (identificadores em inglês, admin em pt, cache por tag).
|
||||
- **O que reavaliar:** a S2 já entregou quase toda a mecânica — global `SocialFeedSettings` com `excludedItems` já tipado para `instagram`, loader irmão com snapshot persistido via SQL direto, card generalizado com `external`, merge por recência na seção. A S3 **não duplica** nada disso: estende a global (campos IG + snapshot IG + picker de exclusão), cria o loader irmão `instagramFeed.ts` e o **picker de exclusão no admin** (única superfície nova de verdade). O rascunho UI aprovado desenha o card IG **1:1** (`aspect-square`) — o `CampaignContentCard` atual é `aspect-video` hardcoded → o card ganha variante de capa (Decisão 3). O plano-site §4.2 já nomeia a config (token + user ID na global `SocialFeedSettings`) e o "refresh automático ~60 dias" (Decisão 2).
|
||||
|
||||
## Abordagem recomendada
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S[CampaignContentSection<br/>server] --> P[getVisiblePosts<br/>tag posts]
|
||||
S --> Y[getYouTubeFeed<br/>tag social-feed]
|
||||
S --> I[getInstagramFeed<br/>tag social-feed<br/>revalidate 300]
|
||||
I --> G[global social-feed-settings<br/>admin-only read]
|
||||
I --> F[fetch Graph API<br/>user + media]
|
||||
F -->|200| W[(snapshot IG<br/>gravado no global)]
|
||||
F -->|falha token| R[refresh + retry 1x]
|
||||
R -->|novo token| F
|
||||
R -->|falha| SNAP[(lê snapshot IG<br/>se existir)]
|
||||
I -->|null sem config| N[(sem cards IG)]
|
||||
I -->|pós-exclusão| M[merge por recência<br/>artigos + YT + IG]
|
||||
M --> B[Bento desktop<br/>1 grande + 4 pequenos]
|
||||
M --> C[CampaignContentCarousel<br/>client · <md]
|
||||
B --> CARD[CampaignContentCard<br/>coverAspect square p/ IG]
|
||||
C --> CARD
|
||||
G -.picker admin.-> X[InstagramPostExclusionPicker<br/>marca excludedItems]
|
||||
```
|
||||
|
||||
**Opções consideradas:** A | B | C
|
||||
**Recomendação:** A — um loader irmão `getInstagramFeed()` em `src/utilities/instagramFeed.ts` (mesmo esqueleto do `youtubeFeed.ts`: parsers/format puros + fetch da Graph API + `unstable_cache` tag `social-feed` + `revalidate: 300` + snapshot cru persistido por SQL direto, exclusões aplicadas na leitura), campos IG na global existente `social-feed-settings` (sem global nova), card IG com `coverAspect: 'square'` (1:1 do rascunho), e o picker de exclusão como **primeiro componente custom do admin do repo** (`src/components/admin/InstagramPostExclusionPicker.tsx`, client, attach num campo `ui` da global — lista os posts do snapshot com toggle que escreve em `excludedItems`).
|
||||
**Rejeitadas:** B) global/loader separado por plataforma (`instagramSettings` própria) — viola o plano-site §4.2 que nomeia UMA global `SocialFeedSettings` e espalha o mecanismo de exclusão que a S2 já unificou; C) embed de feed do Instagram (script da plataforma) — proibido pelo plano-site §4.2 (LCP do mobile) e pela intenção.
|
||||
|
||||
### Componentes / mudanças
|
||||
|
||||
- **Global `SocialFeedSettings`** (`src/globals/SocialFeedSettings.ts`, estender): `instagramEnabled` (checkbox "Instagram ativo", default true), `instagramAccessToken` (text "Token de acesso (Instagram Graph API)", admin.description com nota do tipo de token + refresh), `instagramUserId` (text "ID do usuário (conta Business/Creator)"), `instagramMaxItems` (number "Máximo de posts", default 3, min 1, max 5), `instagramFeedSnapshot` (json, `admin.hidden: true`), `instagramExclusionPicker` (campo `ui` com `admin.components.Field` → picker client; sem valor persistido). `excludedItems` já cobre `platform: 'instagram'` — sem migration para o mecanismo de exclusão. **Migration:** `pnpm migrate:create add_instagram_social_feed_fields` (ALTER TABLE ADD COLUMN, não destrutiva; revisar o DDL gerado — o `migrate:create` da S2 regenerou drift de migrations hand-written sem sidecar JSON, a S2 editou o arquivo para conter só o DDL da feature).
|
||||
- **`src/utilities/instagramFeed.ts`** (novo, `server-only`): `InstagramPost` (`{ id, caption: string | null, mediaType, permalink, thumbnailUrl?, timestamp }`); puros exportados p/ unit: `parseInstagramMediaResponse` (item sem `permalink` é dropado — não dá para abrir na plataforma; `caption` null é mantido — post de grade não tem legenda e deve aparecer para exclusão manual; carrossel resolve thumbnail do primeiro `children`), `pickInstagramThumbnail` (IMAGE → `media_url`; VIDEO/REEL → `thumbnail_url`; CAROUSEL_ALBUM → 1º child com `media_url ?? thumbnail_url`; sem thumbnail → undefined e o card renderiza sem capa — já suportado), `eligibleInstagramPosts(posts, excludedIds, maxItems)`, `loadInstagramFeed({ accessToken, userId, maxResults, fetchImpl, baseUrl })` — `GET /{ig-user-id}/media?fields=id,caption,media_type,media_url,permalink,thumbnail_url,timestamp,children{media_url,thumbnail_url}&limit&access_token` + `GET /{ig-user-id}?fields=username`; em falha de autenticação tenta **refresh + retry 1x** (Decisão 2) e retorna `{ posts, username, refreshedAccessToken? }`; throw em não-2xx/rede/JSON inválido; `baseUrl` default `https://graph.instagram.com`, override `INSTAGRAM_API_BASE_URL`. `getInstagramFeed()` = `unstable_cache` tag `['social-feed']` + `revalidate: 300` — lê a global (Local API), `null` quando desconfigurado/desligado, grava `instagramFeedSnapshot` (`{ username, posts }` cru, pré-exclusão) em 200, persiste token renovado via SQL direto (mesmo padrão do snapshot da S2), lê o snapshot + aplica exclusões quando o fetch falha; sem snapshot → `{ username: null, posts: [] }`.
|
||||
- **`CampaignContentCard`** (`src/components/CampaignContentCard.tsx`, estender): `CampaignContentCardData` ganha `coverAspect?: 'video' | 'square'` (default `'video'` — S1/S2 intactos); IG passa `coverAspect: 'square'` (1:1 do rascunho); nada mais muda.
|
||||
- **`CampaignContentSection`**: mescla `getVisiblePosts()` + `getYouTubeFeed()` + `getInstagramFeed()` por recência, fatia 5, `[featured, ...rest]`; card IG: badge "Instagram", título = `caption` (fallback "Publicação no Instagram" quando null — post de grade sem legenda precisa aparecer para exclusão manual), meta = `formatRelativePostDate(timestamp)` (só data — o rascunho não mostra contador para IG), `external: true`, href = `permalink` da API; link do header "Seguir no Instagram →" (`https://www.instagram.com/<username>`, nova aba) renderizado quando o feed retorna `username` — com API fora e sem snapshot o link some junto com os cards (username é derivado da API, não configurado — Decisão 5).
|
||||
- **`src/components/admin/InstagramPostExclusionPicker.tsx`** (novo, `'use client'`): lista os posts do `instagramFeedSnapshot` (lido via `useAllFormFields`) com thumbnail (`<img>` — admin não passa pelo optimizer), legenda truncada, data relativa e toggle "Não exibir" que adiciona/remove `{ platform: 'instagram', itemId: id, reason? }` em `excludedItems` (via `useField({ path: 'excludedItems' })` + `setModified(true)`); estado vazio honesto ("Nenhum post recente — configure o token e o ID; os posts aparecem aqui após a primeira sincronização"); razão como campo de texto inline opcional. Registrado no importmap (`pnpm generate:importmap` — primeiro componente custom do repo).
|
||||
- **`next.config.mjs`**: `images.remotePatterns` ganha `https://*.cdninstagram.com/**` (URLs de mídia da Graph API; o pattern `localhost/thumbs` da S2 já cobre o stub).
|
||||
- **`playwright.config.ts`**: `webServer` ganha mais um entry — `tests/e2e/instagram-stub.mjs` (porta = dev + 2000; ver Decisão 6) + env `INSTAGRAM_API_BASE_URL` no entry do dev server.
|
||||
- **`tests/helpers/youtubeStub.ts` → `tests/helpers/socialStub.ts`** (rename + extensão): `youtubeStubUrlFor(baseURL)` (+1000) e `instagramStubUrlFor(baseURL)` (+2000) — a derivação da porta continua tendo UMA spelling (a S2 registrou o "+1000 único" como P2 absorvido; com duas plataformas o módulo é o dono, não um twin).
|
||||
- **Migration:** `add_instagram_social_feed_fields` (não destrutiva). **Access/Consent:** nenhum consent (metadados públicos de fonte externa, como posts/YouTube); global permanece read/update admin-only (token nunca vaza via REST).
|
||||
- **UI:** Impeccable B — estende a seção S1/S2 com cards IG (mesma estrutura, badge "Instagram"); shape → craft → critique → polish no navegador (desktop + 390px).
|
||||
|
||||
### Dados → forma (se aplicável)
|
||||
|
||||
- Forma: **nada derivado da campanha** (restrição da intenção) — legenda (título), data relativa (`formatRelativePostDate`, paridade S1/S2) e thumbnail 1:1; sem contadores (IG não entrega views de graça no media edge; o rascunho não mostra). Rejeitadas: `media_url` do vídeo/reel como capa (entrega o arquivo mp4 ao optimizer — thumbnail_url é o formato certo), contagem de likes via extra endpoint (métrica inventada / custo de API sem aceite).
|
||||
|
||||
## Decisões de engenharia
|
||||
|
||||
1. **Loader irmão do youtubeFeed.**
|
||||
Opções: A) `src/utilities/instagramFeed.ts` espelhando `youtubeFeed.ts` (puros + fetch + cache + snapshot) | B) generalizar um `socialFeed.ts` único com adapter por plataforma | C) fetch inline no componente.
|
||||
Recomendação: A — as duas APIs têm contratos diferentes o bastante (URLs, campos, thumbnails, refresh) que um adapter único viraria camada de indireção sem volatilidade real (rabbit hole Teqo); o "irmão" é o precedente declarado pela S2 ("loader irmão de posts.ts"). O conhecimento compartilhado (exclusão, snapshot, kill switch) já está na global + nos helpers, não precisa de classe.
|
||||
Alternativas rejeitadas: B indireção sem call sites suficientes; C quebra cache/fail-closed e mistura fetch na UI.
|
||||
|
||||
2. **Refresh de token automático.**
|
||||
Opções: A) refresh-on-failure: no erro de autenticação do `/media`, uma chamada `GET /refresh_access_token?grant_type=ig_refresh_token&access_token=…`, persiste o token renovado (SQL direto, padrão snapshot) e retry 1x | B) refresh a cada fetch bem-sucedido (token sempre jovem) | C) sem refresh — rotação manual do admin.
|
||||
Recomendação: A — satisfaz "token long-lived com refresh automático ~60 dias" do plano-site sem painel de OAuth (corte do rabbit hole da intenção) e sem custo por miss; a falha de refresh cai no fail-closed (snapshot) intacto. Nota honesta no campo do admin: o refresh endpoint da Graph API só renova tokens emitidos via **Instagram Login** (não os page tokens de Facebook Login) — para token business, o refresh falha → snapshot + rotação manual (documentado; setup da Meta é da assessoria, fora do escopo).
|
||||
Alternativas rejeitadas: B dobra chamadas + 1 write de DB por miss (5 min) sem ganho de correção (o refresh-on-failure cobre o caso real: token expirou); C contradiz o plano-site.
|
||||
|
||||
3. **Formato do card IG (1:1).**
|
||||
Opções: A) `coverAspect?: 'video' | 'square'` no `CampaignContentCardData` (default `'video'`) | B) card IG sempre 16:9 (uniformidade com YT) | C) componente de card separado para IG.
|
||||
Recomendação: A — o rascunho UI aprovado desenha o IG 1:1 (`aspect-square`, "post 1:1"); o default `'video'` preserva S1/S2 byte a byte; um campo opcional no data é mais barato que um segundo card (aceite da S1: card único por fonte). O grande do bento pode cair num IG (merge por recência) — um quadrado no slot grande é o desenho do rascunho, sem regra especial.
|
||||
Alternativas rejeitadas: B trai o rascunho aprovado; C duplica o card (viola o aceite da S1).
|
||||
|
||||
4. **Picker de exclusão no admin (requisito nº 1 da intenção).**
|
||||
Opções: A) campo `ui` na global com componente client custom (lista do snapshot + toggle em `excludedItems`) | B) manter o array `excludedItems` cru (admin copia/cola IDs) | C) campo por plataforma (`instagramExcludedIds`) com picker próprio.
|
||||
Recomendação: A — a intenção decide explicitamente "o admin vê a lista dos últimos posts (thumbnail + ID) e marca os que não devem aparecer; a interface de exclusão é parte desta fatia" (marcar por ID puro é inviável para a assessoria); o snapshot já é persistido pelo loader (a S2 deixou o mecanismo pronto — `excludedItems` já tem `platform: 'instagram'`), então o picker é leitura do snapshot + escrita no array, sem migration e sem endpoint novo.
|
||||
Alternativas rejeitadas: B falha o aceite; C espalha o mecanismo que a S2 unificou e força migration.
|
||||
→ Risco: é o primeiro `admin.components` do repo; se `type: 'ui'` não suportar `admin.components.Field` nesta versão (3.82), fallback documentado: campo `json` `admin.hidden: false` com o mesmo componente attachado — verificar no Riscos.
|
||||
|
||||
5. **Link do header "Seguir no Instagram →".**
|
||||
Opções: A) derivar o username da API (`GET /{ig-user-id}?fields=username`, 1 chamada por miss, cacheado) e renderizar o link só quando o feed devolve username | B) campo `instagramUsername` na config | C) sem link de perfil até a S4.
|
||||
Recomendação: A — o rascunho UI E o wireframe usam exatamente "Seguir no Instagram →" (copy aprovada; nota: a S2 usou "YouTube →" curto — o IG segue a copy do rascunho, divergência de copy documentada); derivar o username evita mais um campo que a assessoria preenche; com API fora e sem snapshot o link some junto com os cards (sem username não há URL honesta — divergência menor do comportamento da S2, onde o link "YouTube →" sobrevive à falha porque o channelId é configurado).
|
||||
Alternativas rejeitadas: B campo redundante com o dado que a API entrega; C deixa o perfil sem porta de entrada quando os cards somem (anti-goal).
|
||||
|
||||
6. **Test seam do fetch IG.**
|
||||
Opções: A) stub HTTP node irmão (`tests/e2e/instagram-stub.mjs`, porta dev+2000) + `INSTAGRAM_API_BASE_URL` no webServer + `fetchImpl` nas units | B) generalizar o stub da S2 num processo único multi-plataforma | C) interceptação do Playwright no browser.
|
||||
Recomendação: A — espelha o precedente aprovado da S2 (stub node sem dependências: `/media`, `/user`, `/__stub/health`, `/__stub/state` ok|fail, thumbnails locais em `/thumbs/<id>.jpg` já cobertas pelo remotePattern localhost); o offset +2000 não colide com o +1000 do YouTube nem com dev servers (3100–4099).
|
||||
Alternativas rejeitadas: B acopla as fixtures das duas plataformas num processo só sem ganho; C não alcança fetch server-side (mesma lição da S2).
|
||||
→ A derivação da porta vive UMA vez: `tests/helpers/socialStub.ts` (rename de `youtubeStub.ts`, Decisão 7 da S2 mantida).
|
||||
|
||||
## Fases verificáveis
|
||||
|
||||
1. **Schema + loader** (~metade do appetite): campos IG na global + `pnpm migrate:create add_instagram_social_feed_fields` (revisar DDL gerado — precedente S2 de drift) + `pnpm migrate` local + `pnpm generate:types`; `instagramFeed.ts` (puros + fetch + refresh + cache + snapshot); unit tests (`parseInstagramMediaResponse` com caption null/carrossel/item sem permalink, `pickInstagramThumbnail` por media_type, `eligibleInstagramPosts`, `loadInstagramFeed` com `fetchImpl` fake cobrindo ok/falha/malformado/refresh-retry). Gates parciais: tsc + unit.
|
||||
2. **UI + admin picker** (restante): `coverAspect` no card; merge IG na seção + link "Seguir no Instagram →"; `next.config` (`*.cdninstagram.com`); `InstagramPostExclusionPicker` + importmap; estender o spec de convenções (pin `instagramFeed.ts`). Verificação manual no admin (a global com snapshot mostra o picker; toggle grava `excludedItems`).
|
||||
3. **e2e + gates finais**: stub IG + helper de porta (`socialStub.ts`) + webServer; no describe serial da seção: (a) full-state IG — settings + stub ok + 1 artigo + 4 posts (o mais novo EXCLUÍDO → o grande pula para o elegível), asserts: badge "Instagram", grande = post elegível mais recente com href = permalink + `target=_blank` + `rel=noopener`, meta "há X", título = legenda E fallback "Publicação no Instagram" no post sem legenda (post de grade entra no automático — aceite), excluído ausente, "Seguir no Instagram →" com href `instagram.com/<username>` + target blank, carrossel mobile 1/tela com IG; (b) fail-closed sem snapshot — stub fail → cards E link IG ausentes, seção viva com artigo; (c) snapshot — stub ok → cards; stub fail + settings edit (maxItems 2, snapshot omitido) → cards persistem re-filtrados; (d) kill switch — estender o teste existente com IG configurado (`enabled=false` → cards E link IG somem, artigos vivem); (e) smoke do picker no `admin.e2e.spec.ts` (abre a global, vê os posts do snapshot, marca um, salva, verifica `excludedItems` via REST). Cleanup: reset da global (incl. campos IG) + stub ok + revalidate + polling positivo (padrão S2). Polish no navegador (desktop + 390px). Gates: `pnpm gate:fast`, `pnpm test`, `pnpm build` local, e2e dev (`pnpm test:e2e:affected`? — e2e roda uma vez no CI; local opcional) + changelog `docs/changelog/2026-08-18-s3.md` + `pnpm changelog:build`; AGENTS.md (allowlist `social-feed` já documentada — ajustar a menção "YouTube" para o board YT+IG).
|
||||
|
||||
## Rabbit holes / Não escopo (engenharia)
|
||||
|
||||
- Não paginar o feed IG (1ª página basta; se o admin excluir mais que o headroom, o board mostra menos cards IG — documentado no campo `instagramMaxItems`).
|
||||
- Não buscar stories, DMs, estatísticas, hashtags, outras contas, mix por tag (pendência §5 do plano-site é decisão da assessoria — o corte é A + exclusão por item, já decidido na intenção).
|
||||
- Não tocar no bug #40 (validação do `itemId` com `data.platform` sempre undefined) — débito registrado da S2, fora do escopo; o picker escreve IDs válidos de qualquer forma.
|
||||
- Não criar global/endpoint/rota nova além do componente admin; sem lightbox/embed; sem player inline.
|
||||
- Não mudar a API de `getVisiblePosts` nem o merge da S2 (artigos+YT intactos quando IG off).
|
||||
|
||||
## Riscos e mitigação
|
||||
|
||||
- **Primeiro componente admin custom do repo.** `type: 'ui'` + `admin.components.Field` é o caminho canônico do Payload 3; se a versão 3.82 reclamar, fallback: campo `json` com o mesmo componente (o importmap é regenerado de qualquer forma — `pnpm generate:importmap`); validação cedo na fase 2 com o smoke e2e do admin.
|
||||
- **Token business vs IG Login (refresh).** O refresh endpoint só renova tokens de Instagram Login; para page token business, o refresh falha → snapshot (fail-closed) e o admin rotaciona manualmente — nota no `admin.description` do campo + risco anotado (setup Meta é da assessoria).
|
||||
- **CDN do Instagram no optimizer.** `scontent*.cdninstagram.com` é wildcard e pode trocar de host — remotePattern `https://*.cdninstagram.com/**` cobre os hosts atuais; se a Meta mudar o host, é 1 linha no `next.config` (anotado no campo admin não é necessário — risco de produção baixo, impacto visual limitado).
|
||||
- **e2e serial do describe cresce.** 4 testes novos + extensão do kill switch; orçamento 12s de polling (padrão S2) mantido; reset da global no beforeAll inclui os campos IG (senão o estado vazio deixa de ser determinístico).
|
||||
- **Escrever o token renovado em render.** 1 UPDATE por refresh (raro — só em falha de autenticação), SQL direto sem hooks (mesmo padrão/precondição do snapshot da S2).
|
||||
- **Home dependente de mais um fetch.** 2 chamadas IG por miss (user + media) ≈ 24/h no pior caso — folga enorme contra o rate limit de 200/h; cache `revalidate: 300` igual ao YT.
|
||||
|
||||
## Aceite de engenharia
|
||||
|
||||
- [ ] Aceite de produto da intenção ainda coberto (cards 1:1 com badge/legenda/data, clique na plataforma com noopener, exclusão por item com picker no admin, fail-closed com snapshot, kill switch, sem credencial → nada de IG, mobile 1/tela, link "Seguir no Instagram →")
|
||||
- [ ] Invariantes AGENTS/engineering-standards (migration não destrutiva; sem consent novo; identificadores em inglês; copy/admin em pt; cache por tag `social-feed`; access admin-only na config com segredo; revalidação via `afterChange` da global já cobre)
|
||||
- [ ] Testes de domínio previstos: unit (parsers, thumbnail por media_type, eligibility, fetch + refresh com fetchImpl) + e2e (full-state IG com exclusão e fallback de legenda, fail-closed sem snapshot, snapshot persistente, kill switch estendido, smoke do picker no admin)
|
||||
|
|
@ -10,9 +10,13 @@ const nextConfig = {
|
|||
remotePatterns: [
|
||||
new URL(`${allowedImageHost}/**`),
|
||||
// YouTube video thumbnails (campaign home content board, S2) come from
|
||||
// the platform's CDN — see `src/utilities/youtubeFeed.ts`.
|
||||
// the platform's CDN — see `src/utilities/socialFeed/youtubeFeed.ts`.
|
||||
new URL('https://i.ytimg.com/**'),
|
||||
// e2e-only: the YouTube stub (tests/e2e/youtube-stub.mjs) serves the
|
||||
// Instagram media thumbnails (campaign home content board, S3) come from
|
||||
// the Graph API's CDN (hosts vary per region) —
|
||||
// see `src/utilities/socialFeed/instagramFeed.ts`.
|
||||
new URL('https://*.cdninstagram.com/**'),
|
||||
// e2e-only: the YouTube/Instagram stubs (tests/e2e/*-stub.mjs) serve the
|
||||
// fixture thumbnails locally so specs never touch the real network.
|
||||
{ protocol: 'http', hostname: 'localhost', pathname: '/thumbs/**' },
|
||||
],
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
GOOGLE_CALENDAR_SERVICE_ACCOUNT_KEY_ENV_NAME,
|
||||
GOOGLE_CALENDAR_TEST_KEY,
|
||||
} from './tests/helpers/googleCalendarTestKey'
|
||||
import { youtubeStubUrlFor } from './tests/helpers/youtubeStub'
|
||||
import { instagramStubUrlFor, youtubeStubUrlFor } from './tests/helpers/socialStub'
|
||||
|
||||
/**
|
||||
* e2e tests boot a real dev server that seeds/deletes records, so they must run
|
||||
|
|
@ -28,14 +28,17 @@ assertTestDatabase(process.env.DATABASE_URL)
|
|||
const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:3000'
|
||||
const webServerPort = new URL(baseURL).port || (baseURL.startsWith('https:') ? '443' : '80')
|
||||
/*
|
||||
* Port of the YouTube Data API stub the content board (S2) fetches in e2e.
|
||||
* dev ports live in 3100..4099 (worktree slots, capped at 999), so +1000
|
||||
* never collides with another worktree's dev server; CI stays on 4000. The
|
||||
* derivation lives once in `tests/e2e/helpers/youtubeStub.ts` (the spec uses
|
||||
* it to flip the stub state).
|
||||
* Ports of the social-feed stubs the content board fetches in e2e (S2
|
||||
* YouTube, S3 Instagram). dev ports live in 3100..4099 (worktree slots,
|
||||
* capped at 999), so +1000 (YouTube) and +2000 (Instagram) never collide
|
||||
* with another worktree's dev server nor with each other; CI stays on 4000
|
||||
* and 5000. The derivation lives once in `tests/helpers/socialStub.ts` (the
|
||||
* spec uses it to flip the stub states).
|
||||
*/
|
||||
const youtubeStubUrl = youtubeStubUrlFor(baseURL)
|
||||
const youtubeStubPort = new URL(youtubeStubUrl).port
|
||||
const instagramStubUrl = instagramStubUrlFor(baseURL)
|
||||
const instagramStubPort = new URL(instagramStubUrl).port
|
||||
const workersOverride = process.env.PLAYWRIGHT_WORKERS
|
||||
const workers = workersOverride === undefined ? 2 : Number(workersOverride)
|
||||
if (!Number.isInteger(workers) || workers < 2) {
|
||||
|
|
@ -48,8 +51,9 @@ if (!Number.isInteger(workers) || workers < 2) {
|
|||
* compiles; against a production build they are pure cost — measured 2026-08-10
|
||||
* (OPS34): the 25 prewarm requests plus the 4-test frontend/admin tail behind
|
||||
* the ~30-file campaign family. Prod mode therefore drops the setup project and
|
||||
* the dependencies so all families run in parallel; CI shards the suite across
|
||||
* runners instead (ci.yml / ci-pr.yml pass `--shard`). Dev mode is unchanged.
|
||||
* the dependencies so all families run in parallel; CI runs the suite in one
|
||||
* process with `PLAYWRIGHT_WORKERS` (ci.yml / ci-pr.yml, OPS62 X1). Dev mode
|
||||
* is unchanged.
|
||||
* Note the chain is an ordering guarantee for dev cold compiles, not a data
|
||||
* dependency: specs are self-contained in both modes (fixtures + advisory
|
||||
* locks), so dropping it in prod cannot reorder shared fixtures.
|
||||
|
|
@ -94,6 +98,20 @@ export default defineConfig({
|
|||
*/
|
||||
timeout: 10_000,
|
||||
},
|
||||
/*
|
||||
* CLI filtering in dev mode (S6-FOLLOWUP, 2026-08-18): positional test paths
|
||||
* ARE parsed and matched per file, but the project dependency chain below
|
||||
* (setup -> campaign -> frontend -> admin, dev mode only) makes the runner
|
||||
* drag ALL files of every dependency project into a selected run
|
||||
* (buildProjectsClosure) — filtering to one frontend spec runs the whole
|
||||
* campaign family. Prod mode (CI / E2E_PROD=1) has no dependencies, so the
|
||||
* filter works as-is (the CI selected job relies on this). Local recipes:
|
||||
* pnpm test:e2e --no-deps -- tests/e2e/campaignHomeActions.e2e.spec.ts
|
||||
* pnpm test:e2e --no-deps --project=campaign
|
||||
* -g/--grep and --list DO work (title/file filters); pair them with
|
||||
* --no-deps/--project for deterministic runs. `pnpm test:e2e:affected`
|
||||
* generates the --no-deps form automatically.
|
||||
*/
|
||||
projects: [
|
||||
/*
|
||||
* `setup` prewarms shared Next route bundles against the dev server's cold
|
||||
|
|
@ -173,9 +191,11 @@ export default defineConfig({
|
|||
// Lets e2e specs bust the `posts` tag after direct REST deletes (cleanup),
|
||||
// mirroring the documented post-seed runbook against the deployed site.
|
||||
REVALIDATE_SECRET: process.env.REVALIDATE_SECRET ?? 'e2e-revalidate-secret',
|
||||
// The content board (S2) fetches the YouTube Data API through the local
|
||||
// stub below instead of the real network (deterministic fixtures).
|
||||
// The content board (S2/S3) fetches the YouTube Data API and the
|
||||
// Instagram Graph API through the local stubs below instead of the
|
||||
// real network (deterministic fixtures).
|
||||
YOUTUBE_API_BASE_URL: youtubeStubUrl,
|
||||
INSTAGRAM_API_BASE_URL: instagramStubUrl,
|
||||
},
|
||||
},
|
||||
{
|
||||
|
|
@ -188,5 +208,15 @@ export default defineConfig({
|
|||
YOUTUBE_STUB_PORT: String(youtubeStubPort),
|
||||
},
|
||||
},
|
||||
{
|
||||
/* Deterministic Instagram Graph API responses for the content board. */
|
||||
command: `node tests/e2e/instagram-stub.mjs`,
|
||||
reuseExistingServer: false,
|
||||
url: `${instagramStubUrl}/__stub/health`,
|
||||
timeout: 30_000,
|
||||
env: {
|
||||
INSTAGRAM_STUB_PORT: String(instagramStubPort),
|
||||
},
|
||||
},
|
||||
],
|
||||
})
|
||||
|
|
|
|||
155
scripts/ci-classify-production.mjs
Normal file
155
scripts/ci-classify-production.mjs
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* ci-classify-production — OPS65 production-change gate for the main CI
|
||||
* window. Classifies whether the merge head differs from the deployed
|
||||
* artifact in anything that would enter the docker build context.
|
||||
*
|
||||
* The `.dockerignore` is the source of truth (the Dockerfile does `COPY . .`):
|
||||
* a changed path is production when it is NOT excluded by the ignore
|
||||
* patterns. The gate is FAIL-OPEN toward production: dispatch (explicit
|
||||
* operator intent) and an unknown deployed SHA always run the full suite;
|
||||
* a classification ERROR (git/.dockerignore unreadable, no input) prints
|
||||
* production=true AND exits 1, so the workflow run turns red — the suite
|
||||
* still runs (fail-open) but the deploy never happens silently. A green run
|
||||
* only ever means "the gate could classify and there is nothing to do".
|
||||
*
|
||||
* Plain Node, stdlib only — the gate must stay cheap (no pnpm install).
|
||||
*
|
||||
* node scripts/ci-classify-production.mjs --deployed <sha> [--value]
|
||||
* node scripts/ci-classify-production.mjs --files-from <file> [--value]
|
||||
*
|
||||
* Output: JSON { production, reason, changed, kept, skipped } on stdout
|
||||
* (`--value` prints only `true`/`false`). Exit 0 = classified; exit 1 =
|
||||
* could not classify (production=true printed, run should go red).
|
||||
*/
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
import { isDockerignored, parseDockerignore } from './lib/dockerignore.mjs'
|
||||
|
||||
const parseArgs = (argv) => {
|
||||
const flags = {}
|
||||
for (let index = 2; index < argv.length; index += 1) {
|
||||
const arg = argv[index]
|
||||
if (arg.startsWith('--')) {
|
||||
const name = arg.slice(2).replace(/-([a-z])/g, (_, char) => char.toUpperCase())
|
||||
const next = argv[index + 1]
|
||||
flags[name] = typeof next === 'string' && !next.startsWith('--') ? next : true
|
||||
if (typeof next === 'string' && !next.startsWith('--')) index += 1
|
||||
}
|
||||
}
|
||||
return flags
|
||||
}
|
||||
|
||||
const flags = parseArgs(process.argv)
|
||||
const deployed = flags.deployed
|
||||
const filesFrom = flags.filesFrom
|
||||
const valueOnly = flags.value === true
|
||||
|
||||
/**
|
||||
* @param {string[]} changed - repo-relative changed paths
|
||||
* @param {import('./lib/dockerignore.mjs').DockerignoreRule[]} patterns -
|
||||
* .dockerignore rules
|
||||
* @returns {{ production: boolean, kept: string[], skipped: string[] }}
|
||||
*/
|
||||
export function classifyProduction(changed, patterns) {
|
||||
const kept = []
|
||||
const skipped = []
|
||||
for (const path of changed) {
|
||||
if (path.length === 0) continue
|
||||
if (isDockerignored(path, patterns)) skipped.push(path)
|
||||
else kept.push(path)
|
||||
}
|
||||
return { production: kept.length > 0, kept, skipped }
|
||||
}
|
||||
|
||||
const report = (production, reason, extra = {}) => {
|
||||
const result = { production, reason, ...extra }
|
||||
if (valueOnly) {
|
||||
console.log(production)
|
||||
return
|
||||
}
|
||||
console.log(JSON.stringify(result))
|
||||
}
|
||||
|
||||
/**
|
||||
* Could not classify at all (git/.dockerignore unreadable, no input): run
|
||||
* the full pipeline AND make the run red — a gate that cannot classify must
|
||||
* never look like "nothing to do".
|
||||
*/
|
||||
const failOpenRed = (reason) => {
|
||||
report(true, reason, { changed: [], kept: [], skipped: [] })
|
||||
process.exitCode = 1
|
||||
}
|
||||
|
||||
// Import-safe: the module is unit-tested (classifyProduction), so the CLI
|
||||
// body only runs when executed as a script.
|
||||
const isCli =
|
||||
typeof process.argv[1] === 'string' && import.meta.url === pathToFileURL(process.argv[1]).href
|
||||
if (isCli) {
|
||||
main()
|
||||
}
|
||||
|
||||
function main() {
|
||||
if (process.env.GITHUB_EVENT_NAME === 'workflow_dispatch') {
|
||||
report(true, 'workflow_dispatch (intenção explícita)')
|
||||
return
|
||||
}
|
||||
|
||||
let changed
|
||||
try {
|
||||
if (filesFrom) {
|
||||
changed = readFileSync(filesFrom, 'utf8').split('\n').filter(Boolean)
|
||||
} else if (deployed === '') {
|
||||
// The workflow always passes --deployed (possibly empty: no container
|
||||
// revision on the homeserver). An empty deployed SHA is a legitimate
|
||||
// "unknown deployed state" — run the full pipeline, keep the run green.
|
||||
report(true, 'sem SHA deployado (estado desconhecido)', {
|
||||
changed: [],
|
||||
kept: [],
|
||||
skipped: [],
|
||||
})
|
||||
return
|
||||
} else if (deployed === true) {
|
||||
failOpenRed('--deployed sem valor')
|
||||
return
|
||||
} else if (deployed) {
|
||||
changed = execFileSync('git', ['diff', '--name-only', deployed, 'HEAD', '--'], {
|
||||
encoding: 'utf8',
|
||||
})
|
||||
.split('\n')
|
||||
.filter(Boolean)
|
||||
} else {
|
||||
failOpenRed('sem SHA deployado nem files-from')
|
||||
return
|
||||
}
|
||||
} catch (error) {
|
||||
failOpenRed(`erro ao obter o diff (${error instanceof Error ? error.message : error})`)
|
||||
return
|
||||
}
|
||||
|
||||
if (changed.length === 0) {
|
||||
report(false, 'diff vazio (nada a fazer)', {
|
||||
changed: [],
|
||||
kept: [],
|
||||
skipped: [],
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
let rules
|
||||
try {
|
||||
rules = parseDockerignore(readFileSync('.dockerignore', 'utf8'))
|
||||
} catch (error) {
|
||||
failOpenRed(`.dockerignore ilegível (${error instanceof Error ? error.message : error})`)
|
||||
return
|
||||
}
|
||||
|
||||
const classified = classifyProduction(changed, rules)
|
||||
report(
|
||||
classified.production,
|
||||
classified.production ? 'mudança de produção desde o último deploy' : 'sem mudança de produção',
|
||||
{ changed, kept: classified.kept, skipped: classified.skipped },
|
||||
)
|
||||
}
|
||||
|
|
@ -1,8 +1,9 @@
|
|||
#!/usr/bin/env node
|
||||
/**
|
||||
* ci-scope — single classifier for PR job-level skips. Prints JSON:
|
||||
* ci-scope — single classifier for PR step-level skips. Prints JSON:
|
||||
* { base, code, build, test, e2e } where each of code/build/test/e2e is the
|
||||
* classify* / selectE2eSpecs result. Used by the `scope` job in ci-pr.yml.
|
||||
* classify* / selectE2eSpecs result. Used by the `scope` step (id: scope) in
|
||||
* ci-pr.yml — its outputs drive `if:` on the heavy steps.
|
||||
*
|
||||
* Base ref: $GITHUB_BASE_REF (PR target) or origin/main locally.
|
||||
*/
|
||||
|
|
@ -13,7 +14,6 @@ import {
|
|||
classifyBuildScope,
|
||||
classifyStaticScope,
|
||||
classifyTestScope,
|
||||
e2eShardConfig,
|
||||
selectE2eSpecs,
|
||||
} from './lib/test-affected-core.mjs'
|
||||
|
||||
|
|
@ -34,9 +34,6 @@ try {
|
|||
build: { mode: 'build', reason: full.reason },
|
||||
test: { ...full },
|
||||
e2e: { mode: 'full', specs: [], reason: full.reason, unmapped: [] },
|
||||
// The scope job always reads e2e_shards.matrix/total — keep the fallback
|
||||
// total (ci-pr.yml's fromJson must never receive a null/empty matrix).
|
||||
e2e_shards: e2eShardConfig('full'),
|
||||
}),
|
||||
)
|
||||
process.exit(0)
|
||||
|
|
@ -67,6 +64,5 @@ console.log(
|
|||
build: classifyBuildScope(files),
|
||||
test: classifyTestScope(files),
|
||||
e2e,
|
||||
e2e_shards: e2eShardConfig(e2e.mode),
|
||||
}),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -52,6 +52,20 @@ if [ "$main_head" != "$SHA" ]; then
|
|||
exit 0
|
||||
fi
|
||||
|
||||
# --- idempotency (OPS65) ------------------------------------------------
|
||||
# A 30-min main window can re-deliver a SHA the cluster already runs (e.g. a
|
||||
# duplicate workflow_dispatch): rebuilding it is a ~15 min no-op. The truth
|
||||
# is the RUNNING container's revision label — the compose file can lie after
|
||||
# a failed rollback (it is swapped before the rollout and restored best-
|
||||
# effort). A container without the label (or down) counts as "not deployed":
|
||||
# the deploy proceeds (safe direction — it rebuilds).
|
||||
|
||||
running_rev="$(docker inspect -f '{{index .Config.Labels "org.opencontainers.image.revision"}}' teqo-1313 2>/dev/null || true)"
|
||||
if [ -n "$running_rev" ] && [ "$running_rev" = "$SHA" ]; then
|
||||
say "already deployed: teqo-1313 runs $SHA — nothing to do"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# --- secrets (sourced locally, never echoed) ----------------------------
|
||||
|
||||
set -a
|
||||
|
|
|
|||
|
|
@ -29,8 +29,21 @@ export const loadCliEnv = () => {
|
|||
loadEnv({ path: '.env' })
|
||||
}
|
||||
|
||||
/** Local database hosts — including the docker-compose service name. THE one list. */
|
||||
export const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '0.0.0.0', '::1', 'postgres'])
|
||||
/**
|
||||
* Local database hosts — docker-compose service name, the job-network service
|
||||
* names of the self-hosted Forgejo runner (OPS62 X1: services are reached by
|
||||
* name, no host publish), and the bridge gateway (OPS50: legacy per-port
|
||||
* publish kept in the allowlist). THE one list.
|
||||
*/
|
||||
export const LOCAL_HOSTS = new Set([
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
'0.0.0.0',
|
||||
'::1',
|
||||
'postgres',
|
||||
'postgres-int',
|
||||
'postgres-build',
|
||||
])
|
||||
|
||||
/**
|
||||
* Gateway of the default route, read from /proc/net/route (Linux). The
|
||||
|
|
|
|||
106
scripts/lib/dockerignore.mjs
Normal file
106
scripts/lib/dockerignore.mjs
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
/**
|
||||
* dockerignore match — pure `.dockerignore` semantics (moby patternmatcher
|
||||
* subset) for the CI production-change gate (OPS65). No git, no fs, no deps.
|
||||
*
|
||||
* The gate classifies "production change" by asking: would this path enter the
|
||||
* docker build context? The `.dockerignore` is the source of truth for the
|
||||
* artifact (the Dockerfile does `COPY . .`), so a path is production when it
|
||||
* is NOT excluded by the ignore patterns.
|
||||
*
|
||||
* Implemented rules (moby semantics):
|
||||
* - blank lines and `#` comments are ignored
|
||||
* - `!` prefixes a negation (re-include); last match wins
|
||||
* - trailing `/` is a directory pattern (the dir itself and its tree)
|
||||
* - leading `/` anchors the pattern to the context root
|
||||
* - a pattern with no other `/` matches the basename at ANY depth
|
||||
* - any matched path also excludes everything under it (the builder prunes
|
||||
* at the matched directory, so `docs` excludes `docs/x.md`)
|
||||
* - `*` matches any run of non-separator chars, `?` a single one
|
||||
* - `**` matches any number of directories (globstar)
|
||||
*/
|
||||
|
||||
/** A compiled ignore rule: regex against the cleaned repo-relative path. */
|
||||
export class DockerignoreRule {
|
||||
/**
|
||||
* @param {RegExp} regex - compiled matcher
|
||||
* @param {boolean} negate - `!` prefix: re-include when matched
|
||||
* @param {string} source - original pattern text (diagnostics)
|
||||
*/
|
||||
constructor(regex, negate, source) {
|
||||
this.regex = regex
|
||||
this.negate = negate
|
||||
this.source = source
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} pattern - one `.dockerignore` line (no trailing newline)
|
||||
* @returns {DockerignoreRule}
|
||||
*/
|
||||
export function compileDockerignoreRule(pattern) {
|
||||
const source = pattern
|
||||
let negate = false
|
||||
if (pattern.startsWith('!')) {
|
||||
negate = true
|
||||
pattern = pattern.slice(1)
|
||||
}
|
||||
if (pattern.endsWith('/')) pattern = pattern.slice(0, -1)
|
||||
const anchored = pattern.startsWith('/')
|
||||
if (anchored) pattern = pattern.slice(1)
|
||||
|
||||
let body = ''
|
||||
for (let index = 0; index < pattern.length; index += 1) {
|
||||
const char = pattern[index]
|
||||
if (char === '*') {
|
||||
if (pattern[index + 1] === '*') {
|
||||
index += 1
|
||||
if (pattern[index + 1] === '/') {
|
||||
body += '(?:.*/)?'
|
||||
index += 1
|
||||
} else {
|
||||
body += '.*'
|
||||
}
|
||||
} else {
|
||||
body += '[^/]*'
|
||||
}
|
||||
} else if (char === '?') {
|
||||
body += '[^/]'
|
||||
} else if ('\\^$.|+()[]{}'.includes(char)) {
|
||||
body += `\\${char}`
|
||||
} else {
|
||||
body += char
|
||||
}
|
||||
}
|
||||
|
||||
const anyDepth = !anchored && !pattern.includes('/') ? '(?:.*/)?' : ''
|
||||
const subtree = '(?:/.*)?'
|
||||
const regexSource = body.length > 0 ? `^${anyDepth}${body}${subtree}$` : '$^'
|
||||
return new DockerignoreRule(new RegExp(regexSource), negate, source)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} text - full `.dockerignore` content
|
||||
* @returns {DockerignoreRule[]} rules in order (last match wins)
|
||||
*/
|
||||
export function parseDockerignore(text) {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0 && !line.startsWith('#'))
|
||||
.map(compileDockerignoreRule)
|
||||
}
|
||||
|
||||
/**
|
||||
* Last-match-wins exclusion test for one repo-relative path.
|
||||
*
|
||||
* @param {string} path - repo-relative, forward slashes (e.g. "src/app/x.ts")
|
||||
* @param {DockerignoreRule[]} rules - from parseDockerignore
|
||||
* @returns {boolean} true when the path is excluded from the build context
|
||||
*/
|
||||
export function isDockerignored(path, rules) {
|
||||
let ignored = false
|
||||
for (const rule of rules) {
|
||||
if (rule.regex.test(path)) ignored = !rule.negate
|
||||
}
|
||||
return ignored
|
||||
}
|
||||
51
scripts/lib/playwright-e2e-args.mjs
Normal file
51
scripts/lib/playwright-e2e-args.mjs
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
/**
|
||||
* Pure argv helpers for the local e2e runner (S6-FOLLOWUP, 2026-08-18).
|
||||
* `run-e2e-affected.mjs` consumes them; unit-pinned in
|
||||
* tests/unit/playwrightE2eArgs.unit.spec.ts.
|
||||
*
|
||||
* Why `--no-deps` + `--`: positional paths ARE parsed correctly by the
|
||||
* Playwright CLI (commander), but in DEV mode the project dependency chain
|
||||
* (setup -> campaign -> frontend -> admin, playwright.config.ts) makes the
|
||||
* runner drag ALL files of every dependency project into a selected run via
|
||||
* buildProjectsClosure — filtering to one frontend spec runs the whole
|
||||
* campaign family. `--no-deps` disables that closure for FILTERED runs only;
|
||||
* a full run keeps the dev chain (OPS34 cold-compile prewarm ordering). The
|
||||
* `--` separator guards the generated scope paths from flag parsing.
|
||||
*/
|
||||
|
||||
/** Flags that filter the run by themselves (not just runner knobs). */
|
||||
const FILTER_FLAG_RE = /^(?:--project|-g|--grep|--grep-invert)(?:=.*)?$/
|
||||
|
||||
/**
|
||||
* Passthrough args from the process argv, minus the script path. pnpm
|
||||
* consumes its own `--` separator, so a leading `--` in argv only appears on
|
||||
* direct `node scripts/...` invocations — strip exactly one, forward the rest
|
||||
* verbatim (flag values must not be re-classified, e.g. `-g grade`).
|
||||
* @param {string[]} argv process.argv
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export const parsePassthroughArgs = (argv) => {
|
||||
const rest = argv.slice(2)
|
||||
return rest[0] === '--' ? rest.slice(1) : rest
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{ scopeSpecPaths?: string[], passthroughArgs?: string[] }} input
|
||||
* scopeSpecPaths — repo-relative spec paths selected by the affected manifest.
|
||||
* passthroughArgs — extra args forwarded by the user.
|
||||
* @returns {string[]} pnpm argv for the e2e run, e.g.
|
||||
* ['test:e2e', '--no-deps', '--', 'tests/e2e/foo.e2e.spec.ts']
|
||||
*/
|
||||
export const buildPlaywrightE2eArgs = ({ scopeSpecPaths = [], passthroughArgs = [] }) => {
|
||||
const filtered =
|
||||
scopeSpecPaths.length > 0 ||
|
||||
passthroughArgs.some((arg) => !arg.startsWith('-') || FILTER_FLAG_RE.test(arg))
|
||||
const args = ['test:e2e', ...passthroughArgs]
|
||||
if (filtered && !passthroughArgs.includes('--no-deps')) {
|
||||
args.push('--no-deps')
|
||||
}
|
||||
if (scopeSpecPaths.length > 0) {
|
||||
args.push('--', ...scopeSpecPaths)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
|
@ -27,7 +27,10 @@ export const HIGH_RISK_EXACT = new Set([
|
|||
'scripts/lib/e2e-affected-manifest.mjs',
|
||||
'scripts/test-affected.mjs',
|
||||
'scripts/e2e-affected.mjs',
|
||||
'scripts/run-e2e-affected.mjs',
|
||||
'scripts/ci-scope.mjs',
|
||||
'scripts/ci-classify-production.mjs',
|
||||
'scripts/lib/dockerignore.mjs',
|
||||
'scripts/check-test-locations.mjs',
|
||||
'scripts/check-plans-only-pr-closes.mjs',
|
||||
'scripts/lib/plansOnlyClosesGuard.mjs',
|
||||
|
|
@ -254,21 +257,6 @@ export function selectE2eSpecs(files, manifest) {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CI job-level parallelism for the e2e suite (OPS34). The full run splits
|
||||
* across 2 shards (`--shard=N/total`); selected and none stay on a single
|
||||
* runner — a second build for a handful of specs is pure waste. Measured
|
||||
* 2026-08-10 (ci.yml run 31412425553): build 172s + tests 196s + ~54s fixed,
|
||||
* so shard 1 and 2 each land ≈ 5–5.5 min. Revisit at 3 shards if the sharded
|
||||
* wall drifts past ~6.5 min or the test split gets lopsided; ci.yml hardcodes
|
||||
* the same [1, 2] / 2 literal with a comment pointing back here.
|
||||
* @param {'full' | 'selected' | 'none'} mode
|
||||
* @returns {{ matrix: number[], total: number }}
|
||||
*/
|
||||
export function e2eShardConfig(mode) {
|
||||
return mode === 'full' ? { matrix: [1, 2], total: 2 } : { matrix: [1], total: 1 }
|
||||
}
|
||||
|
||||
/**
|
||||
* Walk a list of repo-relative paths and return misplaced spec/test files.
|
||||
* @param {string[]} paths
|
||||
|
|
|
|||
|
|
@ -6,7 +6,15 @@
|
|||
* 3. optional production build into `.next-e2e` when `E2E_PROD=1`.
|
||||
* 4. `pnpm test:e2e` (set `CI=1` and `E2E_PROD=1` together for prod mode).
|
||||
*
|
||||
* Extra Playwright args after `--` are forwarded (e.g. a single spec while debugging).
|
||||
* Extra Playwright args are forwarded verbatim (e.g. a single spec while
|
||||
* debugging): pnpm consumes the first `--` separator, so the script only ever
|
||||
* strips a leading `--` left by direct `node scripts/...` invocations
|
||||
* (S6-FOLLOWUP). Flag values like `-g grade` pass through untouched.
|
||||
*
|
||||
* Filtered runs get `--no-deps` (S6-FOLLOWUP): in dev mode the project
|
||||
* dependency chain drags every dependency project's files into a selected run
|
||||
* via buildProjectsClosure; --no-deps disables that closure. Full runs keep
|
||||
* the dev chain (OPS34 prewarm ordering).
|
||||
*
|
||||
* GITHUB_BASE_REF=stage node scripts/run-e2e-affected.mjs
|
||||
* pnpm test:e2e:affected -- tests/e2e/campaignHomeActions.e2e.spec.ts
|
||||
|
|
@ -15,10 +23,11 @@ import { execFileSync, spawnSync } from 'node:child_process'
|
|||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { buildPlaywrightE2eArgs, parsePassthroughArgs } from './lib/playwright-e2e-args.mjs'
|
||||
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
|
||||
const passthroughIndex = process.argv.indexOf('--')
|
||||
const passthroughArgs = passthroughIndex === -1 ? [] : process.argv.slice(passthroughIndex + 1)
|
||||
const passthroughArgs = parsePassthroughArgs(process.argv)
|
||||
|
||||
const scopeRaw = execFileSync('node', ['scripts/e2e-affected.mjs'], {
|
||||
cwd: repoRoot,
|
||||
|
|
@ -51,13 +60,11 @@ if (process.env.E2E_PROD === '1') {
|
|||
run('pnpm', ['build'], { NEXT_DIST_DIR: '.next-e2e' })
|
||||
}
|
||||
|
||||
const playwrightArgs = ['test:e2e']
|
||||
if (scope.mode === 'selected' && scope.specs.length > 0) {
|
||||
for (const name of scope.specs) {
|
||||
playwrightArgs.push(`tests/e2e/${name}.e2e.spec.ts`)
|
||||
}
|
||||
}
|
||||
playwrightArgs.push(...passthroughArgs)
|
||||
const playwrightArgs = buildPlaywrightE2eArgs({
|
||||
scopeSpecPaths:
|
||||
scope.mode === 'selected' ? scope.specs.map((name) => `tests/e2e/${name}.e2e.spec.ts`) : [],
|
||||
passthroughArgs,
|
||||
})
|
||||
|
||||
run('pnpm', playwrightArgs, {
|
||||
...(process.env.E2E_PROD === '1' ? { CI: '1', E2E_PROD: '1' } : {}),
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ import { ExportPreview as ExportPreview_cdf7e044479f899a31f804427d568b36 } from
|
|||
import { ExportSaveButton as ExportSaveButton_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { ImportPreview as ImportPreview_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { ImportSaveButton as ImportSaveButton_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { InstagramPostExclusionPicker as InstagramPostExclusionPicker_ba03418db242c21470543bbeb06827a0 } from '../../../components/admin/InstagramPostExclusionPicker'
|
||||
import { ImportExportProvider as ImportExportProvider_cdf7e044479f899a31f804427d568b36 } from '@payloadcms/plugin-import-export/rsc'
|
||||
import { CollectionCards as CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1 } from '@payloadcms/next/rsc'
|
||||
|
||||
|
|
@ -74,6 +75,7 @@ export const importMap = {
|
|||
"@payloadcms/plugin-import-export/rsc#ExportSaveButton": ExportSaveButton_cdf7e044479f899a31f804427d568b36,
|
||||
"@payloadcms/plugin-import-export/rsc#ImportPreview": ImportPreview_cdf7e044479f899a31f804427d568b36,
|
||||
"@payloadcms/plugin-import-export/rsc#ImportSaveButton": ImportSaveButton_cdf7e044479f899a31f804427d568b36,
|
||||
"./components/admin/InstagramPostExclusionPicker#InstagramPostExclusionPicker": InstagramPostExclusionPicker_ba03418db242c21470543bbeb06827a0,
|
||||
"@payloadcms/plugin-import-export/rsc#ImportExportProvider": ImportExportProvider_cdf7e044479f899a31f804427d568b36,
|
||||
"@payloadcms/next/rsc#CollectionCards": CollectionCards_f9c02e79a4aed9a3924487c0cd4cafb1
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export type CampaignContentCardData = {
|
|||
coverUrl?: string
|
||||
coverAlt?: string
|
||||
subtitle?: string
|
||||
/** Cover ratio: 16:9 for articles/videos, 1:1 for Instagram posts. */
|
||||
coverAspect?: 'video' | 'square'
|
||||
/** External target (e.g. a YouTube video): opens in a new tab with noopener. */
|
||||
external?: boolean
|
||||
}
|
||||
|
|
@ -33,7 +35,11 @@ const cardClassName = (featured: boolean) =>
|
|||
export const CampaignContentCard = ({ card, featured = false }: CampaignContentCardProps) => {
|
||||
const inner = (
|
||||
<>
|
||||
<div className="relative aspect-video w-full shrink-0 overflow-hidden rounded-lg bg-(--campaign-band)">
|
||||
<div
|
||||
className={`relative w-full shrink-0 overflow-hidden rounded-lg bg-(--campaign-band) ${
|
||||
card.coverAspect === 'square' ? 'aspect-square' : 'aspect-video'
|
||||
}`}
|
||||
>
|
||||
{card.coverUrl ? (
|
||||
<Image
|
||||
src={card.coverUrl}
|
||||
|
|
|
|||
|
|
@ -8,7 +8,12 @@ import {
|
|||
getVisiblePosts,
|
||||
POST_TYPE_BADGE_LABELS,
|
||||
} from '@/utilities/posts'
|
||||
import { formatYouTubeViews, getYouTubeFeed, type YouTubeVideo } from '@/utilities/youtubeFeed'
|
||||
import { getInstagramFeed, type InstagramPost } from '@/utilities/socialFeed/instagramFeed'
|
||||
import {
|
||||
formatYouTubeViews,
|
||||
getYouTubeFeed,
|
||||
type YouTubeVideo,
|
||||
} from '@/utilities/socialFeed/youtubeFeed'
|
||||
import Link from 'next/link'
|
||||
|
||||
const CONTENT_SECTION_LIMIT = 5
|
||||
|
|
@ -69,23 +74,44 @@ const toVideoCardData = (video: YouTubeVideo): DatedCard => ({
|
|||
date: dateTimeOf(video.publishedAt),
|
||||
})
|
||||
|
||||
const toInstagramCardData = (post: InstagramPost): DatedCard => ({
|
||||
card: {
|
||||
id: `ig:${post.id}`,
|
||||
href: post.permalink,
|
||||
title: post.caption ?? 'Publicação no Instagram',
|
||||
badgeLabel: 'Instagram',
|
||||
meta: formatRelativePostDate(post.timestamp) ?? '',
|
||||
coverAspect: 'square',
|
||||
...(post.thumbnailUrl
|
||||
? { coverUrl: post.thumbnailUrl, coverAlt: post.caption ?? 'Publicação no Instagram' }
|
||||
: {}),
|
||||
external: true,
|
||||
},
|
||||
date: dateTimeOf(post.timestamp),
|
||||
})
|
||||
|
||||
/**
|
||||
* Campaign home content board: the 5 most recent items across the visible
|
||||
* posts (S1) and the eligible YouTube feed (S2), newest first, as a 1+4 bento
|
||||
* on desktop and a one-per-screen carousel on mobile. Hides entirely when
|
||||
* nothing is visible (`isPostVisible` fail-closed — hidden electoral tags
|
||||
* never leak) and never breaks when the feed API is down (snapshot or no
|
||||
* cards). With the feed unconfigured it degrades to the S1 articles-only
|
||||
* behavior.
|
||||
* posts (S1), the eligible YouTube feed (S2) and the eligible Instagram feed
|
||||
* (S3), newest first, as a 1+4 bento on desktop and a one-per-screen carousel
|
||||
* on mobile. Hides entirely when nothing is visible (`isPostVisible`
|
||||
* fail-closed — hidden electoral tags never leak) and never breaks when a
|
||||
* feed API is down (snapshot or no cards). With the feeds unconfigured it
|
||||
* degrades to the S1 articles-only behavior.
|
||||
*/
|
||||
export const CampaignContentSection = async () => {
|
||||
const [visiblePosts, feed] = await Promise.all([getVisiblePosts(), getYouTubeFeed()])
|
||||
const [visiblePosts, youtubeFeed, instagramFeed] = await Promise.all([
|
||||
getVisiblePosts(),
|
||||
getYouTubeFeed(),
|
||||
getInstagramFeed(),
|
||||
])
|
||||
const articleCards = visiblePosts
|
||||
.map(toArticleCardData)
|
||||
.filter((entry): entry is DatedCard => entry !== null)
|
||||
const videoCards = (feed?.videos ?? []).map(toVideoCardData)
|
||||
const videoCards = (youtubeFeed?.videos ?? []).map(toVideoCardData)
|
||||
const instagramCards = (instagramFeed?.posts ?? []).map(toInstagramCardData)
|
||||
|
||||
const cards = [...articleCards, ...videoCards]
|
||||
const cards = [...articleCards, ...videoCards, ...instagramCards]
|
||||
.sort(byRecencyDesc)
|
||||
.slice(0, CONTENT_SECTION_LIMIT)
|
||||
.map(({ card }) => card)
|
||||
|
|
@ -120,9 +146,19 @@ export const CampaignContentSection = async () => {
|
|||
<Link href="/artigos" className={sectionHeaderLinkClassName}>
|
||||
Ver artigos →
|
||||
</Link>
|
||||
{feed ? (
|
||||
{instagramFeed?.username ? (
|
||||
<a
|
||||
href={`https://www.youtube.com/channel/${feed.channelId}`}
|
||||
href={`https://www.instagram.com/${instagramFeed.username}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={sectionHeaderLinkClassName}
|
||||
>
|
||||
Seguir no Instagram →
|
||||
</a>
|
||||
) : null}
|
||||
{youtubeFeed ? (
|
||||
<a
|
||||
href={`https://www.youtube.com/channel/${youtubeFeed.channelId}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={sectionHeaderLinkClassName}
|
||||
|
|
|
|||
139
src/components/admin/InstagramPostExclusionPicker.tsx
Normal file
139
src/components/admin/InstagramPostExclusionPicker.tsx
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
'use client'
|
||||
|
||||
import { useAllFormFields, useField } from '@payloadcms/ui'
|
||||
import type { FieldClientComponent } from 'payload'
|
||||
|
||||
type InstagramSnapshotPost = {
|
||||
id: string
|
||||
caption: string | null
|
||||
mediaType: string
|
||||
permalink: string
|
||||
thumbnailUrl?: string
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
type InstagramSnapshot = {
|
||||
username?: string
|
||||
posts: InstagramSnapshotPost[]
|
||||
}
|
||||
|
||||
type ExcludedItem = {
|
||||
platform?: string
|
||||
itemId?: string
|
||||
reason?: string | null
|
||||
}
|
||||
|
||||
const isInstagramSnapshot = (value: unknown): value is InstagramSnapshot =>
|
||||
typeof value === 'object' && value !== null && Array.isArray((value as { posts?: unknown }).posts)
|
||||
|
||||
/**
|
||||
* Instagram exclusion picker (S3) — the board's "requisito nº 1": the
|
||||
* assessoria sees the latest posts of the profile (thumbnail + caption + date,
|
||||
* from the persisted feed snapshot) and marks the ones that must NOT appear on
|
||||
* the campaign home (e.g. grid mosaics). Each toggle writes/removes an entry
|
||||
* in the shared `excludedItems` array (platform `instagram`) — the same
|
||||
* mechanism YouTube uses, no migration needed. The posts appear here after the
|
||||
* first successful feed sync (cache of 5 min); while the API is down the
|
||||
* snapshot keeps the list alive.
|
||||
*/
|
||||
export const InstagramPostExclusionPicker: FieldClientComponent = () => {
|
||||
const [fields] = useAllFormFields()
|
||||
const { value: excludedItemsValue, setValue } = useField<ExcludedItem[]>({
|
||||
path: 'excludedItems',
|
||||
})
|
||||
const snapshot = fields.instagramFeedSnapshot?.value as unknown
|
||||
const posts = isInstagramSnapshot(snapshot) ? snapshot.posts : []
|
||||
const current = Array.isArray(excludedItemsValue) ? excludedItemsValue : []
|
||||
|
||||
const isExcluded = (postId: string) =>
|
||||
current.some((item) => item.platform === 'instagram' && item.itemId === postId)
|
||||
const reasonOf = (postId: string) =>
|
||||
current.find((item) => item.platform === 'instagram' && item.itemId === postId)?.reason ?? ''
|
||||
|
||||
const toggle = (post: InstagramSnapshotPost) => {
|
||||
const next = isExcluded(post.id)
|
||||
? current.filter((item) => !(item.platform === 'instagram' && item.itemId === post.id))
|
||||
: [...current, { platform: 'instagram', itemId: post.id }]
|
||||
setValue(next)
|
||||
}
|
||||
|
||||
const setReason = (postId: string, reason: string) => {
|
||||
const next = current.map((item) =>
|
||||
item.platform === 'instagram' && item.itemId === postId ? { ...item, reason } : item,
|
||||
)
|
||||
setValue(next)
|
||||
}
|
||||
|
||||
if (posts.length === 0) {
|
||||
return (
|
||||
<p className="text-sm text-zinc-500">
|
||||
Nenhum post recente ainda. Com o token e o ID do usuário configurados, os posts aparecem
|
||||
aqui após a primeira sincronização (a cada 5 minutos).
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-zinc-500">
|
||||
Posts recentes do perfil (da última sincronização). Marque "Não exibir" nos que
|
||||
não são conteúdo real de campanha (ex.: grade do feed) — eles somem do board.
|
||||
</p>
|
||||
{posts.map((post) => {
|
||||
const excluded = isExcluded(post.id)
|
||||
return (
|
||||
<div
|
||||
key={post.id}
|
||||
className={`flex items-center gap-3 rounded-lg border p-2 ${
|
||||
excluded ? 'border-zinc-300 bg-zinc-100' : 'border-zinc-200'
|
||||
}`}
|
||||
>
|
||||
{post.thumbnailUrl ? (
|
||||
// Plain img: the admin panel renders media outside next/image.
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={post.thumbnailUrl}
|
||||
alt=""
|
||||
width={56}
|
||||
height={56}
|
||||
className="h-14 w-14 shrink-0 rounded object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-14 w-14 shrink-0 items-center justify-center rounded bg-zinc-200 text-xs text-zinc-500">
|
||||
sem capa
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="truncate text-sm font-semibold text-zinc-900">
|
||||
{post.caption ?? 'Publicação no Instagram'}
|
||||
</p>
|
||||
<p className="text-xs text-zinc-500">
|
||||
{new Date(post.timestamp).toLocaleDateString('pt-BR')} · {post.id}
|
||||
</p>
|
||||
{excluded ? (
|
||||
<input
|
||||
defaultValue={reasonOf(post.id)}
|
||||
onChange={(event) => setReason(post.id, event.target.value)}
|
||||
placeholder="Motivo (opcional)"
|
||||
aria-label={`Motivo da exclusão de ${post.caption ?? 'publicação'}`}
|
||||
className="mt-1 w-full rounded border border-zinc-300 px-2 py-1 text-xs text-zinc-700"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => toggle(post)}
|
||||
className={`shrink-0 rounded px-3 py-1.5 text-xs font-bold transition-colors ${
|
||||
excluded
|
||||
? 'bg-zinc-200 text-zinc-700 hover:bg-zinc-300'
|
||||
: 'bg-zinc-900 text-white hover:bg-zinc-700'
|
||||
}`}
|
||||
>
|
||||
{excluded ? 'Reexibir' : 'Não exibir'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -79,6 +79,53 @@ export const SocialFeedSettings: GlobalConfig = {
|
|||
description: 'Quantos vídeos entram no bento (1 grande + os próximos).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramEnabled',
|
||||
type: 'checkbox',
|
||||
label: 'Instagram ativo',
|
||||
defaultValue: true,
|
||||
admin: {
|
||||
description: 'Desliga só os cards de post do Instagram.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramAccessToken',
|
||||
type: 'text',
|
||||
label: 'Token de acesso (Instagram Graph API)',
|
||||
admin: {
|
||||
description:
|
||||
'Token long-lived da conta Business/Creator vinculada à página do Facebook. Tokens emitidos via Instagram Login são renovados automaticamente; para page tokens, o refresh falha e o token precisa ser trocado aqui manualmente.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramUserId',
|
||||
type: 'text',
|
||||
label: 'ID do usuário (conta Business/Creator)',
|
||||
admin: {
|
||||
description: 'ID numérico da conta de negócios do Instagram.',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramMaxItems',
|
||||
type: 'number',
|
||||
label: 'Máximo de posts',
|
||||
defaultValue: 3,
|
||||
min: 1,
|
||||
max: 5,
|
||||
admin: {
|
||||
description: 'Quantos posts entram no bento (1 grande + os próximos).',
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramExclusionPicker',
|
||||
type: 'ui',
|
||||
label: 'Instagram — posts recentes',
|
||||
admin: {
|
||||
components: {
|
||||
Field: './components/admin/InstagramPostExclusionPicker#InstagramPostExclusionPicker',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'excludedItems',
|
||||
type: 'array',
|
||||
|
|
@ -131,5 +178,12 @@ export const SocialFeedSettings: GlobalConfig = {
|
|||
hidden: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'instagramFeedSnapshot',
|
||||
type: 'json',
|
||||
admin: {
|
||||
hidden: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
|
|
|
|||
13749
src/migrations/20260818_192948_add_instagram_social_feed_fields.json
Normal file
13749
src/migrations/20260818_192948_add_instagram_social_feed_fields.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,19 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "social_feed_settings" ADD COLUMN "instagram_enabled" boolean DEFAULT true;
|
||||
ALTER TABLE "social_feed_settings" ADD COLUMN "instagram_access_token" varchar;
|
||||
ALTER TABLE "social_feed_settings" ADD COLUMN "instagram_user_id" varchar;
|
||||
ALTER TABLE "social_feed_settings" ADD COLUMN "instagram_max_items" numeric DEFAULT 3;
|
||||
ALTER TABLE "social_feed_settings" ADD COLUMN "instagram_feed_snapshot" jsonb;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "social_feed_settings" DROP COLUMN "instagram_enabled";
|
||||
ALTER TABLE "social_feed_settings" DROP COLUMN "instagram_access_token";
|
||||
ALTER TABLE "social_feed_settings" DROP COLUMN "instagram_user_id";
|
||||
ALTER TABLE "social_feed_settings" DROP COLUMN "instagram_max_items";
|
||||
ALTER TABLE "social_feed_settings" DROP COLUMN "instagram_feed_snapshot";`)
|
||||
}
|
||||
|
|
@ -55,6 +55,7 @@ import * as migration_20260811_205157_add_google_calendar_push_channel from './2
|
|||
import * as migration_20260811_213648_add_activity_last_mirrored_change_at from './20260811_213648_add_activity_last_mirrored_change_at';
|
||||
import * as migration_20260811_234822_add_state_deputy_ballot_name from './20260811_234822_add_state_deputy_ballot_name';
|
||||
import * as migration_20260818_111748_add_social_feed_settings from './20260818_111748_add_social_feed_settings';
|
||||
import * as migration_20260818_192948_add_instagram_social_feed_fields from './20260818_192948_add_instagram_social_feed_fields';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -340,6 +341,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20260818_111748_add_social_feed_settings.up,
|
||||
down: migration_20260818_111748_add_social_feed_settings.down,
|
||||
name: '20260818_111748_add_social_feed_settings'
|
||||
name: '20260818_111748_add_social_feed_settings',
|
||||
},
|
||||
{
|
||||
up: migration_20260818_192948_add_instagram_social_feed_fields.up,
|
||||
down: migration_20260818_192948_add_instagram_social_feed_fields.down,
|
||||
name: '20260818_192948_add_instagram_social_feed_fields'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -2395,6 +2395,22 @@ export interface SocialFeedSetting {
|
|||
* Quantos vídeos entram no bento (1 grande + os próximos).
|
||||
*/
|
||||
youtubeMaxItems?: number | null;
|
||||
/**
|
||||
* Desliga só os cards de post do Instagram.
|
||||
*/
|
||||
instagramEnabled?: boolean | null;
|
||||
/**
|
||||
* Token long-lived da conta Business/Creator vinculada à página do Facebook. Tokens emitidos via Instagram Login são renovados automaticamente; para page tokens, o refresh falha e o token precisa ser trocado aqui manualmente.
|
||||
*/
|
||||
instagramAccessToken?: string | null;
|
||||
/**
|
||||
* ID numérico da conta de negócios do Instagram.
|
||||
*/
|
||||
instagramUserId?: string | null;
|
||||
/**
|
||||
* Quantos posts entram no bento (1 grande + os próximos).
|
||||
*/
|
||||
instagramMaxItems?: number | null;
|
||||
/**
|
||||
* Conteúdo marcado para NÃO aparecer no board (vídeo errado, transmissão incompleta, post de grade). O board pula para o próximo elegível.
|
||||
*/
|
||||
|
|
@ -2415,6 +2431,15 @@ export interface SocialFeedSetting {
|
|||
| number
|
||||
| boolean
|
||||
| null;
|
||||
instagramFeedSnapshot?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
updatedAt?: string | null;
|
||||
createdAt?: string | null;
|
||||
}
|
||||
|
|
@ -2513,6 +2538,10 @@ export interface SocialFeedSettingsSelect<T extends boolean = true> {
|
|||
youtubeApiKey?: T;
|
||||
youtubeChannelId?: T;
|
||||
youtubeMaxItems?: T;
|
||||
instagramEnabled?: T;
|
||||
instagramAccessToken?: T;
|
||||
instagramUserId?: T;
|
||||
instagramMaxItems?: T;
|
||||
excludedItems?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -2522,6 +2551,7 @@ export interface SocialFeedSettingsSelect<T extends boolean = true> {
|
|||
id?: T;
|
||||
};
|
||||
youtubeFeedSnapshot?: T;
|
||||
instagramFeedSnapshot?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
globalType?: T;
|
||||
|
|
|
|||
312
src/utilities/socialFeed/instagramFeed.ts
Normal file
312
src/utilities/socialFeed/instagramFeed.ts
Normal file
|
|
@ -0,0 +1,312 @@
|
|||
import 'server-only'
|
||||
|
||||
import type { SocialFeedSetting } from '@/payload-types'
|
||||
import { REVALIDATE_SOCIAL_FEED_TAG } from '@/utilities/revalidateRequest'
|
||||
import configPromise from '@payload-config'
|
||||
import { sql } from '@payloadcms/db-postgres'
|
||||
import { unstable_cache } from 'next/cache'
|
||||
import { getPayload, type Payload } from 'payload'
|
||||
|
||||
const INSTAGRAM_API_BASE_URL = process.env.INSTAGRAM_API_BASE_URL ?? 'https://graph.instagram.com'
|
||||
|
||||
export const INSTAGRAM_MAX_RESULTS_CAP = 50
|
||||
|
||||
type InstagramMediaType = 'IMAGE' | 'VIDEO' | 'REEL' | 'CAROUSEL_ALBUM'
|
||||
|
||||
export type InstagramPost = {
|
||||
id: string
|
||||
caption: string | null
|
||||
mediaType: InstagramMediaType
|
||||
permalink: string
|
||||
thumbnailUrl?: string
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
export type InstagramFeedResult = {
|
||||
username: string | null
|
||||
posts: InstagramPost[]
|
||||
}
|
||||
|
||||
export type LoadInstagramFeedArgs = {
|
||||
accessToken: string
|
||||
userId: string
|
||||
maxResults: number
|
||||
fetchImpl?: (input: string, init?: RequestInit) => Promise<Response>
|
||||
baseUrl?: string
|
||||
}
|
||||
|
||||
export type LoadInstagramFeedResult = InstagramFeedResult & {
|
||||
/** Present only when the fetch had to refresh the token mid-flight. */
|
||||
refreshedAccessToken?: string
|
||||
}
|
||||
|
||||
const MEDIA_FIELDS = [
|
||||
'id',
|
||||
'caption',
|
||||
'media_type',
|
||||
'media_url',
|
||||
'permalink',
|
||||
'thumbnail_url',
|
||||
'timestamp',
|
||||
'children{media_url,thumbnail_url}',
|
||||
].join(',')
|
||||
|
||||
/**
|
||||
* Best thumbnail of a media item, by type: images use the media URL, videos
|
||||
* and reels the thumbnail (never the mp4), carousels the first child that
|
||||
* carries either. A missing value reads as undefined and the card renders
|
||||
* without a cover (already supported) instead of a broken image.
|
||||
*/
|
||||
export const pickInstagramThumbnail = (item: {
|
||||
media_type?: unknown
|
||||
media_url?: unknown
|
||||
thumbnail_url?: unknown
|
||||
children?: unknown
|
||||
}): string | undefined => {
|
||||
const urlOf = (value: unknown): string | undefined =>
|
||||
typeof value === 'string' && value ? value : undefined
|
||||
|
||||
const mediaType = item.media_type
|
||||
if (mediaType === 'IMAGE') return urlOf(item.media_url)
|
||||
if (mediaType === 'VIDEO' || mediaType === 'REEL') return urlOf(item.thumbnail_url)
|
||||
|
||||
if (mediaType === 'CAROUSEL_ALBUM') {
|
||||
const children = item.children as { data?: unknown } | undefined
|
||||
if (typeof children === 'object' && children !== null && Array.isArray(children.data)) {
|
||||
for (const child of children.data) {
|
||||
if (typeof child !== 'object' || child === null) continue
|
||||
const rawChild = child as { media_url?: unknown; thumbnail_url?: unknown }
|
||||
const url = urlOf(rawChild.media_url) ?? urlOf(rawChild.thumbnail_url)
|
||||
if (url) return url
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a `/media` response into posts. Throws on a protocol-level violation
|
||||
* (no `data` array); individual malformed items are skipped, but an item
|
||||
* without an id, a timestamp or a permalink is dropped — it could not be
|
||||
* placed in the recency merge nor opened on the platform. A null caption is
|
||||
* kept: captionless posts (e.g. grid mosaics) still show with a fallback
|
||||
* title so the assessoria can exclude them item by item.
|
||||
*/
|
||||
export const parseInstagramMediaResponse = (json: unknown): InstagramPost[] => {
|
||||
if (!json || typeof json !== 'object') {
|
||||
throw new Error('Resposta de mídia do Instagram inválida')
|
||||
}
|
||||
const data = (json as { data?: unknown }).data
|
||||
if (!Array.isArray(data)) {
|
||||
throw new Error('Resposta de mídia do Instagram sem lista de itens')
|
||||
}
|
||||
|
||||
const posts: InstagramPost[] = []
|
||||
for (const item of data) {
|
||||
if (!item || typeof item !== 'object') continue
|
||||
|
||||
const rawItem = item as {
|
||||
id?: unknown
|
||||
caption?: unknown
|
||||
media_type?: unknown
|
||||
permalink?: unknown
|
||||
timestamp?: unknown
|
||||
}
|
||||
if (typeof rawItem.id !== 'string' || !rawItem.id) continue
|
||||
if (typeof rawItem.permalink !== 'string' || !rawItem.permalink) continue
|
||||
if (typeof rawItem.timestamp !== 'string' || !rawItem.timestamp) continue
|
||||
|
||||
posts.push({
|
||||
id: rawItem.id,
|
||||
caption: typeof rawItem.caption === 'string' ? rawItem.caption : null,
|
||||
mediaType: (rawItem.media_type as InstagramMediaType) ?? 'IMAGE',
|
||||
permalink: rawItem.permalink,
|
||||
timestamp: rawItem.timestamp,
|
||||
thumbnailUrl: pickInstagramThumbnail(rawItem),
|
||||
})
|
||||
}
|
||||
return posts
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps only the posts whose ids are not excluded, in API order (newest
|
||||
* first), capped at `maxItems`. The board skips an excluded post — it never
|
||||
* counts as "the latest" (grid mosaics get filtered this way).
|
||||
*/
|
||||
export const eligibleInstagramPosts = (
|
||||
posts: InstagramPost[],
|
||||
excludedIds: string[],
|
||||
maxItems: number,
|
||||
): InstagramPost[] => posts.filter((post) => !excludedIds.includes(post.id)).slice(0, maxItems)
|
||||
|
||||
const jsonFrom = async (response: Response): Promise<unknown> => response.json()
|
||||
|
||||
/**
|
||||
* Fetches the username and the latest media of a Business/Creator profile:
|
||||
* `GET /{userId}` for the username, then `GET /{userId}/media` for the posts
|
||||
* (permalink, caption, thumbnail, timestamp). On any failure it attempts one
|
||||
* token refresh (`refresh_access_token` — only mints/refreshes Instagram
|
||||
* Login tokens; page tokens from Facebook Login error out and the caller
|
||||
* falls back to the snapshot) and retries once. Throws when the retry also
|
||||
* fails so the cached wrapper can fail closed.
|
||||
*/
|
||||
export const loadInstagramFeed = async ({
|
||||
accessToken,
|
||||
userId,
|
||||
maxResults,
|
||||
fetchImpl = fetch,
|
||||
baseUrl = INSTAGRAM_API_BASE_URL,
|
||||
}: LoadInstagramFeedArgs): Promise<LoadInstagramFeedResult> => {
|
||||
const attempt = async (token: string): Promise<InstagramFeedResult> => {
|
||||
const userParams = new URLSearchParams({ fields: 'username', access_token: token })
|
||||
const userResponse = await fetchImpl(`${baseUrl}/${userId}?${userParams}`)
|
||||
if (!userResponse.ok) {
|
||||
throw new Error(`Instagram user falhou com status ${userResponse.status}`)
|
||||
}
|
||||
const userJson = (await jsonFrom(userResponse)) as { username?: unknown }
|
||||
const username = typeof userJson.username === 'string' ? userJson.username : null
|
||||
|
||||
const mediaParams = new URLSearchParams({
|
||||
fields: MEDIA_FIELDS,
|
||||
limit: String(Math.min(Math.max(maxResults, 1), INSTAGRAM_MAX_RESULTS_CAP)),
|
||||
access_token: token,
|
||||
})
|
||||
const mediaResponse = await fetchImpl(`${baseUrl}/${userId}/media?${mediaParams}`)
|
||||
if (!mediaResponse.ok) {
|
||||
throw new Error(`Instagram media falhou com status ${mediaResponse.status}`)
|
||||
}
|
||||
|
||||
return { username, posts: parseInstagramMediaResponse(await jsonFrom(mediaResponse)) }
|
||||
}
|
||||
|
||||
try {
|
||||
return await attempt(accessToken)
|
||||
} catch {
|
||||
const refreshParams = new URLSearchParams({
|
||||
grant_type: 'ig_refresh_token',
|
||||
access_token: accessToken,
|
||||
})
|
||||
const refreshResponse = await fetchImpl(`${baseUrl}/refresh_access_token?${refreshParams}`)
|
||||
if (!refreshResponse.ok) {
|
||||
throw new Error(`Instagram token refresh falhou com status ${refreshResponse.status}`)
|
||||
}
|
||||
const refreshJson = (await jsonFrom(refreshResponse)) as { access_token?: unknown }
|
||||
if (typeof refreshJson.access_token !== 'string' || !refreshJson.access_token) {
|
||||
throw new Error('Instagram token refresh sem novo token')
|
||||
}
|
||||
return {
|
||||
...(await attempt(refreshJson.access_token)),
|
||||
refreshedAccessToken: refreshJson.access_token,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const excludedInstagramIds = (settings: SocialFeedSetting): string[] =>
|
||||
(settings.excludedItems ?? [])
|
||||
.filter((item) => item.platform === 'instagram')
|
||||
.map((item) => item.itemId)
|
||||
.filter(Boolean)
|
||||
|
||||
const isInstagramSnapshot = (value: unknown): value is { username?: unknown; posts?: unknown } =>
|
||||
typeof value === 'object' && value !== null
|
||||
|
||||
/**
|
||||
* Persists the raw feed as the global's snapshot column. Deliberately raw SQL
|
||||
* (`payload.db.drizzle`) instead of `payload.updateGlobal`: this runs INSIDE
|
||||
* `unstable_cache` during a page render, and Next 15.4 throws when
|
||||
* `revalidateTag` (the global's `afterChange` hook) fires inside a cached
|
||||
* function. Raw SQL bypasses hooks; the row is created on first write when the
|
||||
* admin has not saved the global yet (a serial id is assigned, so no id
|
||||
* assumption is made).
|
||||
*
|
||||
* Precondition: at most one `social_feed_settings` row exists. The UPDATE
|
||||
* targets the single row and the INSERT only fires when none exists; a
|
||||
* concurrent double-insert would need two writers racing the very first write
|
||||
* (the row is created by the first admin save or feed render) — accepted.
|
||||
*/
|
||||
const persistInstagramSnapshot = async (
|
||||
payload: Payload,
|
||||
snapshot: InstagramFeedResult,
|
||||
): Promise<void> => {
|
||||
const database = payload.db.drizzle
|
||||
const json = JSON.stringify(snapshot)
|
||||
const updated = await database.execute(sql`
|
||||
UPDATE "social_feed_settings"
|
||||
SET "instagram_feed_snapshot" = ${json}::jsonb, "updated_at" = now()
|
||||
WHERE "id" = (SELECT "id" FROM "social_feed_settings" ORDER BY "id" LIMIT 1)
|
||||
`)
|
||||
if (!updated?.rowCount) {
|
||||
await database.execute(sql`
|
||||
INSERT INTO "social_feed_settings" ("instagram_feed_snapshot", "created_at", "updated_at")
|
||||
VALUES (${json}::jsonb, now(), now())
|
||||
`)
|
||||
}
|
||||
}
|
||||
|
||||
/** Persists a refreshed token the same way as the snapshot (raw SQL, no hooks). */
|
||||
const persistInstagramAccessToken = async (payload: Payload, token: string): Promise<void> => {
|
||||
await payload.db.drizzle.execute(sql`
|
||||
UPDATE "social_feed_settings"
|
||||
SET "instagram_access_token" = ${token}, "updated_at" = now()
|
||||
WHERE "id" = (SELECT "id" FROM "social_feed_settings" ORDER BY "id" LIMIT 1)
|
||||
`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached Instagram feed for the campaign home content board: `null` when the
|
||||
* feed is off (kill switch, platform toggle or missing credentials), otherwise
|
||||
* the latest eligible posts plus the profile username. A successful fetch
|
||||
* persists the RAW list (pre-exclusion) as the global snapshot; a failed fetch
|
||||
* falls back to that snapshot with the current exclusions applied — so a new
|
||||
* exclusion works even while the API is down, and the page never breaks.
|
||||
* Busted by the global's `afterChange` (tag `social-feed`); the per-entry
|
||||
* `revalidate` keeps new uploads appearing without an admin edit.
|
||||
*/
|
||||
export const getInstagramFeed = unstable_cache(
|
||||
async (): Promise<InstagramFeedResult | null> => {
|
||||
const payload = await getPayload({ config: configPromise })
|
||||
const settings = await payload.findGlobal({
|
||||
slug: 'social-feed-settings',
|
||||
depth: 0,
|
||||
})
|
||||
|
||||
if (
|
||||
settings.enabled === false ||
|
||||
settings.instagramEnabled === false ||
|
||||
!settings.instagramAccessToken ||
|
||||
!settings.instagramUserId
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
const maxItems = Math.min(Math.max(settings.instagramMaxItems ?? 3, 1), 5)
|
||||
const excludedIds = excludedInstagramIds(settings)
|
||||
|
||||
try {
|
||||
const result = await loadInstagramFeed({
|
||||
accessToken: settings.instagramAccessToken,
|
||||
userId: settings.instagramUserId,
|
||||
maxResults: Math.min(maxItems + 10, INSTAGRAM_MAX_RESULTS_CAP),
|
||||
})
|
||||
await persistInstagramSnapshot(payload, { username: result.username, posts: result.posts })
|
||||
if (result.refreshedAccessToken) {
|
||||
await persistInstagramAccessToken(payload, result.refreshedAccessToken)
|
||||
}
|
||||
return {
|
||||
username: result.username,
|
||||
posts: eligibleInstagramPosts(result.posts, excludedIds, maxItems),
|
||||
}
|
||||
} catch {
|
||||
const snapshot = settings.instagramFeedSnapshot as unknown
|
||||
if (!isInstagramSnapshot(snapshot) || !Array.isArray(snapshot.posts)) {
|
||||
return { username: null, posts: [] }
|
||||
}
|
||||
return {
|
||||
username: typeof snapshot.username === 'string' ? snapshot.username : null,
|
||||
posts: eligibleInstagramPosts(snapshot.posts, excludedIds, maxItems),
|
||||
}
|
||||
}
|
||||
},
|
||||
['instagram-feed'],
|
||||
{ tags: [REVALIDATE_SOCIAL_FEED_TAG], revalidate: 300 },
|
||||
)
|
||||
|
|
@ -38,4 +38,98 @@ test.describe('Admin Panel', () => {
|
|||
const editViewArtifact = page.locator('input[name="email"]')
|
||||
await expect(editViewArtifact).toBeVisible()
|
||||
})
|
||||
|
||||
test('can exclude an Instagram post through the content board picker', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
// Seed the social-feed global with an Instagram snapshot so the exclusion
|
||||
// picker (S3) has posts to show. The snapshot is plain data — the picker
|
||||
// lists it and writes `excludedItems` (the same mechanism YouTube uses).
|
||||
const login = await request.post(`${baseURL}/api/users/login`, {
|
||||
data: { email: testUser.email, password: testUser.password },
|
||||
})
|
||||
expect(login.ok()).toBeTruthy()
|
||||
const { token } = await login.json()
|
||||
const headers = { cookie: `payload-token=${token}` }
|
||||
|
||||
const snapshot = {
|
||||
username: 'depjorgesolla',
|
||||
posts: [
|
||||
{
|
||||
id: 'e2e-ig-muro-1',
|
||||
caption: 'E2e Post do muro',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://www.instagram.com/p/e2e-ig-muro-1/',
|
||||
thumbnailUrl: null,
|
||||
timestamp: '2026-08-18T10:00:00+00:00',
|
||||
},
|
||||
{
|
||||
id: 'e2e-ig-reel-2',
|
||||
caption: 'E2e Reel da caravana',
|
||||
mediaType: 'REEL',
|
||||
permalink: 'https://www.instagram.com/p/e2e-ig-reel-2/',
|
||||
thumbnailUrl: null,
|
||||
timestamp: '2026-08-18T09:00:00+00:00',
|
||||
},
|
||||
],
|
||||
}
|
||||
const seed = await request.post(`${baseURL}/api/globals/social-feed-settings`, {
|
||||
headers,
|
||||
data: {
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: 'e2e-ig-token',
|
||||
instagramUserId: '17841400000000000',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [],
|
||||
instagramFeedSnapshot: snapshot,
|
||||
},
|
||||
})
|
||||
expect(seed.ok()).toBeTruthy()
|
||||
|
||||
try {
|
||||
await page.goto(`${baseURL}/admin/globals/social-feed-settings`)
|
||||
await expect(page.getByText('E2e Post do muro')).toBeVisible()
|
||||
|
||||
const hideButton = page.getByRole('button', { name: 'Não exibir' }).first()
|
||||
await expect(hideButton).toBeVisible()
|
||||
await hideButton.click()
|
||||
await expect(page.getByRole('button', { name: 'Reexibir' })).toBeVisible()
|
||||
|
||||
const saveResponse = page.waitForResponse(
|
||||
(response) =>
|
||||
response.url().includes('/api/globals/social-feed-settings') &&
|
||||
response.request().method() === 'POST',
|
||||
)
|
||||
await page.getByRole('button', { name: 'Salvar' }).click()
|
||||
await saveResponse
|
||||
|
||||
const read = await request.get(`${baseURL}/api/globals/social-feed-settings`, { headers })
|
||||
expect(read.ok()).toBeTruthy()
|
||||
const { excludedItems } = await read.json()
|
||||
expect(excludedItems).toEqual([
|
||||
expect.objectContaining({ platform: 'instagram', itemId: 'e2e-ig-muro-1' }),
|
||||
])
|
||||
} finally {
|
||||
await request
|
||||
.post(`${baseURL}/api/globals/social-feed-settings`, {
|
||||
headers,
|
||||
data: {
|
||||
enabled: true,
|
||||
youtubeEnabled: true,
|
||||
youtubeApiKey: '',
|
||||
youtubeChannelId: '',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: '',
|
||||
instagramUserId: '',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
},
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { APIRequestContext, Page } from '@playwright/test'
|
||||
|
||||
import { seedTestUser, testUser } from '../helpers/seedUser'
|
||||
import { youtubeStubUrlFor } from '../helpers/youtubeStub'
|
||||
import { instagramStubUrlFor, youtubeStubUrlFor } from '../helpers/socialStub'
|
||||
import { expect, test } from './fixtures/e2eTest'
|
||||
|
||||
const swipeLeft = async (
|
||||
|
|
@ -611,16 +611,33 @@ test.describe('Campaign home content section', () => {
|
|||
}
|
||||
}
|
||||
|
||||
// ---- S2 — YouTube feed: stub + settings helpers ----
|
||||
// The home route is ISR (s-maxage 300, no max-age): Chromium applies a
|
||||
// heuristic cache to such responses and a plain goto may serve the previous
|
||||
// body even after the poll converged (measured on the S2 snapshot tests —
|
||||
// flaky in CI, deterministic in prod-mode local). Navigating with a unique
|
||||
// query param misses every cache entry (HTTP + Next router), so the page
|
||||
// always comes fresh from the server; the app ignores unknown params.
|
||||
const gotoHomeFresh = async (page: Page) => {
|
||||
await page.goto(`/?e2e=${Date.now()}`)
|
||||
}
|
||||
|
||||
// Same derivation as playwright.config.ts: the stub listens on dev port + 1000.
|
||||
// ---- S2/S3 — YouTube + Instagram feed: stub + settings helpers ----
|
||||
|
||||
// Same derivation as playwright.config.ts: the stubs listen on dev port +
|
||||
// 1000 (YouTube) and + 2000 (Instagram).
|
||||
const youtubeStubUrl = youtubeStubUrlFor(baseURL)
|
||||
const instagramStubUrl = instagramStubUrlFor(baseURL)
|
||||
|
||||
const setYouTubeStubState = async (request: APIRequestContext, state: 'ok' | 'fail') => {
|
||||
const response = await request.post(`${youtubeStubUrl}/__stub/state`, { data: { state } })
|
||||
expect(response.ok()).toBeTruthy()
|
||||
}
|
||||
|
||||
const setInstagramStubState = async (request: APIRequestContext, state: 'ok' | 'fail') => {
|
||||
const response = await request.post(`${instagramStubUrl}/__stub/state`, { data: { state } })
|
||||
expect(response.ok()).toBeTruthy()
|
||||
}
|
||||
|
||||
const updateSocialFeedSettings = async (
|
||||
request: APIRequestContext,
|
||||
headers: Record<string, string>,
|
||||
|
|
@ -633,7 +650,7 @@ test.describe('Campaign home content section', () => {
|
|||
expect(response.ok()).toBeTruthy()
|
||||
}
|
||||
|
||||
// Full unconfigured state: the feed returns null and the S1 behavior is intact.
|
||||
// Full unconfigured state: both feeds return null and the S1 behavior is intact.
|
||||
const resetSocialFeedSettings = async (
|
||||
request: APIRequestContext,
|
||||
headers: Record<string, string>,
|
||||
|
|
@ -644,8 +661,13 @@ test.describe('Campaign home content section', () => {
|
|||
youtubeApiKey: '',
|
||||
youtubeChannelId: '',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: '',
|
||||
instagramUserId: '',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -687,6 +709,7 @@ test.describe('Campaign home content section', () => {
|
|||
.catch(() => undefined)
|
||||
await waitForHomeSectionState(request, 'absent')
|
||||
|
||||
// Plain URL on purpose: the test also pins the canonical home URL.
|
||||
await page.goto('/')
|
||||
await expect(page).toHaveURL(/\/$/)
|
||||
await expect(page.locator('[data-home-section="contents"]')).toHaveCount(0)
|
||||
|
|
@ -764,7 +787,7 @@ test.describe('Campaign home content section', () => {
|
|||
// The create hooks revalidated the `posts` tag in the server process;
|
||||
// wait until the regenerated page actually shows the section.
|
||||
await waitForHomeSectionState(request, 'present')
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
|
||||
|
|
@ -817,7 +840,7 @@ test.describe('Campaign home content section', () => {
|
|||
await page.goBack()
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const carousel = page.getByRole('region', { name: 'Conteúdos recentes' })
|
||||
await expect(carousel).toBeVisible()
|
||||
await expect(carousel.getByText('E2e Conteúdo oculto')).toHaveCount(0)
|
||||
|
|
@ -869,7 +892,7 @@ test.describe('Campaign home content section', () => {
|
|||
// next run starts deterministic (fail-closed on delete, too).
|
||||
await waitForHomeSectionState(request, 'absent')
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.locator('[data-home-section="contents"]')).toHaveCount(0)
|
||||
}
|
||||
}
|
||||
|
|
@ -911,7 +934,7 @@ test.describe('Campaign home content section', () => {
|
|||
['E2e Vídeo excluído'],
|
||||
)
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
|
||||
|
|
@ -941,7 +964,7 @@ test.describe('Campaign home content section', () => {
|
|||
await expect(channelLink).toHaveAttribute('target', '_blank')
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const carousel = page.getByRole('region', { name: 'Conteúdos recentes' })
|
||||
await expect(carousel).toBeVisible()
|
||||
await expect(carousel.getByText('1 de 4 · deslize para ver os próximos')).toBeVisible()
|
||||
|
|
@ -995,7 +1018,7 @@ test.describe('Campaign home content section', () => {
|
|||
['E2e Artigo fallback', 'YouTube →'],
|
||||
['E2e Vídeo em destaque'],
|
||||
)
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
await expect(section.getByRole('link', { name: /E2e Artigo fallback/ })).toBeVisible()
|
||||
|
|
@ -1029,7 +1052,7 @@ test.describe('Campaign home content section', () => {
|
|||
try {
|
||||
// Live fetch succeeds and persists the raw snapshot.
|
||||
await waitForHomeHTML(request, ['E2e Vídeo em destaque'], ['E2e Vídeo excluído'])
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Vídeo em destaque/ }).first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
|
|
@ -1051,7 +1074,7 @@ test.describe('Campaign home content section', () => {
|
|||
['E2e Vídeo em destaque', 'E2e Vídeo de caravana'],
|
||||
['E2e Vídeo de entrevista'],
|
||||
)
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Vídeo em destaque/ }).first()).toBeVisible()
|
||||
await expect(page.getByRole('link', { name: /E2e Vídeo de caravana/ })).toBeVisible()
|
||||
await expect(page.getByText('E2e Vídeo de entrevista')).toHaveCount(0)
|
||||
|
|
@ -1062,7 +1085,7 @@ test.describe('Campaign home content section', () => {
|
|||
await setYouTubeStubState(request, 'ok')
|
||||
await updateSocialFeedSettings(request, headers, baseSettings)
|
||||
await waitForHomeHTML(request, ['E2e Vídeo de entrevista'], ['E2e Vídeo excluído'])
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByText('E2e Vídeo de entrevista').first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
|
|
@ -1072,6 +1095,224 @@ test.describe('Campaign home content section', () => {
|
|||
}
|
||||
})
|
||||
|
||||
test('renders the Instagram feed with exclusions and opens posts on the platform', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
await seedTestUser()
|
||||
const headers = await adminHeaders(request)
|
||||
await setYouTubeStubState(request, 'ok')
|
||||
await setInstagramStubState(request, 'ok')
|
||||
|
||||
const mixTag = await createTag(
|
||||
request,
|
||||
headers,
|
||||
`E2e Mix IG ${runSuffix}`,
|
||||
`e2e-mix-ig-${runSuffix}`,
|
||||
)
|
||||
await createPost(request, headers, {
|
||||
title: 'E2e Artigo no mix IG',
|
||||
slug: `e2e-artigo-mix-ig-${runSuffix}`,
|
||||
type: 'artigo',
|
||||
category: mixTag.id,
|
||||
publishedDate: new Date(Date.now() - 60 * 60_000).toISOString(),
|
||||
})
|
||||
// The newest stub post is a grid mosaic marked as excluded: the board must
|
||||
// skip it and promote the next eligible one to the featured slot.
|
||||
await updateSocialFeedSettings(request, headers, {
|
||||
enabled: true,
|
||||
youtubeEnabled: true,
|
||||
youtubeApiKey: '',
|
||||
youtubeChannelId: '',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: 'e2e-ig-token',
|
||||
instagramUserId: '17841400000000000',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [{ platform: 'instagram', itemId: 'e2e-ig-grade-excluido-5' }],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
})
|
||||
|
||||
try {
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
['E2e Post do muro', 'E2e Artigo no mix IG'],
|
||||
['E2e Post de grade', 'YouTube →'],
|
||||
)
|
||||
await page.setViewportSize({ width: 1280, height: 900 })
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
|
||||
const featured = section.getByRole('link', { name: /E2e Post do muro/ })
|
||||
await expect(featured).toBeVisible()
|
||||
await expect(featured).toHaveAttribute('href', 'https://www.instagram.com/p/e2e-ig-muro-1/')
|
||||
await expect(featured).toHaveAttribute('target', '_blank')
|
||||
await expect(featured).toHaveAttribute('rel', 'noopener noreferrer')
|
||||
await expect(section.getByText('Instagram', { exact: true }).first()).toBeVisible()
|
||||
await expect(section.getByText('há 20 minutos').first()).toBeVisible()
|
||||
await expect(section.getByText('E2e Post de grade')).toHaveCount(0)
|
||||
|
||||
// The captionless grid post shows the fallback title (it enters the
|
||||
// board automatically and the assessoria excludes it item by item).
|
||||
await expect(section.getByText('Publicação no Instagram').first()).toBeVisible()
|
||||
// Instagram cards render the 1:1 cover of the approved draft.
|
||||
await expect(featured.locator('.aspect-square').first()).toBeVisible()
|
||||
|
||||
await expect(
|
||||
section.getByRole('link', { name: /E2e Artigo no mix IG/ }).first(),
|
||||
).toBeVisible()
|
||||
await expect(section.getByText('E2e Reel da caravana').first()).toBeVisible()
|
||||
|
||||
const profileLink = section.getByRole('link', { name: /Seguir no Instagram/ })
|
||||
await expect(profileLink).toHaveAttribute('href', 'https://www.instagram.com/depjorgesolla')
|
||||
await expect(profileLink).toHaveAttribute('target', '_blank')
|
||||
|
||||
await page.setViewportSize({ width: 390, height: 844 })
|
||||
await gotoHomeFresh(page)
|
||||
const carousel = page.getByRole('region', { name: 'Conteúdos recentes' })
|
||||
await expect(carousel).toBeVisible()
|
||||
await expect(carousel.getByText('1 de 4 · deslize para ver os próximos')).toBeVisible()
|
||||
await expect(carousel.getByText('E2e Post de grade')).toHaveCount(0)
|
||||
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
} finally {
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await cleanupS2Fixtures(request, headers)
|
||||
}
|
||||
})
|
||||
|
||||
test('hides Instagram cards and keeps articles when the API fails without a snapshot', async ({
|
||||
page,
|
||||
request,
|
||||
}) => {
|
||||
await seedTestUser()
|
||||
const headers = await adminHeaders(request)
|
||||
await setInstagramStubState(request, 'fail')
|
||||
|
||||
const fallbackTag = await createTag(
|
||||
request,
|
||||
headers,
|
||||
`E2e Fallback IG ${runSuffix}`,
|
||||
`e2e-fallback-ig-${runSuffix}`,
|
||||
)
|
||||
await createPost(request, headers, {
|
||||
title: 'E2e Artigo fallback IG',
|
||||
slug: `e2e-artigo-fallback-ig-${runSuffix}`,
|
||||
type: 'noticia',
|
||||
category: fallbackTag.id,
|
||||
publishedDate: new Date(Date.now() - 2 * 60 * 60_000).toISOString(),
|
||||
})
|
||||
await updateSocialFeedSettings(request, headers, {
|
||||
enabled: true,
|
||||
youtubeEnabled: true,
|
||||
youtubeApiKey: '',
|
||||
youtubeChannelId: '',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: 'e2e-ig-token',
|
||||
instagramUserId: '17841400000000000',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
})
|
||||
|
||||
try {
|
||||
// Without a snapshot there is no username to build the profile link
|
||||
// from, so the IG cards AND the "Seguir no Instagram →" link stay
|
||||
// silently absent and the article carries the section (page never
|
||||
// breaks, no error shown).
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
['E2e Artigo fallback IG'],
|
||||
['E2e Post do muro', 'Seguir no Instagram'],
|
||||
)
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
await expect(section.getByRole('link', { name: /E2e Artigo fallback IG/ })).toBeVisible()
|
||||
await expect(section.getByText('E2e Post do muro')).toHaveCount(0)
|
||||
await expect(section.getByRole('link', { name: /Seguir no Instagram/ })).toHaveCount(0)
|
||||
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
} finally {
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await cleanupS2Fixtures(request, headers)
|
||||
}
|
||||
})
|
||||
|
||||
test('keeps the last Instagram snapshot while the API is down', async ({ page, request }) => {
|
||||
await seedTestUser()
|
||||
const headers = await adminHeaders(request)
|
||||
await setInstagramStubState(request, 'ok')
|
||||
const baseSettings = {
|
||||
enabled: true,
|
||||
youtubeEnabled: true,
|
||||
youtubeApiKey: '',
|
||||
youtubeChannelId: '',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: 'e2e-ig-token',
|
||||
instagramUserId: '17841400000000000',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [{ platform: 'instagram', itemId: 'e2e-ig-grade-excluido-5' }],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
}
|
||||
await updateSocialFeedSettings(request, headers, baseSettings)
|
||||
|
||||
try {
|
||||
// Live fetch succeeds and persists the raw snapshot (with the username).
|
||||
await waitForHomeHTML(request, ['E2e Post do muro'], ['E2e Post de grade'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Post do muro/ }).first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
|
||||
// API down + a settings change: the re-execution must serve the snapshot
|
||||
// re-filtered by the CURRENT exclusions/maxItems (raw snapshot, applied
|
||||
// on read) — maxItems 2 proves the re-run read the new settings, and the
|
||||
// profile link survives because the username came from the snapshot. The
|
||||
// snapshot field is OMITTED on purpose: an update merges over the
|
||||
// existing doc (Payload update semantics), so the persisted snapshot
|
||||
// survives the settings edit — exactly the production admin path.
|
||||
await setInstagramStubState(request, 'fail')
|
||||
const { instagramFeedSnapshot: _ignored, ...settingsWithoutSnapshot } = baseSettings
|
||||
await updateSocialFeedSettings(request, headers, {
|
||||
...settingsWithoutSnapshot,
|
||||
instagramMaxItems: 2,
|
||||
})
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
['E2e Post do muro', 'E2e Reel da caravana', 'Seguir no Instagram'],
|
||||
['Publicação no Instagram'],
|
||||
)
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByRole('link', { name: /E2e Post do muro/ }).first()).toBeVisible()
|
||||
await expect(page.getByText('E2e Reel da caravana').first()).toBeVisible()
|
||||
await expect(page.getByText('Publicação no Instagram')).toHaveCount(0)
|
||||
await expect(page.getByRole('link', { name: /Seguir no Instagram/ })).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
|
||||
// API back: the live feed returns with the original cap.
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await updateSocialFeedSettings(request, headers, baseSettings)
|
||||
await waitForHomeHTML(request, ['Publicação no Instagram'], ['E2e Post de grade'])
|
||||
await gotoHomeFresh(page)
|
||||
await expect(page.getByText('Publicação no Instagram').first()).toBeVisible()
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
} finally {
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await cleanupS2Fixtures(request, headers)
|
||||
}
|
||||
})
|
||||
|
||||
test('the kill switch pauses the external feed without touching articles', async ({
|
||||
page,
|
||||
request,
|
||||
|
|
@ -1079,6 +1320,7 @@ test.describe('Campaign home content section', () => {
|
|||
await seedTestUser()
|
||||
const headers = await adminHeaders(request)
|
||||
await setYouTubeStubState(request, 'ok')
|
||||
await setInstagramStubState(request, 'ok')
|
||||
|
||||
const killTag = await createTag(
|
||||
request,
|
||||
|
|
@ -1099,29 +1341,38 @@ test.describe('Campaign home content section', () => {
|
|||
youtubeApiKey: 'e2e-youtube-api-key',
|
||||
youtubeChannelId: 'UCe2eTestChannel',
|
||||
youtubeMaxItems: 3,
|
||||
instagramEnabled: true,
|
||||
instagramAccessToken: 'e2e-ig-token',
|
||||
instagramUserId: '17841400000000000',
|
||||
instagramMaxItems: 3,
|
||||
excludedItems: [],
|
||||
youtubeFeedSnapshot: null,
|
||||
instagramFeedSnapshot: null,
|
||||
})
|
||||
|
||||
try {
|
||||
// `enabled: false` pauses the whole external board: no cards AND no
|
||||
// channel link, while the article section lives on.
|
||||
// platform links (YouTube and Instagram alike), while the article
|
||||
// section lives on.
|
||||
await waitForHomeHTML(
|
||||
request,
|
||||
['E2e Artigo kill switch'],
|
||||
['E2e Vídeo em destaque', 'YouTube →'],
|
||||
['E2e Vídeo em destaque', 'YouTube →', 'E2e Post do muro', 'Seguir no Instagram'],
|
||||
)
|
||||
await page.goto('/')
|
||||
await gotoHomeFresh(page)
|
||||
const section = page.locator('[data-home-section="contents"]')
|
||||
await expect(section).toBeVisible()
|
||||
await expect(section.getByRole('link', { name: /E2e Artigo kill switch/ })).toBeVisible()
|
||||
await expect(section.getByText('E2e Vídeo em destaque')).toHaveCount(0)
|
||||
await expect(section.getByRole('link', { name: /YouTube →/ })).toHaveCount(0)
|
||||
await expect(section.getByText('E2e Post do muro')).toHaveCount(0)
|
||||
await expect(section.getByRole('link', { name: /Seguir no Instagram/ })).toHaveCount(0)
|
||||
|
||||
await page.goto('about:blank')
|
||||
await expect(page).toHaveURL(/about:blank/)
|
||||
} finally {
|
||||
await setYouTubeStubState(request, 'ok')
|
||||
await setInstagramStubState(request, 'ok')
|
||||
await cleanupS2Fixtures(request, headers)
|
||||
}
|
||||
})
|
||||
|
|
|
|||
144
tests/e2e/instagram-stub.mjs
Normal file
144
tests/e2e/instagram-stub.mjs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
/**
|
||||
* Deterministic Instagram Graph API stub for e2e — the campaign home content
|
||||
* board (S3) fetches the feed server-side, so the Next dev/prod server points
|
||||
* `INSTAGRAM_API_BASE_URL` here (see playwright.config.ts) and this process
|
||||
* answers `/media`, `/user` and `/refresh_access_token` with a fixed fixture.
|
||||
* `POST /__stub/state` with `{ "state": "ok" | "fail" }` makes the API fail
|
||||
* (HTTP 500) so specs can exercise the fail-closed/snapshot paths without any
|
||||
* network. Thumbnails are served locally from `/thumbs/<id>.jpg` — the
|
||||
* sandbox never reaches `scontent.cdninstagram.com`, and next/image would 404
|
||||
* (a console error the e2e guard treats as a failure).
|
||||
*/
|
||||
import { createServer } from 'node:http'
|
||||
|
||||
const PORT = Number(process.env.INSTAGRAM_STUB_PORT ?? 5000)
|
||||
const USER_ID = '17841400000000000'
|
||||
const USERNAME = 'depjorgesolla'
|
||||
const ORIGIN = `http://localhost:${PORT}`
|
||||
|
||||
// 1x1 transparent PNG — enough for the optimizer to proxy successfully.
|
||||
const THUMBNAIL_PNG = Buffer.from(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==',
|
||||
'base64',
|
||||
)
|
||||
|
||||
const minutesAgo = (minutes) => new Date(Date.now() - minutes * 60_000).toISOString()
|
||||
|
||||
const POSTS = [
|
||||
{
|
||||
id: 'e2e-ig-muro-1',
|
||||
caption: 'E2e Post do muro',
|
||||
media_type: 'IMAGE',
|
||||
minutesAgo: 20,
|
||||
},
|
||||
{
|
||||
id: 'e2e-ig-reel-2',
|
||||
caption: 'E2e Reel da caravana',
|
||||
media_type: 'REEL',
|
||||
minutesAgo: 90,
|
||||
},
|
||||
{
|
||||
id: 'e2e-ig-sem-legenda-3',
|
||||
caption: null,
|
||||
media_type: 'IMAGE',
|
||||
minutesAgo: 26 * 60,
|
||||
},
|
||||
{
|
||||
id: 'e2e-ig-carrossel-4',
|
||||
caption: 'E2e Carrossel de fotos',
|
||||
media_type: 'CAROUSEL_ALBUM',
|
||||
minutesAgo: 30 * 60,
|
||||
},
|
||||
{
|
||||
id: 'e2e-ig-grade-excluido-5',
|
||||
caption: 'E2e Post de grade',
|
||||
media_type: 'IMAGE',
|
||||
minutesAgo: 5,
|
||||
},
|
||||
]
|
||||
|
||||
const mediaItem = (post) => {
|
||||
const base = `${ORIGIN}/thumbs/${post.id}.jpg`
|
||||
const item = {
|
||||
id: post.id,
|
||||
caption: post.caption,
|
||||
media_type: post.media_type,
|
||||
permalink: `https://www.instagram.com/p/${post.id}/`,
|
||||
timestamp: minutesAgo(post.minutesAgo),
|
||||
media_url: base,
|
||||
thumbnail_url: base,
|
||||
}
|
||||
if (post.media_type === 'CAROUSEL_ALBUM') {
|
||||
item.children = { data: [{ media_url: base, thumbnail_url: base }] }
|
||||
}
|
||||
return item
|
||||
}
|
||||
|
||||
const mediaResponse = () => ({ data: POSTS.map(mediaItem) })
|
||||
|
||||
let state = 'ok'
|
||||
|
||||
const json = (res, status, body) => {
|
||||
res.writeHead(status, { 'content-type': 'application/json' })
|
||||
res.end(JSON.stringify(body))
|
||||
}
|
||||
|
||||
const server = createServer((req, res) => {
|
||||
const url = new URL(req.url, `http://localhost:${PORT}`)
|
||||
|
||||
if (url.pathname === '/__stub/health') {
|
||||
json(res, 200, { ok: true })
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname === '/__stub/state' && req.method === 'POST') {
|
||||
let body = ''
|
||||
req.on('data', (chunk) => {
|
||||
body += chunk
|
||||
})
|
||||
req.on('end', () => {
|
||||
try {
|
||||
const parsed = JSON.parse(body)
|
||||
if (parsed.state === 'ok' || parsed.state === 'fail') state = parsed.state
|
||||
} catch {
|
||||
// keep the current state
|
||||
}
|
||||
json(res, 200, { state })
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (state === 'fail') {
|
||||
res.writeHead(500)
|
||||
res.end('stub fail')
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith('/media')) {
|
||||
json(res, 200, mediaResponse())
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname === '/refresh_access_token') {
|
||||
json(res, 200, { access_token: 'e2e-refreshed-token' })
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname.endsWith(`/${USER_ID}`) || url.pathname === '/user') {
|
||||
json(res, 200, { id: USER_ID, username: USERNAME })
|
||||
return
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith('/thumbs/')) {
|
||||
res.writeHead(200, { 'content-type': 'image/png' })
|
||||
res.end(THUMBNAIL_PNG)
|
||||
return
|
||||
}
|
||||
|
||||
res.writeHead(404)
|
||||
res.end('not found')
|
||||
})
|
||||
|
||||
server.listen(PORT, () => {
|
||||
console.log(`instagram e2e stub listening on :${PORT}`)
|
||||
})
|
||||
|
|
@ -12,9 +12,10 @@
|
|||
/** `teqo_test`, `teqo_wt15_test`, … — the _test suffix is the hard contract. */
|
||||
const TEST_DATABASE_NAME = /^teqo(_[a-z0-9]+)?_test$/
|
||||
|
||||
// Self-hosted Forgejo runner: the job's postgres service is published on the
|
||||
// bridge gateway IP (RFC1918), not localhost. Same source as the CLI guard so
|
||||
// both guards admit exactly the same hosts (OPS50).
|
||||
// Self-hosted Forgejo runner: services are reached by NAME on the job network
|
||||
// (postgres-int / postgres-build, OPS62 X1) or, on the legacy per-port
|
||||
// publish, through the bridge gateway IP (RFC1918). Same source as the CLI
|
||||
// guard so both guards admit exactly the same hosts (OPS50/OPS62).
|
||||
import { defaultGatewayHost } from '../../scripts/lib/cli.mjs'
|
||||
|
||||
export function assertTestDatabase(databaseUrl: string | undefined): void {
|
||||
|
|
@ -33,7 +34,14 @@ export function assertTestDatabase(databaseUrl: string | undefined): void {
|
|||
}
|
||||
|
||||
const databaseName = decodeURIComponent(parsedUrl.pathname.replace(/^\//, ''))
|
||||
const localHosts = new Set(['localhost', '127.0.0.1', '::1', '[::1]'])
|
||||
const localHosts = new Set([
|
||||
'localhost',
|
||||
'127.0.0.1',
|
||||
'::1',
|
||||
'[::1]',
|
||||
'postgres-int',
|
||||
'postgres-build',
|
||||
])
|
||||
const gateway = defaultGatewayHost()
|
||||
if (gateway) localHosts.add(gateway)
|
||||
|
||||
|
|
|
|||
17
tests/helpers/socialStub.ts
Normal file
17
tests/helpers/socialStub.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
/**
|
||||
* Port/URL of the social-feed stubs the e2e board (S2 YouTube, S3 Instagram)
|
||||
* fetches. The single spelling of the derivation: dev servers live in
|
||||
* 3100..4099 (worktree slots, capped at 999), so the offsets never collide
|
||||
* with another worktree's dev server or with each other; CI stays on 4000
|
||||
* (YouTube) and 5000 (Instagram). Shared by playwright.config.ts (webServer +
|
||||
* env) and the frontend spec (state switches) so the two cannot drift apart.
|
||||
*/
|
||||
export const youtubeStubUrlFor = (baseURL: string): string => {
|
||||
const port = new URL(baseURL).port || (baseURL.startsWith('https:') ? '443' : '80')
|
||||
return `http://localhost:${Number(port) + 1000}`
|
||||
}
|
||||
|
||||
export const instagramStubUrlFor = (baseURL: string): string => {
|
||||
const port = new URL(baseURL).port || (baseURL.startsWith('https:') ? '443' : '80')
|
||||
return `http://localhost:${Number(port) + 2000}`
|
||||
}
|
||||
|
|
@ -1,11 +0,0 @@
|
|||
/**
|
||||
* Port/URL of the YouTube Data API stub the e2e board (S2) fetches. The single
|
||||
* spelling of the derivation: dev servers live in 3100..4099 (worktree slots,
|
||||
* capped at 999), so +1000 never collides with another worktree's dev server;
|
||||
* CI stays on 4000. Shared by playwright.config.ts (webServer + env) and the
|
||||
* frontend spec (state switches) so the two cannot drift apart.
|
||||
*/
|
||||
export const youtubeStubUrlFor = (baseURL: string): string => {
|
||||
const port = new URL(baseURL).port || (baseURL.startsWith('https:') ? '443' : '80')
|
||||
return `http://localhost:${Number(port) + 1000}`
|
||||
}
|
||||
194
tests/unit/ciClassifyProduction.unit.spec.ts
Normal file
194
tests/unit/ciClassifyProduction.unit.spec.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { classifyProduction } from '../../scripts/ci-classify-production.mjs'
|
||||
import { parseDockerignore } from '../../scripts/lib/dockerignore.mjs'
|
||||
|
||||
const repoRoot = join(fileURLToPath(new URL('.', import.meta.url)), '../..')
|
||||
const cliPath = join(repoRoot, 'scripts/ci-classify-production.mjs')
|
||||
const realRules = parseDockerignore(readFileSync(join(repoRoot, '.dockerignore'), 'utf8'))
|
||||
|
||||
let fixturesDir: string
|
||||
let filesFrom: string
|
||||
let gitRepo: string
|
||||
let fixtureShas: { baseSha: string; prodSha: string; docsSha: string }
|
||||
|
||||
beforeAll(() => {
|
||||
fixturesDir = mkdtempSync(join(tmpdir(), 'ci-classify-production-'))
|
||||
filesFrom = join(fixturesDir, 'changed.txt')
|
||||
gitRepo = join(fixturesDir, 'repo')
|
||||
execFileSync('git', ['init', '-q', '-b', 'main', gitRepo])
|
||||
writeFileSync(join(gitRepo, '.dockerignore'), 'docs\n')
|
||||
writeFileSync(join(gitRepo, 'README.md'), 'a\n')
|
||||
const commit = (message: string) =>
|
||||
execFileSync('git', [
|
||||
'-C',
|
||||
gitRepo,
|
||||
'-c',
|
||||
'user.name=t',
|
||||
'-c',
|
||||
'user.email=t@t',
|
||||
'commit',
|
||||
'-q',
|
||||
'-m',
|
||||
message,
|
||||
])
|
||||
execFileSync('git', ['-C', gitRepo, 'add', '-A'])
|
||||
commit('base')
|
||||
const baseSha = execFileSync('git', ['-C', gitRepo, 'rev-parse', 'HEAD'], {
|
||||
encoding: 'utf8',
|
||||
}).trim()
|
||||
execFileSync('mkdir', ['-p', join(gitRepo, 'src'), join(gitRepo, 'docs')])
|
||||
writeFileSync(join(gitRepo, 'src', 'a.ts'), 'x\n')
|
||||
writeFileSync(join(gitRepo, 'docs', 'x.md'), 'x\n')
|
||||
execFileSync('git', ['-C', gitRepo, 'add', '-A'])
|
||||
commit('prod change')
|
||||
const prodSha = execFileSync('git', ['-C', gitRepo, 'rev-parse', 'HEAD'], {
|
||||
encoding: 'utf8',
|
||||
}).trim()
|
||||
writeFileSync(join(gitRepo, 'docs', 'y.md'), 'x\n')
|
||||
execFileSync('git', ['-C', gitRepo, 'add', '-A'])
|
||||
commit('docs only')
|
||||
const docsSha = execFileSync('git', ['-C', gitRepo, 'rev-parse', 'HEAD'], {
|
||||
encoding: 'utf8',
|
||||
}).trim()
|
||||
fixtureShas = { baseSha, prodSha, docsSha }
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
execFileSync('rm', ['-rf', fixturesDir])
|
||||
})
|
||||
|
||||
const fixture = () => fixtureShas
|
||||
|
||||
const runCli = (args: string[], options: { cwd?: string } = {}) => {
|
||||
const env = { ...process.env, GITHUB_EVENT_NAME: 'schedule' }
|
||||
const result = spawnSync('node', [cliPath, ...args], {
|
||||
encoding: 'utf8',
|
||||
env,
|
||||
cwd: options.cwd,
|
||||
})
|
||||
return { out: result.stdout.trim(), status: result.status }
|
||||
}
|
||||
|
||||
const writeChanged = (paths: string[]) => writeFileSync(filesFrom, paths.join('\n'))
|
||||
|
||||
describe('classifyProduction (pure)', () => {
|
||||
it('keeps paths the docker build context receives', () => {
|
||||
const { production, kept, skipped } = classifyProduction(
|
||||
['src/app/page.tsx', 'docs/plans/x.md', 'package.json'],
|
||||
realRules,
|
||||
)
|
||||
expect(production).toBe(true)
|
||||
expect(kept).toEqual(['src/app/page.tsx', 'package.json'])
|
||||
expect(skipped).toEqual(['docs/plans/x.md'])
|
||||
})
|
||||
|
||||
it('reports no production change when every path is ignored', () => {
|
||||
const { production, kept, skipped } = classifyProduction(
|
||||
['docs/ops/teqo-1313-deploy.md', '.agents/skills/foo/SKILL.md'],
|
||||
realRules,
|
||||
)
|
||||
expect(production).toBe(false)
|
||||
expect(kept).toEqual([])
|
||||
expect(skipped).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ci-classify-production CLI (OPS65 gate)', () => {
|
||||
it('reports JSON with production, changed, kept and skipped', () => {
|
||||
writeChanged(['docs/plans/x.md', 'src/lib/foo.ts'])
|
||||
const { out, status } = runCli(['--files-from', filesFrom])
|
||||
expect(status).toBe(0)
|
||||
const result = JSON.parse(out)
|
||||
expect(result.production).toBe(true)
|
||||
expect(result.kept).toEqual(['src/lib/foo.ts'])
|
||||
expect(result.skipped).toEqual(['docs/plans/x.md'])
|
||||
})
|
||||
|
||||
it('--value prints only the boolean', () => {
|
||||
writeChanged(['docs/plans/x.md'])
|
||||
expect(runCli(['--files-from', filesFrom, '--value']).out).toBe('false')
|
||||
writeChanged(['src/app/page.tsx'])
|
||||
expect(runCli(['--files-from', filesFrom, '--value']).out).toBe('true')
|
||||
})
|
||||
|
||||
it('an empty diff means nothing to do (production=false)', () => {
|
||||
writeChanged([])
|
||||
const { out, status } = runCli(['--files-from', filesFrom])
|
||||
expect(status).toBe(0)
|
||||
const result = JSON.parse(out)
|
||||
expect(result.production).toBe(false)
|
||||
expect(result.reason).toContain('nada a fazer')
|
||||
})
|
||||
|
||||
it('classifies a real git diff against the deployed revision', () => {
|
||||
const { baseSha, prodSha, docsSha } = fixture()
|
||||
// HEAD is the docs-only commit; from the base SHA the diff mixes the
|
||||
// production change (src/a.ts) with the docs-only commits.
|
||||
const prod = JSON.parse(runCli(['--deployed', baseSha], { cwd: gitRepo }).out)
|
||||
expect(prod.production).toBe(true)
|
||||
expect(prod.changed).toEqual(['docs/x.md', 'docs/y.md', 'src/a.ts'])
|
||||
expect(prod.kept).toEqual(['src/a.ts'])
|
||||
expect(prod.skipped).toEqual(['docs/x.md', 'docs/y.md'])
|
||||
|
||||
const docs = JSON.parse(runCli(['--deployed', prodSha], { cwd: gitRepo }).out)
|
||||
expect(docs.production).toBe(false)
|
||||
expect(docs.skipped).toEqual(['docs/y.md'])
|
||||
|
||||
const same = JSON.parse(runCli(['--deployed', docsSha], { cwd: gitRepo }).out)
|
||||
expect(same.production).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the run green when the deployed SHA is unknown (empty)', () => {
|
||||
const { out, status } = runCli(['--deployed', ''])
|
||||
expect(status).toBe(0)
|
||||
const result = JSON.parse(out)
|
||||
expect(result.production).toBe(true)
|
||||
expect(result.reason).toContain('sem SHA deployado')
|
||||
})
|
||||
|
||||
it('turns the run red when it cannot classify (no input)', () => {
|
||||
const { out, status } = runCli([])
|
||||
expect(status).not.toBe(0)
|
||||
expect(JSON.parse(out).production).toBe(true)
|
||||
})
|
||||
|
||||
it('turns the run red when the deployed revision cannot be diffed', () => {
|
||||
const { out, status } = runCli(['--deployed', 'ffffffffffffffffffffffffffffffffffffffff'], {
|
||||
cwd: gitRepo,
|
||||
})
|
||||
expect(status).not.toBe(0)
|
||||
const result = JSON.parse(out)
|
||||
expect(result.production).toBe(true)
|
||||
expect(result.reason).toContain('erro ao obter o diff')
|
||||
})
|
||||
|
||||
it('turns the run red when the .dockerignore is unreadable', () => {
|
||||
writeChanged(['src/app/page.tsx'])
|
||||
const { out, status } = runCli(['--files-from', filesFrom], { cwd: fixturesDir })
|
||||
expect(status).not.toBe(0)
|
||||
const result = JSON.parse(out)
|
||||
expect(result.production).toBe(true)
|
||||
expect(result.reason).toContain('.dockerignore ilegível')
|
||||
})
|
||||
|
||||
it('workflow_dispatch always runs the full pipeline', () => {
|
||||
const env = { ...process.env, GITHUB_EVENT_NAME: 'workflow_dispatch' }
|
||||
const result = spawnSync('node', [cliPath, '--files-from', filesFrom], {
|
||||
encoding: 'utf8',
|
||||
env,
|
||||
})
|
||||
const parsed = JSON.parse(result.stdout)
|
||||
expect(result.status).toBe(0)
|
||||
expect(parsed.production).toBe(true)
|
||||
expect(parsed.reason).toContain('workflow_dispatch')
|
||||
})
|
||||
})
|
||||
|
|
@ -96,11 +96,14 @@ describe('ciSkipInvariants', () => {
|
|||
for (const path of [
|
||||
'scripts/lib/test-affected-core.mjs',
|
||||
'scripts/ci-scope.mjs',
|
||||
'scripts/ci-classify-production.mjs',
|
||||
'scripts/lib/dockerignore.mjs',
|
||||
'scripts/check-test-locations.mjs',
|
||||
'scripts/check-plans-only-pr-closes.mjs',
|
||||
'scripts/lib/plansOnlyClosesGuard.mjs',
|
||||
'scripts/test-affected.mjs',
|
||||
'scripts/e2e-affected.mjs',
|
||||
'scripts/run-e2e-affected.mjs',
|
||||
'tests/unit/ciSkipInvariants.unit.spec.ts',
|
||||
'tests/unit/testAffected.unit.spec.ts',
|
||||
]) {
|
||||
|
|
@ -108,6 +111,32 @@ describe('ciSkipInvariants', () => {
|
|||
}
|
||||
})
|
||||
|
||||
it('main CI runs in a 30-minute window with a production gate (OPS65)', () => {
|
||||
const ci = readFileSync(join(repoRoot, '.forgejo/workflows/ci.yml'), 'utf8')
|
||||
expect(ci).toContain('schedule:')
|
||||
expect(ci).toContain("cron: '*/30 * * * *'")
|
||||
expect(ci).not.toMatch(/push:\s*\n\s*branches:\s*\[main\]/)
|
||||
expect(ci).toContain('workflow_dispatch:')
|
||||
|
||||
// The cheap gate (no pnpm) classifies production change and every
|
||||
// expensive job consumes it, fail-open on gate errors. The gate is
|
||||
// main-only: a branch dispatch must not run branch code on the host.
|
||||
expect(ci).toContain('gate production change')
|
||||
expect(ci).toContain("if: github.ref == 'refs/heads/main'")
|
||||
expect(ci).toContain('fetch-depth: 0')
|
||||
expect(ci).toContain('scripts/ci-classify-production.mjs')
|
||||
expect(ci).toContain(
|
||||
"needs.gate.result != 'success' || needs.gate.outputs.production == 'true'",
|
||||
)
|
||||
|
||||
// Deploy is double-gated: green rollup AND production change (never
|
||||
// deploy blind, never deploy with a red suite).
|
||||
expect(ci).toContain('needs: [checks, gate]')
|
||||
expect(ci).toContain(
|
||||
"needs.checks.result == 'success' && needs.gate.outputs.production == 'true'",
|
||||
)
|
||||
})
|
||||
|
||||
it('every campaign domain dir is covered by the e2e affected manifest', () => {
|
||||
const componentDirs = readdirSync(join(repoRoot, 'src/components/campaign'), {
|
||||
withFileTypes: true,
|
||||
|
|
|
|||
|
|
@ -496,11 +496,11 @@ describe('src/utilities top-level is pinned', () => {
|
|||
'voteEstimateScenarioFields.ts',
|
||||
'votePledgeData.ts',
|
||||
'votePledgeViews.ts',
|
||||
// S2 — YouTube Data API v3 feed of the campaign home content board
|
||||
// (fetch + cache + snapshot + formatters). A sibling of `posts.ts`, not a
|
||||
// domain subfolder: only one external source so far — the Instagram feed
|
||||
// (S3) would earn a `socialFeed/` subfolder instead of a third top-level.
|
||||
'youtubeFeed.ts',
|
||||
// The campaign home content board's external feeds (YouTube Data API v3
|
||||
// and Instagram Graph API) live in the `socialFeed/` subfolder — the S2
|
||||
// pin predicted it: one external source stayed top-level, the second
|
||||
// earned the domain folder. Fetch + cache + snapshot + formatters, per
|
||||
// platform, siblings of `posts.ts`.
|
||||
])
|
||||
|
||||
it('fails the build on an unregistered top-level module', () => {
|
||||
|
|
|
|||
|
|
@ -22,6 +22,14 @@ describe('scripts/deploy-homeserver.sh (OPS53 deploy pipeline)', () => {
|
|||
expect(script).toContain('stale run')
|
||||
})
|
||||
|
||||
it('skips idempotently when the running container already runs the SHA (OPS65)', () => {
|
||||
expect(script).toContain('already deployed')
|
||||
expect(script).toContain('docker inspect')
|
||||
expect(script).toContain('org.opencontainers.image.revision')
|
||||
expect(script).toContain('$running_rev')
|
||||
expect(script).toContain('"$running_rev" = "$SHA"')
|
||||
})
|
||||
|
||||
it('builds with BuildKit secrets — prod credentials never enter image layers', () => {
|
||||
expect(script).toContain('--secret')
|
||||
expect(script).toContain('id=database_url,env=DATABASE_URL')
|
||||
|
|
|
|||
107
tests/unit/dockerignoreMatch.unit.spec.ts
Normal file
107
tests/unit/dockerignoreMatch.unit.spec.ts
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
compileDockerignoreRule,
|
||||
isDockerignored,
|
||||
parseDockerignore,
|
||||
} from '../../scripts/lib/dockerignore.mjs'
|
||||
|
||||
const repoRoot = join(fileURLToPath(new URL('.', import.meta.url)), '../..')
|
||||
const dockerignore = readFileSync(join(repoRoot, '.dockerignore'), 'utf8')
|
||||
|
||||
describe('dockerignoreMatch (OPS65 production-change gate)', () => {
|
||||
it('compiles the moby semantics: basename at any depth, subtree exclusion', () => {
|
||||
const rules = parseDockerignore('docs\n*.log\n')
|
||||
expect(isDockerignored('docs', rules)).toBe(true)
|
||||
expect(isDockerignored('docs/plans/x.md', rules)).toBe(true)
|
||||
expect(isDockerignored('a/docs/plans/x.md', rules)).toBe(true)
|
||||
expect(isDockerignored('x.log', rules)).toBe(true)
|
||||
expect(isDockerignored('a/b/x.log', rules)).toBe(true)
|
||||
expect(isDockerignored('src/app/page.tsx', rules)).toBe(false)
|
||||
})
|
||||
|
||||
it('anchors leading-slash patterns to the context root', () => {
|
||||
const rules = parseDockerignore('/*.png\n')
|
||||
expect(isDockerignored('a.png', rules)).toBe(true)
|
||||
expect(isDockerignored('sub/b.png', rules)).toBe(false)
|
||||
})
|
||||
|
||||
it('honours ! negations with last-match-wins', () => {
|
||||
const rules = parseDockerignore('.env.*\n!.env.example\n')
|
||||
expect(isDockerignored('.env.local', rules)).toBe(true)
|
||||
expect(isDockerignored('.env.example', rules)).toBe(false)
|
||||
expect(isDockerignored('a/.env.example', rules)).toBe(false)
|
||||
})
|
||||
|
||||
it('supports globstar and directory-only patterns', () => {
|
||||
const rules = parseDockerignore('**/fixtures\na/**/b\n')
|
||||
expect(isDockerignored('x/fixtures/y.json', rules)).toBe(true)
|
||||
expect(isDockerignored('a/b', rules)).toBe(true)
|
||||
expect(isDockerignored('a/x/b', rules)).toBe(true)
|
||||
expect(isDockerignored('a/x/c/b', rules)).toBe(true)
|
||||
})
|
||||
|
||||
it('ignores blank lines and comments', () => {
|
||||
const rules = parseDockerignore('# header\n\ndocs\n')
|
||||
expect(rules).toHaveLength(1)
|
||||
expect(isDockerignored('docs/x', rules)).toBe(true)
|
||||
})
|
||||
|
||||
it('escapes regex metacharacters in plain patterns', () => {
|
||||
const rules = parseDockerignore('foo.bar\n')
|
||||
expect(isDockerignored('foo.bar', rules)).toBe(true)
|
||||
expect(isDockerignored('fooXbar', rules)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats the repo .dockerignore as the source of truth', () => {
|
||||
const rules = parseDockerignore(dockerignore)
|
||||
// Anything the image needs is production: changes force the full suite.
|
||||
for (const path of [
|
||||
'src/app/page.tsx',
|
||||
'src/migrations/20260818_x.ts',
|
||||
'public/favicon.ico',
|
||||
'Dockerfile',
|
||||
'.dockerignore',
|
||||
'AGENTS.md',
|
||||
'package.json',
|
||||
'pnpm-lock.yaml',
|
||||
'scripts/deploy-homeserver.sh',
|
||||
'scripts/ci-classify-production.mjs',
|
||||
'.forgejo/workflows/ci.yml',
|
||||
'.forgejo/workflows/ci-pr.yml',
|
||||
'tests/unit/dockerignoreMatch.unit.spec.ts',
|
||||
'.env.example',
|
||||
]) {
|
||||
expect(isDockerignored(path, rules), path).toBe(false)
|
||||
}
|
||||
// Non-artifact paths skip the suite (quiet days cost seconds).
|
||||
for (const path of [
|
||||
'docs/plans/x.md',
|
||||
'docs/ops/teqo-1313-deploy.md',
|
||||
'.agents/skills/foo/SKILL.md',
|
||||
'.env.local',
|
||||
'.env.test.local',
|
||||
'data/tse/x.zip',
|
||||
'media/x.jpg',
|
||||
'foo.png',
|
||||
'x.log',
|
||||
'x.tsbuildinfo',
|
||||
'node_modules/x',
|
||||
'.next/x',
|
||||
'.next-e2e/x',
|
||||
]) {
|
||||
expect(isDockerignored(path, rules), path).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the .dockerignore itself explicit (self-referential gate)', () => {
|
||||
const rule = compileDockerignoreRule('!.dockerignore')
|
||||
expect(rule.negate).toBe(true)
|
||||
})
|
||||
})
|
||||
|
|
@ -327,6 +327,38 @@ describe('forgejo-api', () => {
|
|||
await expect(api.waitForChecks(4, { pollMs: 1 })).rejects.toThrow(/Checks falharam/)
|
||||
})
|
||||
|
||||
it('waitForChecks throws when a matrix shard is red even if the rollup is green (run 607, OPS64)', async () => {
|
||||
// Forgejo reports the LAST shard's result as the matrix parent result, so
|
||||
// the ci-pr `checks` rollup job can post SUCCESS with e2e (1) red (runs
|
||||
// 604/607/610). The CLI must NEVER trust the rollup alone: it scans the
|
||||
// individual shard statuses (`CI (PR) / e2e (1)` = failure) and refuses to
|
||||
// merge — this is what kept PR #55 out of main red in run 607.
|
||||
const api = createApi({
|
||||
token: 'tok',
|
||||
fetchImpl: async (url) => {
|
||||
if (String(url).includes('/pulls/')) {
|
||||
return ok({
|
||||
number: 55,
|
||||
state: 'open',
|
||||
merged: false,
|
||||
mergeable: true,
|
||||
head: { ref: 'OPS59-x', sha: 'abc' },
|
||||
})
|
||||
}
|
||||
return ok({
|
||||
statuses: [
|
||||
{ context: 'CI / static', status: 'success' },
|
||||
{ context: 'CI (PR) / e2e (1) (pull_request)', status: 'failure' },
|
||||
{ context: 'CI (PR) / e2e (2) (pull_request)', status: 'success' },
|
||||
{ context: 'CI (PR) / checks (pull_request)', status: 'success' },
|
||||
],
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
await expect(api.waitForChecks(55, { pollMs: 1 })).rejects.toThrow(/Checks falharam/)
|
||||
})
|
||||
|
||||
it('waitForChecks ignores the safety-net own status, pending for the whole run (OPS61 finding)', async () => {
|
||||
let statusPoll = 0
|
||||
const api = createApi({
|
||||
|
|
|
|||
337
tests/unit/instagramFeed.unit.spec.ts
Normal file
337
tests/unit/instagramFeed.unit.spec.ts
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { InstagramPost } from '@/utilities/socialFeed/instagramFeed'
|
||||
import {
|
||||
INSTAGRAM_MAX_RESULTS_CAP,
|
||||
eligibleInstagramPosts,
|
||||
loadInstagramFeed,
|
||||
parseInstagramMediaResponse,
|
||||
pickInstagramThumbnail,
|
||||
} from '@/utilities/socialFeed/instagramFeed'
|
||||
|
||||
const MEDIA_ITEM = (
|
||||
id: string,
|
||||
overrides: Record<string, unknown> = {},
|
||||
): Record<string, unknown> => ({
|
||||
id,
|
||||
caption: `Legenda ${id}`,
|
||||
media_type: 'IMAGE',
|
||||
media_url: `https://scontent.cdninstagram.com/${id}.jpg`,
|
||||
permalink: `https://www.instagram.com/p/${id}/`,
|
||||
timestamp: '2026-08-18T10:00:00+00:00',
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('pickInstagramThumbnail', () => {
|
||||
it('uses the media URL for images', () => {
|
||||
expect(pickInstagramThumbnail(MEDIA_ITEM('img'))).toBe(
|
||||
'https://scontent.cdninstagram.com/img.jpg',
|
||||
)
|
||||
})
|
||||
|
||||
it('uses the thumbnail for videos and reels, never the mp4', () => {
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('vid', {
|
||||
media_type: 'VIDEO',
|
||||
media_url: 'https://scontent.cdninstagram.com/vid.mp4',
|
||||
thumbnail_url: 'https://scontent.cdninstagram.com/vid.jpg',
|
||||
}),
|
||||
),
|
||||
).toBe('https://scontent.cdninstagram.com/vid.jpg')
|
||||
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('reel', {
|
||||
media_type: 'REEL',
|
||||
thumbnail_url: 'https://scontent.cdninstagram.com/reel.jpg',
|
||||
}),
|
||||
),
|
||||
).toBe('https://scontent.cdninstagram.com/reel.jpg')
|
||||
})
|
||||
|
||||
it('resolves carousels from the first child that carries a URL', () => {
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('car', {
|
||||
media_type: 'CAROUSEL_ALBUM',
|
||||
children: {
|
||||
data: [
|
||||
{ media_url: 'https://scontent.cdninstagram.com/first.jpg' },
|
||||
{ media_url: 'https://scontent.cdninstagram.com/second.jpg' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe('https://scontent.cdninstagram.com/first.jpg')
|
||||
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('car2', {
|
||||
media_type: 'CAROUSEL_ALBUM',
|
||||
children: {
|
||||
data: [
|
||||
{ thumbnail_url: 'https://scontent.cdninstagram.com/child-video.jpg' },
|
||||
{ media_url: 'https://scontent.cdninstagram.com/child-image.jpg' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe('https://scontent.cdninstagram.com/child-video.jpg')
|
||||
})
|
||||
|
||||
it('reads missing or malformed thumbnails as undefined', () => {
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('no-thumb', { media_type: 'REEL', thumbnail_url: undefined }),
|
||||
),
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('empty-children', { media_type: 'CAROUSEL_ALBUM', children: { data: [] } }),
|
||||
),
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('bad-children', {
|
||||
media_type: 'CAROUSEL_ALBUM',
|
||||
children: { data: ['nope'] },
|
||||
}),
|
||||
),
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
pickInstagramThumbnail(
|
||||
MEDIA_ITEM('no-type', { media_type: undefined, media_url: undefined }),
|
||||
),
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseInstagramMediaResponse', () => {
|
||||
it('parses a valid media response, keeping null captions', () => {
|
||||
const posts = parseInstagramMediaResponse({
|
||||
data: [
|
||||
MEDIA_ITEM('post1'),
|
||||
MEDIA_ITEM('post2', { caption: null, media_type: 'REEL', thumbnail_url: 'thumb.jpg' }),
|
||||
MEDIA_ITEM('post3', {
|
||||
media_type: 'CAROUSEL_ALBUM',
|
||||
children: { data: [{ media_url: 'child.jpg' }] },
|
||||
}),
|
||||
],
|
||||
})
|
||||
expect(posts).toHaveLength(3)
|
||||
expect(posts[0]).toEqual({
|
||||
id: 'post1',
|
||||
caption: 'Legenda post1',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://www.instagram.com/p/post1/',
|
||||
thumbnailUrl: 'https://scontent.cdninstagram.com/post1.jpg',
|
||||
timestamp: '2026-08-18T10:00:00+00:00',
|
||||
})
|
||||
expect(posts[1].caption).toBeNull()
|
||||
expect(posts[1].thumbnailUrl).toBe('thumb.jpg')
|
||||
expect(posts[2].thumbnailUrl).toBe('child.jpg')
|
||||
})
|
||||
|
||||
it('drops items without id, permalink or timestamp but throws on protocol violations', () => {
|
||||
expect(
|
||||
parseInstagramMediaResponse({
|
||||
data: [
|
||||
MEDIA_ITEM('ok'),
|
||||
{ ...MEDIA_ITEM('no-permalink'), permalink: undefined },
|
||||
{ ...MEDIA_ITEM('no-timestamp'), timestamp: undefined },
|
||||
{ id: 'no-caption', permalink: 'https://instagram.com/p/x/', timestamp: 't' },
|
||||
'malformed',
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
expect.objectContaining({ id: 'ok' }),
|
||||
expect.objectContaining({ id: 'no-caption', caption: null }),
|
||||
])
|
||||
|
||||
expect(() => parseInstagramMediaResponse({})).toThrow()
|
||||
expect(() => parseInstagramMediaResponse(null)).toThrow()
|
||||
expect(() => parseInstagramMediaResponse({ data: 'nope' })).toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('eligibleInstagramPosts', () => {
|
||||
const posts: InstagramPost[] = [
|
||||
{
|
||||
id: 'a',
|
||||
caption: 'A',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://instagram.com/p/a/',
|
||||
timestamp: 't1',
|
||||
},
|
||||
{
|
||||
id: 'b',
|
||||
caption: 'B',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://instagram.com/p/b/',
|
||||
timestamp: 't2',
|
||||
},
|
||||
{
|
||||
id: 'c',
|
||||
caption: 'C',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://instagram.com/p/c/',
|
||||
timestamp: 't3',
|
||||
},
|
||||
{
|
||||
id: 'd',
|
||||
caption: 'D',
|
||||
mediaType: 'IMAGE',
|
||||
permalink: 'https://instagram.com/p/d/',
|
||||
timestamp: 't4',
|
||||
},
|
||||
]
|
||||
|
||||
it('drops excluded ids and caps at maxItems, keeping API order', () => {
|
||||
expect(eligibleInstagramPosts(posts, ['b'], 2)).toEqual([posts[0], posts[2]])
|
||||
expect(eligibleInstagramPosts(posts, [], 3)).toEqual(posts.slice(0, 3))
|
||||
expect(eligibleInstagramPosts(posts, ['a', 'b', 'c', 'd'], 5)).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('loadInstagramFeed', () => {
|
||||
const fakeResponse = (body: unknown, ok = true): Response =>
|
||||
({ ok, json: async () => body }) as unknown as Response
|
||||
|
||||
const calls: string[] = []
|
||||
const fetchImpl = async (input: string): Promise<Response> => {
|
||||
calls.push(input)
|
||||
if (input.includes('/media')) {
|
||||
return fakeResponse({
|
||||
data: [
|
||||
MEDIA_ITEM('post1', { caption: 'Post 1' }),
|
||||
MEDIA_ITEM('post2', { caption: 'Post 2' }),
|
||||
],
|
||||
})
|
||||
}
|
||||
if (input.includes('/refresh_access_token')) {
|
||||
return fakeResponse({ access_token: 'refreshed-token' })
|
||||
}
|
||||
return fakeResponse({ username: 'depjorgesolla' })
|
||||
}
|
||||
|
||||
const args = {
|
||||
accessToken: 'test-token',
|
||||
userId: '17841400000000000',
|
||||
maxResults: 3,
|
||||
fetchImpl,
|
||||
baseUrl: 'http://localhost:5000',
|
||||
}
|
||||
|
||||
it('fetches user then media and resolves the thumbnail per type', async () => {
|
||||
calls.length = 0
|
||||
const result = await loadInstagramFeed(args)
|
||||
|
||||
expect(result.username).toBe('depjorgesolla')
|
||||
expect(result.refreshedAccessToken).toBeUndefined()
|
||||
expect(result.posts).toEqual([
|
||||
expect.objectContaining({ id: 'post1', caption: 'Post 1' }),
|
||||
expect.objectContaining({ id: 'post2' }),
|
||||
])
|
||||
|
||||
const userCall = calls[0]
|
||||
expect(userCall).toContain(`/17841400000000000?`)
|
||||
expect(userCall).toContain('fields=username')
|
||||
expect(userCall).toContain(`access_token=test-token`)
|
||||
expect(calls[1]).toContain('/media?')
|
||||
expect(calls[1]).toContain('fields=id%2Ccaption%2Cmedia_type%2Cmedia_url')
|
||||
expect(calls[1]).toContain('children%7Bmedia_url%2Cthumbnail_url%7D')
|
||||
expect(calls[1]).toContain('limit=3')
|
||||
})
|
||||
|
||||
it('clamps maxResults to the API cap and the minimum of 1', async () => {
|
||||
calls.length = 0
|
||||
await loadInstagramFeed({ ...args, maxResults: 100 })
|
||||
expect(calls[1]).toContain(`limit=${INSTAGRAM_MAX_RESULTS_CAP}`)
|
||||
|
||||
calls.length = 0
|
||||
await loadInstagramFeed({ ...args, maxResults: 0 })
|
||||
expect(calls[1]).toContain('limit=1')
|
||||
})
|
||||
|
||||
it('refreshes the token once and retries when the media call fails', async () => {
|
||||
calls.length = 0
|
||||
let mediaFailures = 1
|
||||
const result = await loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async (input) => {
|
||||
calls.push(input)
|
||||
if (input.includes('/media')) {
|
||||
if (mediaFailures > 0) {
|
||||
mediaFailures -= 1
|
||||
return fakeResponse({ error: { code: 190 } }, false)
|
||||
}
|
||||
return fakeResponse({ data: [MEDIA_ITEM('post-retry')] })
|
||||
}
|
||||
if (input.includes('/refresh_access_token')) {
|
||||
return fakeResponse({ access_token: 'refreshed-token' })
|
||||
}
|
||||
return fakeResponse({ username: 'depjorgesolla' })
|
||||
},
|
||||
})
|
||||
|
||||
expect(result.refreshedAccessToken).toBe('refreshed-token')
|
||||
expect(result.posts).toEqual([expect.objectContaining({ id: 'post-retry' })])
|
||||
const refreshCall = calls.find((call) => call.includes('/refresh_access_token'))
|
||||
expect(calls.filter((call) => call.includes('/refresh_access_token'))).toHaveLength(1)
|
||||
expect(calls.filter((call) => call.includes('/media'))).toHaveLength(2)
|
||||
expect(refreshCall).toContain('grant_type=ig_refresh_token')
|
||||
expect(refreshCall).toContain('access_token=test-token')
|
||||
})
|
||||
|
||||
it('throws when the refresh fails or returns no token (fail-closed to the snapshot)', async () => {
|
||||
await expect(
|
||||
loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async () => fakeResponse({}, false),
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
await expect(
|
||||
loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async (input) =>
|
||||
input.includes('/media') ? fakeResponse({}, false) : fakeResponse({}, true),
|
||||
}),
|
||||
).rejects.toThrow(/refresh/)
|
||||
|
||||
await expect(
|
||||
loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async (input) =>
|
||||
input.includes('/media') ? fakeResponse({}, false) : fakeResponse({ nope: true }),
|
||||
}),
|
||||
).rejects.toThrow(/sem novo token/)
|
||||
})
|
||||
|
||||
it('throws on protocol violations and a failed retry', async () => {
|
||||
await expect(
|
||||
loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async () => fakeResponse({ data: 'nope' }),
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
|
||||
await expect(
|
||||
loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async (input) =>
|
||||
input.includes('/media') ? fakeResponse({}, false) : fakeResponse({}, false),
|
||||
}),
|
||||
).rejects.toThrow()
|
||||
})
|
||||
|
||||
it('reads a missing or malformed username as null', async () => {
|
||||
const result = await loadInstagramFeed({
|
||||
...args,
|
||||
fetchImpl: async (input) =>
|
||||
input.includes('/media') ? fakeResponse({ data: [MEDIA_ITEM('p')] }) : fakeResponse({}),
|
||||
})
|
||||
expect(result.username).toBeNull()
|
||||
})
|
||||
})
|
||||
|
|
@ -4,18 +4,23 @@ import { describe, expect, it } from 'vitest'
|
|||
|
||||
import { defaultGatewayHost, LOCAL_HOSTS } from '../../scripts/lib/cli.mjs'
|
||||
|
||||
describe('LOCAL_HOSTS (OPS50 — self-hosted runner reaches services via the bridge gateway)', () => {
|
||||
describe('LOCAL_HOSTS (OPS50/OPS62 — self-hosted runner services by name, legacy gateway)', () => {
|
||||
it('still contains the canonical static hosts', () => {
|
||||
for (const host of ['localhost', '127.0.0.1', '0.0.0.0', '::1', 'postgres']) {
|
||||
expect(LOCAL_HOSTS.has(host)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('admits the job-network service names (OPS62 X1: no host publish)', () => {
|
||||
expect(LOCAL_HOSTS.has('postgres-int')).toBe(true)
|
||||
expect(LOCAL_HOSTS.has('postgres-build')).toBe(true)
|
||||
})
|
||||
|
||||
it('admits the machine default gateway when it is RFC1918 (Linux CI bridge)', () => {
|
||||
const gateway = defaultGatewayHost()
|
||||
if (gateway) {
|
||||
// The Forgejo runner publishes the job's postgres service on the bridge
|
||||
// gateway IP; assertLocalDatabase must accept it so seeds run in CI.
|
||||
// The Forgejo runner published the job's postgres service on the bridge
|
||||
// gateway IP before OPS62; assertLocalDatabase must still accept it.
|
||||
expect(LOCAL_HOSTS.has(gateway)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
|
@ -24,5 +29,6 @@ describe('LOCAL_HOSTS (OPS50 — self-hosted runner reaches services via the bri
|
|||
expect(LOCAL_HOSTS.has('8.8.8.8')).toBe(false)
|
||||
expect(LOCAL_HOSTS.has('127.0.0.2')).toBe(false)
|
||||
expect(LOCAL_HOSTS.has('203.0.113.1')).toBe(false)
|
||||
expect(LOCAL_HOSTS.has('postgres-prod')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
101
tests/unit/playwrightE2eArgs.unit.spec.ts
Normal file
101
tests/unit/playwrightE2eArgs.unit.spec.ts
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
buildPlaywrightE2eArgs,
|
||||
parsePassthroughArgs,
|
||||
} from '../../scripts/lib/playwright-e2e-args.mjs'
|
||||
|
||||
// S6-FOLLOWUP (2026-08-18): the e2e CLI filters WERE ignored locally because
|
||||
// the dev-mode project dependency chain drags every dependency project's files
|
||||
// into a selected run (buildProjectsClosure). The helpers pin the generated
|
||||
// argv: `--no-deps` on filtered runs only (full runs keep the OPS34 dev
|
||||
// chain), generated scope paths after the `--` separator, and a verbatim
|
||||
// passthrough (pnpm consumes the first `--`, so the script never sees it; flag
|
||||
// values like `-g grade` must not be re-classified).
|
||||
describe('parsePassthroughArgs', () => {
|
||||
it('returns nothing for a plain invocation', () => {
|
||||
expect(parsePassthroughArgs(['node', 'scripts/run-e2e-affected.mjs'])).toEqual([])
|
||||
})
|
||||
|
||||
it('keeps bare args when pnpm consumed the `--` separator', () => {
|
||||
expect(
|
||||
parsePassthroughArgs(['node', 'scripts/run-e2e-affected.mjs', 'tests/x.e2e.spec.ts']),
|
||||
).toEqual(['tests/x.e2e.spec.ts'])
|
||||
})
|
||||
|
||||
it('strips exactly one leading `--` (direct invocation with separator)', () => {
|
||||
expect(
|
||||
parsePassthroughArgs(['node', 'scripts/run-e2e-affected.mjs', '--', '-g', 'grade']),
|
||||
).toEqual(['-g', 'grade'])
|
||||
})
|
||||
|
||||
it('keeps flags and flag values verbatim', () => {
|
||||
expect(
|
||||
parsePassthroughArgs([
|
||||
'node',
|
||||
'scripts/run-e2e-affected.mjs',
|
||||
'--grep=home',
|
||||
'-g',
|
||||
'grade',
|
||||
'--',
|
||||
'tests/x.e2e.spec.ts',
|
||||
]),
|
||||
).toEqual(['--grep=home', '-g', 'grade', '--', 'tests/x.e2e.spec.ts'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildPlaywrightE2eArgs', () => {
|
||||
it('keeps the full-suite form when nothing is filtered (dev chain intact)', () => {
|
||||
expect(buildPlaywrightE2eArgs({ scopeSpecPaths: [], passthroughArgs: [] })).toEqual([
|
||||
'test:e2e',
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps non-filter flags on the full-suite form (shards, reporters, workers)', () => {
|
||||
expect(buildPlaywrightE2eArgs({ passthroughArgs: ['--shard=1/2', '--reporter=line'] })).toEqual(
|
||||
['test:e2e', '--shard=1/2', '--reporter=line'],
|
||||
)
|
||||
})
|
||||
|
||||
it('disables the dependency closure and separates generated paths with -- on filtered runs', () => {
|
||||
expect(
|
||||
buildPlaywrightE2eArgs({ scopeSpecPaths: ['tests/e2e/campaignHomeActions.e2e.spec.ts'] }),
|
||||
).toEqual(['test:e2e', '--no-deps', '--', 'tests/e2e/campaignHomeActions.e2e.spec.ts'])
|
||||
})
|
||||
|
||||
it('treats a bare passthrough path as a filtered run and adds --no-deps', () => {
|
||||
expect(buildPlaywrightE2eArgs({ passthroughArgs: ['tests/e2e/frontend.e2e.spec.ts'] })).toEqual(
|
||||
['test:e2e', 'tests/e2e/frontend.e2e.spec.ts', '--no-deps'],
|
||||
)
|
||||
})
|
||||
|
||||
it('treats filter flags (--project, -g/--grep) as filtered runs', () => {
|
||||
expect(buildPlaywrightE2eArgs({ passthroughArgs: ['--project=campaign'] })).toEqual([
|
||||
'test:e2e',
|
||||
'--project=campaign',
|
||||
'--no-deps',
|
||||
])
|
||||
expect(buildPlaywrightE2eArgs({ passthroughArgs: ['-g', 'grade'] })).toEqual([
|
||||
'test:e2e',
|
||||
'-g',
|
||||
'grade',
|
||||
'--no-deps',
|
||||
])
|
||||
})
|
||||
|
||||
it('does not duplicate an explicit --no-deps passthrough', () => {
|
||||
expect(buildPlaywrightE2eArgs({ passthroughArgs: ['--no-deps'] })).toEqual([
|
||||
'test:e2e',
|
||||
'--no-deps',
|
||||
])
|
||||
})
|
||||
|
||||
it('merges scope paths and passthrough positionals in a single filtered run', () => {
|
||||
expect(
|
||||
buildPlaywrightE2eArgs({
|
||||
scopeSpecPaths: ['tests/e2e/a.e2e.spec.ts'],
|
||||
passthroughArgs: ['tests/e2e/b.e2e.spec.ts'],
|
||||
}),
|
||||
).toEqual(['test:e2e', 'tests/e2e/b.e2e.spec.ts', '--no-deps', '--', 'tests/e2e/a.e2e.spec.ts'])
|
||||
})
|
||||
})
|
||||
|
|
@ -1,16 +1,11 @@
|
|||
// @vitest-environment node
|
||||
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
classifyBuildScope,
|
||||
classifyStaticScope,
|
||||
classifyTestScope,
|
||||
e2eShardConfig,
|
||||
HIGH_RISK_EXACT,
|
||||
HIGH_RISK_PREFIXES,
|
||||
selectE2eSpecs,
|
||||
|
|
@ -153,21 +148,3 @@ describe('selectE2eSpecs (OPS5)', () => {
|
|||
expect(result.specs).toContain('admin')
|
||||
})
|
||||
})
|
||||
|
||||
describe('e2eShardConfig (OPS34)', () => {
|
||||
it('splits the full suite across 2 shards', () => {
|
||||
expect(e2eShardConfig('full')).toEqual({ matrix: [1, 2], total: 2 })
|
||||
})
|
||||
|
||||
it('keeps selected and skipped runs on a single runner', () => {
|
||||
expect(e2eShardConfig('selected')).toEqual({ matrix: [1], total: 1 })
|
||||
expect(e2eShardConfig('none')).toEqual({ matrix: [1], total: 1 })
|
||||
})
|
||||
|
||||
it('pins the ci.yml matrix literal against the single source', () => {
|
||||
const repoRoot = join(fileURLToPath(new URL('.', import.meta.url)), '../..')
|
||||
const workflow = readFileSync(join(repoRoot, '.forgejo/workflows/ci.yml'), 'utf8')
|
||||
const { matrix } = e2eShardConfig('full')
|
||||
expect(workflow).toContain(`shard: [${matrix.join(', ')}]`)
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import type { YouTubeVideo } from '@/utilities/youtubeFeed'
|
||||
import type { YouTubeVideo } from '@/utilities/socialFeed/youtubeFeed'
|
||||
import {
|
||||
YOUTUBE_MAX_RESULTS_CAP,
|
||||
eligibleYouTubeVideos,
|
||||
|
|
@ -9,7 +9,7 @@ import {
|
|||
parseYouTubeSearchResponse,
|
||||
parseYouTubeVideosResponse,
|
||||
pickThumbnailUrl,
|
||||
} from '@/utilities/youtubeFeed'
|
||||
} from '@/utilities/socialFeed/youtubeFeed'
|
||||
|
||||
const SEARCH_ITEM = (videoId: string, title: string, publishedAt: string, extra?: object) => ({
|
||||
id: { videoId },
|
||||
|
|
|
|||
Loading…
Reference in a new issue