Commit Graph

45 Commits

Author SHA1 Message Date
cbf8227dc4 docs(v1.0): close out — 4/4 fases shipped, 581 tests green, tag v1.0.0
Some checks failed
CI / Lint & Type-check (push) Has been cancelled
Deploy / Build & Push Docker image (push) Has been cancelled
CI / Build (push) Has been cancelled
Deploy / Deploy to production (push) Has been cancelled
Final test totals after v1.0 (Fase 17 → 20):
- pgTAP:               196 (was 177 → +19)
- Vitest integration:  187 (was 179 → +8)
- Vitest unit:          89 (was  52 → +37)
- Playwright e2e:      108 (was  96 → +12)
- Rate-limit gated:      1
- Total active:        581 (was 505 → +76)
- Skipped:               3 (unchanged: 2 Realtime presence + 1 gated)

Cycle summary:
- Fase 17 — semver tags + CHANGELOG + about modal + deploy tag check
- Fase 18 — required title + #N auto-numbering + default + title catalog
- Fase 19 — emoji picker with food + animals categories
- Fase 20 — Euskera locale (machine-translated seed pending native review)

Tag v1.0.0 cut from commit d1f6d3a (CHANGELOG flushed, package.json
bumped). Local only; not pushed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 04:36:38 +02:00
4832981e25 docs(fase-17): history doc + bump version to 1.0.0-rc.0
Closes Fase 17 (v1.0 · 1/4). Bumps package.json `version` to
`1.0.0-rc.0` — picked up by apps/web/vite.config.ts's `__APP_VERSION__`
define, so the next built bundle reads it. The plain `1.0.0` tag is
reserved for the close of Fase 20 (Euskera locale) per the v1.0 plan.

Updates CLAUDE.md to mark the v1.0 cycle as in-progress (1/4 ) and
adds the per-fase history docs (Fase 13–17) to the documentation map.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 01:48:09 +02:00
427fe33c9c docs(plan): v1.0 cycle — fases 17–20 (versioning + list flow + emojis + euskera)
Four planned-fase docs for the first tagged release.

- Fase 17 — semver git tags + CHANGELOG.md (Keep-a-Changelog, [new]/
  [fix]/[tweak] prefixes), one big v0.0.0-beta backfill block covering
  Fases 0–16, About-modal in /settings rendering bundled CHANGELOG via
  ?raw import, deploy-script tag check + tag column in .deploys.log.
- Fase 18 — shopping list flow: required title (client + DB tighten),
  per-collective per-prefix #N auto-numbering parsed from typed title,
  collectives.default_list_title, collective_list_titles catalog + admin
  RPCs, autocomplete union (catalog + last-10). Migration 027.
- Fase 19 — EMOJI_CATALOG with faces/food/animals/objects categories
  (~280 codepoints, Unicode 14 baseline for iOS<17 compat), new
  EmojiPicker.svelte replacing the 8-emoji hardcoded selector at 4
  sites. No migration.
- Fase 20 — Euskera locale: messages/eu.json via machine-translate
  seed flagged with [needs review], users.language check constraint
  extended to ('en','es','eu'), accept-language parser + selector in
  /settings. Migration 028. v1.0.0 tag lands at the end of this fase.

README + CLAUDE.md updated with the v1.0 cycle pointers.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-19 01:01:34 +02:00
40a59ef581 docs(mvp2): close out — 8/8 fases shipped, 505 tests green
Fase 16 (loading spinner) lands; MVP2 cycle complete.

Final test totals after MVP2 (Fase 9 → 16):
- pgTAP:               177 (was 45 → +132)
- Vitest integration:  179 (was 140 → +39)
- Vitest unit:          52 (was 15  → +37)
- Playwright e2e:       96 (was 59  → +37)
- Rate-limit gated:      1
- Total active:        505 (was 259 → +246)
- Skipped:               3 (unchanged)

12 new migrations (015 → 026). 10 new pgTAP files (009 → 018).
8 history docs under docs/history/fase-{9,10,11,12,13,14,15,16}-*.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 14:45:16 +02:00
51e62ecba3 docs(plan): add Fase 16 — loading spinner (MVP2 reopened to 8 fases)
Adds a tiny planned-phase doc for visual feedback during async operations.

- Single SVG-circle Spinner.svelte component, three sizes (sm/md/lg = 16
  / 24 / 40 px), color via currentColor (theme-aware), motion-reduce-aware,
  role="status" + sr-only m.loading() for a11y.
- Integration at 5 existing sites that already render m.loading() text or
  own a `loading` flag: auth splash, /search, /notes/archive,
  CreateCollectiveModal "creating" state, /collective/manage sub-sections.
- 5 unit + 3 e2e tests planned. No DB migration. No new Paraglide strings.

Rebrand: MVP2 reopens from 7/7  to in-progress 7/8 . Headers in fases
9–15 bump "·N/7" + "fases 9 → 15" to "·N/8" + "fases 9 → 16". README +
CLAUDE.md updated.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 13:34:58 +02:00
3c60e5a026 docs(mvp2): close out — 7/7 fases shipped, 497 tests green
Fase 15 (common items management) lands; MVP2 cycle complete.

Final test totals after MVP2 (Fase 9 → 15):
- pgTAP:               177 (was 45 → +132)
- Vitest integration:  179 (was 140 → +39)
- Vitest unit:          47 (was 15  → +32)
- Playwright e2e:       93 (was 59  → +34)
- Rate-limit gated:      1
- Total active:        497 (was 259 → +237)
- Skipped:               3 (unchanged)

Migrations 015 → 026 (12 new). pgTAP 009 → 018 (10 new files).
Per-fase history docs under docs/history/fase-{9,10,11,12,13,14,15}-*.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 12:40:34 +02:00
b994fc7c95 docs(plan): add Fase 15 — common items management (MVP2 reopened to 7 fases)
Adds a planned-phase doc for the next ask on top of the closed MVP2 cycle:
weighted suggestion ordering + exclude items already on the active list.

- Extends item_frequency (migration 026) with `weight integer` written via
  two admin-only SECURITY DEFINER RPCs (set_item_frequency_weight +
  purge_item_frequency). The client never writes weight directly — the
  existing all-deny policies on item_frequency stay in place.
- fetchSuggestions reorders by `weight desc, use_count desc, last_used_at
  desc` and accepts an excludeNames arg to drop already-added items from
  the dropdown.
- UI lives in /collective/manage as a 3-way segmented control per row
  (Hide / Normal / Boost mapping to -50 / 0 / 50). Admin writes; member
  read-only; guest hidden.

Rebrand: MVP2 reopens from 6/6  to in-progress 6/7 , with Fase 15
pending. Headers in fases 9–14 bump from "·N/6" + "fases 9 → 14" to
"·N/7" + "fases 9 → 15". README status table + index updated, CLAUDE.md
project status appends the Fase 15 pending paragraph.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 11:08:00 +02:00
d9d5f780c1 docs(mvp2): close out — 6/6 fases shipped, 476 tests green
Final test totals after MVP2:
- pgTAP:               166 (was 45 → +121)
- Vitest integration:  173 (was 140 → +33)
- Vitest unit:          47 (was 15  → +32)
- Playwright e2e:       89 (was 59  → +30)
- Rate-limit gated:      1
- Total active:        476 (was 259 → +217)
- Skipped:               3 (unchanged: 2 Realtime presence + 1 gated)

Cycle summary:
- Fase 9  — dark mode + max-w-2xl + sync_conflicts + WebKit project
- Fase 10 — H06/H07/H08 + trash restore + account delete + sidebar create
            + reset-from-detail + auto language detection
- Fase 11 — item tags + drag-reorder
- Fase 12 — section visibility (feature flags, JSONB + section_enabled())
- Fase 13 — server admin (/admin, server_admins, audit log, server-layer
            section_enabled extension)
- Fase 14 — PWA auto-update toast + offline polish + version chip

Migrations 015 → 025 (11 new). pgTAP 009 → 017 (9 new files).
Per-fase history docs under docs/history/fase-{9,10,11,12,13,14}-*.md.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 07:39:54 +02:00
0485ccc75e docs(fase-13): history doc + deployment server admin runbook + CLAUDE.md status
Wraps Fase 13:
  - docs/history/fase-13-server-admin.md captures the full fase
    breakdown (model, RPCs, UI, store wiring, tests, verification,
    deviations from plan, scope out).
  - docs/deployment.md gains a Server administration section with the
    SERVER_ADMIN_EMAIL bootstrap recipe + the "first prod boot has no
    users yet" gotcha + manual re-run command (with the </dev/null
    redirect for the heredoc-stdin gotcha) + last-admin guard note +
    audit log query snippet.
  - CLAUDE.md "Project Status" updated: MVP2 now 5/6, Fase 13 , test
    totals, the one pre-existing SV-02 flake noted.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 06:26:51 +02:00
99096f9f4a docs(fase-12): history doc + CLAUDE.md status + new-section convention
Adds docs/history/fase-12-section-visibility.md describing the
COALESCE-precedence design that keeps Fase 13's server-settings layer
to a one-line diff, the realtime publication addition that SV-02
forced, and the hermetic test-reset deviation from the plan.

Updates CLAUDE.md project status (2/6 → 4/6 since Fase 11 and 12 both
shipped on the mvp2 branch) and adds the "new top-level section requires"
rule under Domain Model.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 04:45:36 +02:00
a868b5a314 docs(fase-10): history doc + CLAUDE.md status + plan closed
Records the closing state of Fase 10: spec coverage now 100% on the
H-series CUs, full FK on-delete audit table, 5 architectural decisions
(Keycloak not cleaned up on account delete, sole-member must dissolve,
type-the-name dissolve confirmation, client-side language detection,
trash via RPC). Bumps the MVP2 progress to 2/6 and the test totals
to 360 active + 3 skipped.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 02:43:29 +02:00
6cb13146f5 docs(fase-9): history doc + CLAUDE.md status + plan closed
- docs/history/fase-9-polish-dark-mode.md captures the final palette
  (hex + contrast ratios), the four sub-fases (dark mode / reading
  width / sync_conflicts / WebKit specs), the test-count delta
  (259 → 300 + 3 skipped, +41 specs), the upstream-bug audit for
  Realtime presence (#1617 still open as of 2026-05-18, latest stable
  v2.86.3), and the prod-migration note (existing sessions do not
  need a re-login because users.theme is queried, not in the JWT).
- CLAUDE.md project-status line flips Fase 9 to complete, bumps the
  test totals to 300 green / 3 skipped, and adds a new "Testing"
  gotcha for the WebKit project gate (RUN_WEBKIT=1 + libicu74 deps).
- plan/fase-9 marks the phase  with a one-liner about new test counts.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:53:02 +02:00
93153cd750 docs(plan): brand fases 9–14 as MVP2
Stamps the six planned post-MVP fases as the MVP2 cycle (matching the
`mvp2` branch name). Each plan file gets an "MVP2 · N/6" header. README
status + index tables group them under an MVP2 bracket. CLAUDE.md project
status reframes the planned line as MVP2 and clarifies that Fase 7+8
shipped as MVP cleanup, not MVP2.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 00:42:08 +02:00
6e0814169d docs(plan): fases 11–14 — tags, section visibility, server admin, PWA hardening
Adds four planned-phase docs covering the next post-MVP roadmap:

- Fase 11 — item tags (collective-scoped) + drag-reorder UI for the
  existing `shopping_items.sort_order` column. Migration 021.
- Fase 12 — section visibility via JSONB `feature_flags` on `users` and
  `collectives`, with a `section_enabled()` SQL helper that resolves
  precedence (collective > user > default ON). Migration 022.
- Fase 13 — `/admin` area with a global `server_admins` role, append-only
  `admin_actions` audit log, RPCs for collective CRUD + member removal,
  and server-level section-visibility defaults that sit above Fase 12.
  Migrations 023+024. Depends on Fase 12.
- Fase 14 — PWA hardening: `onNeedRefresh` update toast, explicit offline
  indicator + sync queue badge + conflict surface, `__APP_VERSION__` and
  `__APP_COMMIT__` baked at build with a chip in `/settings`. No migration.
  Depends on Fase 9.3 (`sync_conflicts` wiring).

Also bumps CLAUDE.md project status with the planned-fases pointer, and
brings README.md status + index tables in line with Fase 7, 8, 9, 10
(previously missing) plus the four new ones.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 00:38:23 +02:00
d4a781ddcf deploy(prod): swap NetBird-Traefik labels for off-stack proxy + internal Caddy
The stack no longer talks to any specific external proxy. Removed traefik.*
labels and the shared `traefik` external network from kong + app, and dropped
TRAEFIK_NETWORK / TRAEFIK_ENTRYPOINT / TRAEFIK_CERTRESOLVER from the .env
template and the deploy-script bootstrap.

Internal edge is a `caddy:2-alpine` container on the `colectivo` network,
publishing host port 3000. `infra/Caddyfile.erosi` does the path split:
/rest|/auth|/realtime|/storage|/graphql|/pg -> kong:8000, everything else
-> app:3000. Global block sets `auto_https off` + `admin off` so :3000 is
the only listener.

Whatever proxy fronts the host (NetBird's Traefik, nginx, anything) just
terminates TLS for erosi.limonia.net and forwards plain HTTP to
ambrosio:3000. Off-stack and out of this repo.

Docs (CLAUDE.md + docs/deployment.md) updated to describe the two-layer
edge. Includes the gotcha that bind-mounted file edits (Caddyfile) need
`docker compose restart caddy` since `up -d` won't recreate the container
on file-only changes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 22:26:06 +02:00
dee9ee8014 docs(deploy): runbook + fixes from the limonia.net cutover
Document what we learned doing the real NetBird+Traefik migration:

- Keycloak realm/client names are operator-chosen; the realm-export.json's
  literal "colectivo-web" / "colectivo" values are illustrative, not required.
- Legacy Keycloak /auth/ base path: PUBLIC_KEYCLOAK_URL must include the
  suffix when the deployment serves realms under /auth/realms/... (hit this
  on auth.fosil.eu). Verify with the discovery URL returning 200.
- NetBird's installer deploys Traefik with idleTimeout=0 (unlimited) by
  default — verify instead of prescribing 3600s.
- Runbook: --no-cache fixes the intermittent vite SSR "transforming..."
  hang that surfaces as a PostHog shutdown timeout.
- Runbook: any PUBLIC_* change needs an app rebuild (build args); secret
  changes only need `docker compose restart auth`.
- Runbook: TRUNCATE recipe for wiping all app + auth data while keeping
  schema + migration tracking intact.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-24 01:58:00 +02:00
33b32cae4a deploy(prod): swap host Caddy for NetBird-Traefik labels + external Keycloak
Ambrosio's TLS is now handled by the Traefik that NetBird's self-hosted
installer deploys. kong + app attach to that Traefik network and expose
themselves via Docker-provider labels (erosi-kong priority 100 for
Supabase API paths, erosi-app priority 1 for everything else on
erosi.limonia.net). No container publishes host ports; host Caddy is
out of the deploy path permanently.

Keycloak is no longer bundled — PUBLIC_KEYCLOAK_URL points at an
external IdP. The deploy script writes .env with FILL_IN_* placeholders
for PUBLIC_KEYCLOAK_URL, KEYCLOAK_CLIENT_SECRET, and TRAEFIK_NETWORK,
and fails fast until they are filled.

New domain: erosi.limonia.net. realm-export.erosi.json is retained
as reference for the external Keycloak operator; it is no longer
imported by this stack.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 23:49:10 +02:00
6bc7092ce5 docs(auth): record fase-8 logout + migration 014 hardening
Some checks failed
CI / Lint & Type-check (push) Failing after 1m12s
CI / Build (push) Has been skipped
Deploy / Build & Push Docker image (push) Failing after 2m28s
Deploy / Deploy to production (push) Has been skipped
- CLAUDE.md status line + logout paragraph + migration 013 gotcha updated
  to cover the INSERT+UPDATE two-step GoTrue behaviour and the RP-initiated
  logout flow; new SvelteKit gotcha block spelling out the signOut→$effect
  race that produced "PKCE code verifier not found in storage" and how the
  isLoggingOut flag + /logged-out public route close it.
- docs/history/fase-8-auth-logout.md captures both prod bugs with symptom,
  root cause, fix, the Keycloak id_token_hint tradeoff (why the one-click
  confirmation page is accepted UX), and the test deltas.
- docs/development.md auth.ts one-liner updated.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 10:40:07 +02:00
768b3cda58 docs: split CLAUDE.md into docs/{development,deployment,history/fase-*}
CLAUDE.md shrinks to rules + status + index (175 lines, down from 476).
Dev setup, prod deploy, and per-phase build records move to docs/.
Gotchas regrouped by domain (auth, frontend, PWA, testing, backend, deploy,
platform) and unnumbered so they don't drift as new ones land.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-18 22:21:20 +02:00
3d85d0a50e fix(deploy): stop docker compose exec -T from draining the heredoc
Symptom observed twice (migrations 012 and 013): deploy-erosi.sh ran the
migration loop's first iteration (the `CREATE TABLE IF NOT EXISTS
_applied_migrations` step) then silently skipped every file in
supabase/migrations/*.sql without printing a single skip/apply line. Had
to `psql -f <new-migration>` by hand on ambrosio after every deploy.

Root cause: the deploy uses `ssh host bash -s << 'REMOTE' ... REMOTE` so
the outer bash on the remote reads its own script from stdin. Any
`docker compose exec -T db psql ...` inside that script — particularly
inside a command substitution like `already=$(docker compose exec -T ...)`
— inherits that stdin and consumes it, eating the rest of the heredoc.

Fix: pass `</dev/null` (or the migration file for the actual `apply`
step) to every `docker compose exec -T` call so docker gets an empty /
file-scoped stdin instead of the parent's heredoc.

Verified on ambrosio: deploy now prints all 13 `skip ... (applied)` lines
as expected, and will apply new migrations going forward without manual
intervention.

- CLAUDE.md: gotcha #20 documenting the pattern; applies to any
  heredoc-delivered remote script using `docker compose exec -T` or
  `kubectl exec`.
2026-04-15 00:31:00 +02:00
2294a31942 fix(auth): default empty role/aud on auth.users → 'authenticated'
Found on ambrosio after the first real self-registration: GoTrue v2.158.1
persists OIDC-provisioned users with empty-string role and aud. PostgREST
then dies with `role "" does not exist` on every REST call because its
per-request `SET LOCAL role = $claim` can't resolve ''. Dev never caught
this because seed.sql hardcodes both columns.

- supabase/migrations/013_auth_users_role_default.sql: backfill existing
  rows + BEFORE INSERT trigger on auth.users that fills empty/NULL role +
  aud with 'authenticated'. Idempotent, preserves explicit values.
- supabase/tests/008_auth_user_role_default.sql: pgTAP coverage — function
  + trigger exist, backfill left nothing empty, empty-string and NULL
  values get defaulted, explicit non-empty role is preserved.
- CLAUDE.md: status line updated to 255 tests (was 248), new gotcha #19
  documenting the GoTrue quirk + that users in existing sessions must
  re-login once for a fresh JWT after the fix lands on any given env.

Total: 41 pgTAP (was 34) + 140 integration + 15 unit + 58 Playwright + 1
gated rate-limit. Full `just test-all` green.
2026-04-15 00:23:00 +02:00
f5c8cb68be feat(fase-7): collective-flow E2E coverage + fix 3 latent bugs
12 new Playwright tests closing the UI coverage gap in the collective
lifecycle (onboarding → invitation → admin manage). Writing them surfaced
three product-code bugs that have silently been present since Fase 1;
fixed as part of this phase.

Tests:
- tests/e2e/onboarding.test.ts       O-01..O-03 (Eva auto-redirect, happy
                                     path create, empty-name submit-disabled)
- tests/e2e/invitation.test.ts       I-01..I-05 (token generation, accept
                                     logged-out + logged-in, expired, used)
- tests/e2e/manage-collective.test.ts MC-02..MC-05 (promote, demote, remove
                                     member, generate pending invite)
- tests/fixtures/db.ts               resetEva, seedExpiredInvitation,
                                     seedUsedInvitation, restoreSeedMembership,
                                     countMembership — all via raw SQL so they
                                     don't depend on SUPABASE_SERVICE_ROLE_KEY

Bugs found & fixed:
- supabase/migrations/012_create_collective_rpc.sql: atomic
  `create_collective(name, emoji)` SECURITY DEFINER RPC. Fase 1 onboarding
  used `.insert(...).select().single()` which triggers the SELECT policy on
  the fresh row — creator isn't a member yet, so the INSERT was rejected with
  "row-level security" even though the INSERT policy passed. onboarding now
  calls the RPC which inserts both the collective AND the creator-as-admin
  membership in one transaction, bypassing RLS. F-08 in rls-isolation.test.ts
  has been silently masking this bug (only the spoof branch was asserted).

- routes/+layout.svelte: post-login redirect now reads sessionStorage
  `pendingInvitationToken` and routes back to /invitation/<token> instead of
  defaulting to /onboarding or /lists. The invitation page already stashed
  the token before kicking off Keycloak, but nothing read it back.

- routes/(app)/collective/manage/+page.svelte: loadMembers now subscribes
  to currentCollective so it re-runs when the store resolves after cold
  navigation. onMount alone races with the auth listener's first emit and
  the member list stayed empty on direct URL hits.

- routes/invitation/[token]/+page.svelte: awaits authLoading before deciding
  whether to redirect to login. Previously raced with the auth listener and
  triggered a redundant Keycloak round-trip for freshly-authenticated users.

Stable selectors added (Playwright):
- Onboarding: onboarding-create-tab, onboarding-join-tab,
  collective-name-input, collective-submit
- Manage: member-row-<uid>, role-select-<uid>, remove-member-<uid>,
  generate-invite, invite-link
- Invitation: invitation-accept, invitation-error (+ data-error-key attr)

Scope dropped from the plan — UI does not exist, would be feature work:
- O-04: "+ new collective" affordance in the sidebar.
- MC-01: rename-collective input in /collective/manage.
Both flagged as follow-ups in plan/fase-7-collective-flow-tests.md.

Test totals: 34 pgTAP + 140 Vitest integration + 15 Vitest unit + 58
Playwright + 1 gated rate-limit. 3 skipped (2 Realtime presence, 1 gated).
2026-04-14 22:33:33 +02:00
17bc344986 docs(fase-7): plan — collective-flow E2E coverage + ambrosio deploy notes
- plan/fase-7-collective-flow-tests.md: 14 new Playwright tests (O-01..O-04
  onboarding, I-01..I-05 invitation acceptance, MC-01..MC-05 admin manage)
  plus shared fixtures/db.ts helpers (resetEva, seedExpiredInvitation,
  seedUsedInvitation, restoreSeedMembership). Risks + scope-out documented.
- CLAUDE.md: add "Fase 6+ production deploy to ambrosio" section with the
  files / config / discovered fixes for the prod stack; link to the new plan
  from the Project Status line; add gotchas #16 (injectManifest filename
  hardcoded in @vite-pwa/sveltekit 0.6.8) and #17 (supabase/postgres doesn't
  bootstrap its internal roles on a fresh volume).
2026-04-14 21:39:26 +02:00
2db5aaac14 Fase 6: deploy readiness (PWA + invitation rate-limit + JWT rotation)
Closes the deferrals from Fase 4 that gated a public deploy of the MVP.

PWA install
- Custom SW at apps/web/src/sw.ts (named sw.ts, not service-worker.ts, so
  SvelteKit doesn't intercept it and block Workbox imports).
- vite.config.ts switched to injectManifest strategy with precache of the
  built shell; no runtime caching of Supabase (offline writes stay on the
  existing $lib/sync pending_ops queue).
- Root +layout.svelte onMount() calls registerSW({ immediate: true }) from
  virtual:pwa-register — the plugin does not auto-register.
- Web manifest with 192/512/512-maskable icons + iOS meta tags
  (apple-mobile-web-app-capable, apple-touch-icon, etc.) in app.html.
- Placeholder icons generated via ImageMagick; replace before public launch
  (noted in apps/web/static/icons/README.md).

Kong rate-limit
- /rest/v1/collective_invitations POST: 20/hour per Authorization header.
  Anti-spam on invitation creation is the only rate-limit that survived —
  auth rate-limits were dropped during execution (see plan §6.3): Keycloak
  already provides bruteForceProtected=true on the realm, and stacking a
  Kong limit on /auth/v1/token throttled legitimate PKCE code exchanges
  during E2E.
- Added 'rate-limiting' to KONG_PLUGINS in docker-compose.dev.yml.
- Discovered: strip_path=true on a full-table path sends "/" upstream and
  PostgREST rejects POST to root with PGRST117. Route carries a
  request-transformer plugin that rewrites the URI back.

JWT rotation + prod template
- infra/scripts/rotate-jwt.sh signs anon + service_role JWTs with a fresh
  48-byte secret via openssl. Prints three values for the operator to
  paste; does not touch files.
- Dev secret rotated as a dry-run. Updated both .env (local, gitignored)
  and apps/web/.env.development. Existing sessions are invalidated — all
  users must re-login once.
- .env.production.example committed with placeholders + rotation notes.

Lighthouse + RLS audit tooling
- `just lighthouse` boots the prod build + Supabase stack and runs
  lighthouse CLI against PWA/A11y/Best-Practices.
- `just rls-audit` runs infra/scripts/rls-audit.sh which signs an Eva JWT
  (non-member) and GETs 8 REST endpoints — all must return []. Complements
  the Vitest rls-audit.test.ts suite.

Tests
- 236 green: 34 pgTAP + 140 Vitest integration + 15 unit + 46 Playwright.
- 1 rate-limit test gated behind RUN_RATE_LIMIT_TESTS=1 (Kong counters are
  shared state); run via `just test-rate-limit` which force-recreates Kong
  first to reset counters.
- 3 skipped in `just test-all` (2 Realtime presence upstream bug, 1 gated
  rate-limit).

Deliberately out of scope: push notifications, CI ephemeral Docker, final
production icons, runtime caching of Supabase (SyncBanner + pending_ops
already covers offline).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 04:48:04 +02:00
5803806295 docs(fase-5.15): title chrome cleanup on detail views
Recorded in plan/fase-5-mobile-ux.md (new §5.15 right next to the
existing 5.13 / 5.14 sections) and CLAUDE.md "Fase 5 — what has been
built" with the list.status → visual signal table.

Code change landed in 73bc51e.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 03:25:28 +02:00
12b7b7443f docs(fase-5.14): document inline add-form UX change
Recorded in plan/fase-5-mobile-ux.md (new §5.14 with the six UX answers)
and CLAUDE.md "Fase 5 — what has been built" section. Also corrected the
"Fase 2a — what has been built" line that still claimed a sticky create
input for /lists, which was replaced by the masthead "New list" button
back in Fase 5.8.

Code change was committed in 3a11914.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 03:12:49 +02:00
53de447aa5 fix: generateId() fallback for insecure-context origins
Problem
  The phone-preview path (http://192.168.1.167:5173) is a non-secure
  origin. `window.crypto.randomUUID` is gated behind secure contexts
  (HTTPS / localhost / 127.0.0.1 / file://) so it's undefined there,
  and every optimistic-id call site crashed handleAdd with
  `TypeError: crypto.randomUUID is not a function`.

Fix
  apps/web/src/lib/utils/id.ts — generateId() uses crypto.randomUUID()
    when available, otherwise falls back to crypto.getRandomValues()
    + RFC 4122 §4.4 byte assembly. getRandomValues IS exposed on
    insecure contexts (unlike subtle), so the fallback is v4-compliant
    and cryptographically acceptable for client-side optimistic ids.
  Replaced crypto.randomUUID() at every call site:
    stores/lists.ts, stores/tasks.ts, sync/queue.ts, sync/undoQueue.ts
    routes/(app)/lists/[id]/+page.svelte
    routes/(app)/tasks/[id]/+page.svelte
  CLAUDE.md gotcha added: never call crypto.randomUUID() directly —
    always import generateId from $lib/utils/id.

Tests (written first, confirmed failing on main)
  src/lib/utils/id.test.ts (4 tests)
    U-01 returns UUID v4 when randomUUID is available
    U-02 falls back when randomUUID is undefined
    U-03 50 fallback-generated ids are all unique
    U-04 prefers randomUUID when present (doesn't drop into fallback)
  tests/e2e/insecure-context.test.ts (1 test)
    INS-01 stubs crypto.randomUUID = undefined via addInitScript,
      drives the add-item flow, confirms the row renders (if the
      old call site were still there, handleAdd would throw).

Verification
  just test-all → exit 0, 233 green, 2 skipped:
    34 pgTAP (unchanged)
    140 Vitest integration + 2 skipped presence (unchanged)
    15 Vitest unit (was 11, +4 generateId)
    44 Playwright (was 43, +1 INS-01)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 02:41:39 +02:00
4532c24e1a docs(fase-5): close-out — plan, CLAUDE.md, README status
Fase 5 is  complete in automatable scope after the last five feature
commits (d6cea51, 4cc5f69, d14d6cd, 1cb408a, f3e8234). 228 tests green,
4 skipped. Deferred: WebKit-dependent swipe/long-press E2E, card
presence avatars, max-w-2xl reading width.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:37:11 +02:00
2174d2c2c0 feat(fase-5): mobile UX shell + masthead + swipe-delete undo (224 tests green)
5.0 Tests primero
  Playwright: mobile-shell.test.ts (4 — sidebar hidden on mobile, bottom tab
    bar visible with aria-current, hamburger opens drawer, desktop shows
    sidebar), mobile-masthead.test.ts (4 — every top-level route pairs
    masthead-label + masthead-title), mobile-swipe-delete.test.ts (M-06/M-07
    describe.skip — Chromium touch emulation flaky; needs `playwright install
    webkit`)
  Vitest: undoQueue.test.ts (5 — schedule+commit, undo+restore, TTL expiry,
    double-undo no-op, custom ttlMs)

5.1 Responsive shell
  DesktopSidebar.svelte (hidden md:flex)
  MobileTopBar.svelte (md:hidden sticky backdrop-blur-xl)
  BottomTabBar.svelte (md:hidden glassmorphism, safe-area-inset-bottom)
  MobileDrawer.svelte (backdrop + collective switcher + settings + logout)
  (app)/+layout.svelte — CRITICAL FIX: flex flex-col md:flex-row. Was
    horizontal-only, which pushed masthead off-screen on mobile. UndoToast
    mounted globally here.

5.2 Masthead + responsive padding
  ScreenMasthead.svelte — label (13px uppercase) + title (26px/32px).
  Applied to /lists, /tasks, /notes, /search. px-8 → px-4 md:px-6 everywhere.
  messages/{en,es}.json: masthead_{lists,tasks,notes,search}_label +
    masthead_search_title, undo, undo_deleted_item, list_item_delete_aria.

5.4 Red-zone swipe-delete on /lists/[id]
  SWIPE_MAX=96 (red zone rest width), SWIPE_THRESHOLD=48 (latch-open),
  SWIPE_COMMIT_THRESHOLD=200 (full-swipe commit). Red zone button exposes
  aria-label="Delete item"/"Eliminar producto". handleDelete uses
  scheduleUndoable — optimistic local removal, 4-s TTL, commit to Supabase
  on timeout or restore from snapshot on Undo.

5.5 UndoQueue + UndoToast
  src/lib/sync/undoQueue.ts — writable store + Map-backed actions with TTL.
    __flushUndoQueueForTests + __pendingUndoCount for Vitest.
  src/lib/components/UndoToast.svelte — renders latest undoable, offset
    above bottom tab bar (bottom: calc(env(safe-area-inset-bottom) + 4.5rem)),
    Undo button.

5.6 Scrollable frequency chips
  ItemSuggestions.svelte — mobile: flex overflow-x-auto with
    [scrollbar-width:none] [&::-webkit-scrollbar]:hidden; desktop: wraps.
    Chips shrink-0 so they don't compress.

5.7 Shell polish on tasks/notes/search
  Search group headers now carry "{n} MATCH / MATCHES" badges.
  Grid in /lists goes 2-col → 3-col at md+.
  Sticky create input offset for the bottom tab bar on mobile.

5.Z Verification
  just test-all → 224 verdes, 4 skipped
    34 pgTAP (unchanged)
    140 Vitest integration + 2 skipped presence (unchanged)
    11 Vitest unit (was 6, +5 undoQueue)
    39 Playwright + 2 skipped swipe-touch (was 31, +8 new mobile tests)

Deferred (explicitly):
  - Presence avatars + item counts on list cards (needs per-list count RPC)
  - Integrate undoQueue in task delete + note trash (trivial when needed)
  - WebKit install to unskip M-06/M-07 swipe gesture tests
  - max-w-2xl reading-width constraint on notes/search
  - Manual visual QA in DevTools iPhone/Pixel/Desktop viewports

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 14:09:17 +02:00
30a7c55252 docs: point DESIGN.md references to design/slate_collective/DESIGN.md
The duplicate design/DESIGN.md was removed; the authoritative "Monolith
Editorial" spec lives at design/slate_collective/DESIGN.md. Update
CLAUDE.md, README.md, and plan/fase-5-mobile-ux.md accordingly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 13:40:58 +02:00
ee962991e1 docs(fase-5): plan mobile UX rewrite ("Monolith Editorial")
- Add plan/fase-5-mobile-ux.md with 7-chunk breakdown:
    5.0 mobile tests (Playwright mobile-shell/masthead/swipe-delete + Vitest helpers)
    5.1 responsive shell (MobileTopBar + BottomTabBar + MobileDrawer)
    5.2 ScreenMasthead + px-4/md:px-6 pass
    5.3 /lists mobile cards
    5.4 /lists/[id] rows + red-zone swipe-delete
    5.5 undoQueue store + UndoToast
    5.6 scrollable frequency chips
    5.7 tasks/notes/search shell + masthead
    5.Z verify 211 + new M-series green
- Explicit gap analysis vs. current app + deliberate exclusions
    (no priority badges, no voice search, no fake meta like "Dairy · Weekly")
- Index design/ directory: Stitch mockups per screen (mobile + desktop variants),
  plus the "Monolith Editorial" DESIGN.md directing tonal shifts, masthead
  typography, glassmorphism, and the no-line rule
- Relocate DESIGN.md under design/slate_collective/DESIGN.md (old entry point) —
  the current design direction lives at design/DESIGN.md
- Reference design/ from CLAUDE.md + add Fase 5 to README phase index

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 13:36:52 +02:00
2806e06db2 feat(fase-4): global search + RLS isolation audit (211 tests green)
4.0 Tests primero
  Vitest: search.test.ts (10 — S-01..S-04), rls-audit.test.ts (42 —
    3 intruders × 14 cross-collective ops proving zero leakage)
  pgTAP: 007_search_tsvector.sql (9 — columns, GIN indexes, function
    signature, generated-vector invariant)
  Playwright: search.test.ts (2 — SR-01 happy-path, SR-02 filter toggle)

4.1 Búsqueda global
  Migration 010_search_vectors.sql: STORED GENERATED tsvector columns
    on shopping_items/tasks/notes + GIN indexes + search_result_type
    enum + search_in_collective() SECURITY INVOKER function (RLS-aware,
    trash-excluded per RN-08) + GRANT EXECUTE to anon/authenticated.
    Uses `simple` config (no stemmer — bilingual en/es).
  Store apps/web/src/lib/stores/search.ts — RPC wrapper
  /search: debounced input (300ms, ≥2 chars), type filter chips with
    multi-toggle, results grouped per type with data-testid hooks for
    Playwright, deep-link per type (shopping_item → /lists/[id], task →
    /tasks/[id], note → /notes/[id])

4.4 Security
  rls-audit.test.ts replaces the curl-based manual audit with a
    parametrised matrix — zero cross-collective reads/writes under
    three different attacker roles

Realtime flake hardening
  Add 250ms settle after SUBSCRIBED in realtime-helpers.ts — the Phoenix
    socket reports SUBSCRIBED slightly before the backend finishes
    propagating the filter to the WAL subscription, so mutations fired
    immediately after subscribe could miss the filter under load.

4.Z Verification
  just test-all → 211 verdes, 2 skipped
    34 pgTAP (was 25, +9 search)
    140 Vitest integration (was 88, +10 search +42 rls-audit; 2 skipped)
    6 Vitest unit (unchanged)
    31 Playwright (was 29, +2 search)
  Deferred (prod-deploy scope):
    PWA install/push (needs real iOS/Android hardware)
    Kong rate-limit plugin config
    JWT_SECRET / ANON_KEY rotation
    Lighthouse PWA ≥ 90 manual validation

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 12:47:38 +02:00
673a320a66 docs: note Realtime waitFor 10s timeout in CLAUDE.md
Documents the flake fix from 3afc911 so future contributors don't
accidentally drop the timeout back to 5s. Cross-referenced with the
`project_realtime_config` memory, which has the full rationale.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 12:06:03 +02:00
104eeba02e feat(fase-3): Tareas + Notas — TDD complete (148 tests green)
3.0 Tests primero
  pgTAP: 005_tasks_rls.sql (5 — completion CHECK), 006_notes_trash_purge.sql (4 — purge SQL inline + pin/archive CHECK)
  Vitest RLS: rls-tasks.test.ts (14), rls-notes.test.ts (15)
  Playwright: tasks.test.ts (3), notes.test.ts (4)

3.1 Tareas
  Migration 008_tasks.sql: task_lists + tasks + task_list_collective_id() helper
  CHECK constraint: is_completed ⇔ completed_by ⇔ completed_at
  RLS by role + cross-collective isolation
  Store apps/web/src/lib/stores/tasks.ts (optimistic CRUD + reorder)
  /tasks overview (grid + sticky create input + 5s polling)
  /tasks/[id] detail with svelte-dnd-action reorder, flip animation,
    inline edit (dblclick), "Completed by …" attribution via lazy-loaded
    collective_members

3.2 Notas
  Migration 009_notes.sql: notes + note_color enum (8) + pin/archive CHECK
    + 7d trash window in RLS + fn_notes_touch trigger + pg_cron purge job
  Store apps/web/src/lib/stores/notes.ts (CRUD + pin/archive/trash/duplicate)
  /notes board (pinned section testid notes-pinned + 30s polling)
  /notes/[id] editor (title + textarea, 500ms debounced autosave,
    color picker, pin/archive/duplicate/trash actions)
  /notes/archive (restore + send to trash)
  /notes/trash (restore + permanent delete)

3.Z Verification
  just test-all → 148 verdes, 2 skipped:
    25 pgTAP (was 16, +9)
    88 Vitest integration (was 59, +29; 2 presence skipped)
    6 Vitest unit (unchanged)
    29 Playwright (was 22, +3 tasks +4 notes)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 10:28:19 +02:00
e7a961a66d feat(fase-2b): Realtime sync + offline queue + Modo Compra
Fase 2b closes the critical-path product differentiator. Two sessions on the
same list see each other's changes in real time, mutations survive network
drops and sync when reconnected, and a dedicated full-screen shopping view
optimises the in-store experience.

2b.1 Realtime
- `$lib/stores/realtimeSync.ts` wraps `postgres_changes` with an `applyItemEvent`
  reducer (INSERT/UPDATE/DELETE → next items[]) and a `subscribeToList` helper
  that awaits the SUBSCRIBED handshake before returning
- `/lists/[id]` subscribes in onMount, unsubscribes in onDestroy. Uses a
  `pendingTempIds` set to deduplicate own-mutation echoes against optimistic
  rows (matches by name+created_by+sort_order)
- Client-generated UUIDs for new inserts make the path idempotent: if the
  server response is lost and we retry, the second POST hits PK-conflict
  which the queue treats as success
- CHECKED section div now carries role="listitem" so Playwright locators
  follow the item across sections

2b.2 Offline queue
- `$lib/sync/queue.ts` — SyncQueue class backed by IndexedDB (idb), FIFO flush,
  MAX_ATTEMPTS=5 retry budget, PK-conflict-as-success short-circuit
- `$lib/sync/index.ts` — app-wide singleton, window.online listener flushes
  automatically, hydrateSyncState() at page load restores pendingOpsCount
- `$lib/stores/syncStatus.ts` — derived store (offline | syncing | synced)
  tracking navigator.onLine + queue depth
- SyncBanner component renders the offline/syncing indicator in the detail
  and session views
- handleAdd enqueues on failure instead of reverting, so an offline mutation
  keeps its optimistic row and syncs on reconnect

2b.3 Modo Compra
- `/lists/[id]/session/+page.svelte` — full-screen overlay (fixed inset-0
  z-50) that covers the sidebar while keeping the normal auth routing.
  56×56 toggles, flip animation shuffling items between TO BUY / CHECKED,
  Finish Shopping confirmation modal → completeList → goto('/lists')
- Link from `/lists/[id]` header (data-testid=start-session) with the
  new `list_start_session` message

Testing infra
- apps/web gets its own Vitest config (jsdom + fake-indexeddb/auto) and a
  new `pnpm test:unit` script. `just test-all` now chains pgTAP → integration
  → unit → e2e so a single command is the gate.
- packages/test-utils/tests/sync-queue.test.ts (placeholder scaffold) removed —
  replaced by `apps/web/src/lib/sync/queue.test.ts` co-located with the module

Totals: 103 tests green
  16 pgTAP
  59 Vitest integration (in packages/test-utils)
   6 Vitest unit (in apps/web — the SyncQueue)
  22 Playwright E2E (5 auth + 4 lists + 6 items + 2 realtime + 2 offline + 3 session)
   2 skipped (realtime-presence — upstream bug, unchanged)

Documented in plan/fase-2b and CLAUDE.md.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 03:32:15 +02:00
cb07f67a69 feat(realtime): full Fase 2b.0 test suite + infra hardening
Extend the 2b.0 red-phase coverage: presence, RLS isolation, offline-queue
contract, and Playwright scaffolds for the shopping-session UX. Only the
presence test is blocked on an upstream Realtime bug (documented below); all
other Realtime paths are proven end-to-end.

Tests
- realtime-postgres-changes.test.ts: now uses afterEach socket disconnect
  (Vitest singleFork kept Phoenix sockets alive between files, leaking state)
- realtime-isolation.test.ts (new): R-I-01 David (guest, same collective)
  receives events; R-I-02 Eva (non-member) receives NONE — RLS is enforced
  server-side per subscribed JWT
- realtime-presence.test.ts (new, describe.skip): two-client roster + leave
  assertions ready, gated on upstream bug
- sync-queue.test.ts (new, describe.skip): 7 placeholders pinning the
  apps/web/src/lib/sync/queue.ts contract (Q-01..Q-04 enqueue / in-order
  flush / retry; F-01..F-03 online-event flush + last-write-wins)
- apps/web/tests/e2e/{session,realtime,offline}.test.ts (new, describe.skip):
  S-01..S-03, R-E-01, R-E-02, O-01, O-02 pinning the Modo Compra UI contract
- vitest.config.ts: fileParallelism=false, drop singleFork so each file gets
  a fresh worker fork — prevents RealtimeClient singleton leakage

Infra
- db-init/00-role-passwords.sh: pre-create `realtime` schema with
  AUTHORIZATION supabase_admin. Realtime's per-tenant migrator creates tables
  INSIDE the schema but does not create the schema itself; without this the
  first tenant connect fails with "schema realtime does not exist"
- docker-compose.dev.yml: adopt the upstream supabase/supabase Realtime env
  shape — SEED_SELF_HOST=true + RUN_JANITOR=true + RLIMIT_NOFILE=10000 +
  drop the custom `command: eval seeds` (that bypasses the normal supervisor
  startup and was observed to cause GenServer crashes under load).
  Version pinned to v2.76.5 to match the official docker-compose.

Known upstream bug
- Realtime v2.76.5 and v2.83.0 both crash on presence_diff:
  `(UndefinedFunctionError) RealtimeChannel.handle_out/3 is undefined`.
  postgres_changes + isolation unaffected (they don't traverse handle_out).
  Presence tests stay `describe.skip` until a fixed upstream is released.

Totals: 59 Vitest passed (+ 9 skipped awaiting implementation/upstream),
16 pgTAP, 15 Playwright (+ 7 E2E scaffolded for 2b UI) = 90 green.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:55:55 +02:00
4c913cf495 feat(realtime): Fase 2b.0 infra + first R-series tests green
Enable postgres_changes broadcasts on shopping_items / shopping_lists and prove
the path end-to-end with Vitest Realtime tests and a pgTAP configuration check.

Infra changes that were silently blocking events
- Migration 007: shopping_items + shopping_lists added to supabase_realtime
  publication with REPLICA IDENTITY FULL (UPDATE/DELETE payloads need the full
  row so list_id-based filters work and RLS can evaluate DELETE against OLD)
- Realtime service: DB_USER=supabase_admin (superuser; supabase_replication_admin
  lacks CREATE on the `realtime` schema that the service auto-creates per tenant)
- Realtime service: SELF_HOST_TENANT_NAME=realtime so the seed tenant name
  matches the default supabase-js resolves for localhost URLs (was realtime-dev
  → TenantNotFound)

Tests
- pgTAP 004_realtime_publication.sql — P-01..P-04: publication membership and
  REPLICA IDENTITY FULL for both shopping tables
- Vitest realtime-postgres-changes.test.ts — R-01 INSERT broadcast,
  R-02 UPDATE carries full row, R-03 list_id filter isolates events
- test-utils realtime-helpers.ts — subscribePostgresChanges() returns a
  waitFor(predicate, timeout) helper that captures the SUBSCRIBED handshake
  before returning so mutations issued right after are not lost
- createClientAs now calls realtime.setAuth(token) so the server evaluates
  RLS against the test user's JWT
- Justfile test-db now globs supabase/tests/*.sql so new pgTAP files are picked
  up automatically

Totals: 54→57 Vitest, 12→16 pgTAP, 15 Playwright = 88 tests green.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 02:33:40 +02:00
f396897cb5 test: full test suite (Vitest + pgTAP + Playwright) + TDD plan restructure
Add a 4-layer test stack covering RLS, triggers, and UI flows for Fases 0–2a,
then restructure every plan file so future fases start with tests and end with
a verification gate.

Test suite
- packages/test-utils: Vitest integration tests signing HS256 JWTs via jose so
  each test acts as a specific seed user (createClientAs + createAdminClient)
- supabase/tests: pgTAP for accept_invitation(), item_frequency trigger, and
  promote-on-admin-leave; each file self-installs pgtap extension
- apps/web/tests: Playwright E2E with live Keycloak login per test (storageState
  caching doesn't rehydrate Supabase's session state reliably)
- just test-all chains the three suites; test-db forwards POSTGRES_PASSWORD
  as PGPASSWORD with ON_ERROR_STOP=1 so failures abort the chain

Supabase auth gotcha
- PostgREST queries inside onAuthStateChange deadlock on GoTrue's navigator.locks
  auth lock (getAccessToken → getSession → initializePromise waits on the same
  lock that's held during event dispatch). Fix is two defenses: a pass-through
  lock in $lib/supabase, and a setTimeout(0) defer in root +layout.svelte to
  push loadUserCollectives out of the callback's microtask chain. Either alone
  is insufficient; both together unblock the Playwright suite.

Env key rotation
- apps/web/.env.development had a stale demo anon key signed with a different
  secret than root .env; Vite inlined that into the browser bundle so Kong (which
  uses the root .env value) rejected every request with 401. Aligned the two
  files and added a memory entry to flag this for the next rotation.

Plan restructure (TDD)
- Every fase now opens with X.0 Tests primero and closes with X.Z Verificación
  final. Completed fases (0, 1, 2a) show the pattern retroactively with the
  tests that currently cover them; pending fases (2b, 3, 4) list the tests to
  write before implementation.

Docs
- CLAUDE.md status line reports 54 + 12 + 15 = 81 green tests, adds gotchas
  #11 (auth-lock deadlock) and #12 (no storageState caching)
- README.md adds a TDD methodology section and the test-all command
- .gitignore excludes Playwright's generated reports and auth state

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 01:40:16 +02:00
3af1276c15 feat: Fase 2a — shopping lists CRUD
DB: shopping_lists + shopping_items tables with full RLS, pg_cron jobs
(archive completed lists after 7 days, purge trash after 7 days).
item_frequency table with SECURITY DEFINER trigger that normalises and
upserts on every shopping_items INSERT.

Frontend: /lists overview (featured card + 2-col grid + trash toggle),
/lists/[id] detail (qty stepper, inline edit, swipe-to-reveal-delete,
drag & drop reorder via svelte-dnd-action, ItemSuggestions chips).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 22:25:31 +02:00
ce1bcfb7a6 feat(design): apply Monolith Editorial design system to all Fase 1 screens
- Remove all 1px border separators (sidebar border-r, page header border-b,
  section border-t, member list divide-y, invite card border). Separation is
  now achieved via background color shifts and whitespace per the "No-Line" rule.
- Fix sidebar: bg-surface-raised vs bg-background creates tonal separation.
- Correct dark background to #020617 (slate-950) per spec.
- Add surface-container-low, text-primary/secondary/muted, destructive tokens.
- Fix CSS variable color space: all tokens are RGB triplets; switch Tailwind
  config and app.css from hsl() to rgb() to prevent yellow/warm color bleed.
- Replace emoji nav icons with Lucide icons at 16px / 1.5 stroke-width.
- Apply Masthead typography (uppercase Label-MD + Title-LG) to all page headers
  and section labels across lists, tasks, notes, search, settings, manage.
- Destructive action (sign out) uses bg-destructive per spec.
- Add `just serve` command: builds and runs the prod Node server at :3000
  against the dev Docker stack for production build testing.
- Add nav_collective i18n key (en + es).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 22:09:25 +02:00
b297d253d9 fix(auth+pwa): resolve stuck-loading race condition and PWA build error
Auth: `getSession()` in a SvelteKit load function races with Supabase's async
localStorage init and can return null for a valid session, triggering a spurious
login() redirect. Moved auth redirect to (app)/+layout.svelte via $effect, which
correctly waits for onAuthStateChange to fire. Also fixed collective data never
loading on page refresh (INITIAL_SESSION event, not SIGNED_IN).

PWA: SvelteKit blocks Workbox imports in src/service-worker.ts, preventing
@vite-pwa/sveltekit from finding the compiled SW output. Switched to generateSW
strategy (plugin auto-generates the SW). Custom SW deferred to Fase 2b using
src/sw.ts (a filename SvelteKit does not intercept).

Docs: added gotchas 6–8 to CLAUDE.md covering both root causes so they are not
reintroduced. Updated plan/fase-2b with the sw.ts workaround note.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 21:44:14 +02:00
7d91705fc2 feat(fase-1): auth, collective management, and DB migrations
- SQL migrations: users, collectives, collective_members, collective_invitations,
  full RLS policies, is_active_member/is_member/is_admin helpers,
  accept_invitation SECURITY DEFINER function, admin auto-promote trigger,
  avatars storage bucket
- Auth refactor: replace keycloak-js with Supabase OAuth (GoTrue OIDC proxy,
  Option B). signInWithOAuth({ provider: 'keycloak' }) + PKCE flow
- GoTrue config: GOTRUE_EXTERNAL_KEYCLOAK_URL + GOTRUE_EXTERNAL_KEYCLOAK_REDIRECT_URI
  added to docker-compose.dev.yml; Keycloak realm updated with GoTrue callback URI
- New routes: /auth/callback, /invitation/[token], /(app)/collective/manage
- Functional onboarding: create collective or join via invite link
- Full settings page: display name (debounced), avatar (initials/emoji/upload),
  language switcher, Keycloak account console link
- Components: Avatar.svelte (initials/emoji/upload with fallback),
  ImageCropper.svelte (cropperjs, 1:1 crop, lazy-loaded)
- i18n: added all Fase 1 message keys (en + es); renamed 'delete' → 'action_delete'
  (JS reserved word); fixed plugin-m-function-matcher major-version URL format
- Database types: manually seeded packages/types/src/database.ts from migrations
- .env.development: committed public dev defaults for SvelteKit type checking
- CLAUDE.md: documented /etc/hosts requirement for keycloak hostname

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 15:29:29 +02:00
f197a81a42 Record Fase 1 design decisions before implementation
- JWT strategy: Option B (GoTrue as OIDC proxy, not direct Keycloak JWT)
- Self-registration enabled in Keycloak realm
- Multiple collectives per user with sidebar switcher
- Invitations are link-only (no email/Resend integration)
- Avatar upload uses in-browser crop (cropperjs) at 1:1 ratio
- Removed Edge Functions from plan; invitation logic handled in SvelteKit server actions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 14:39:11 +02:00
973f9e413c Fase 0: scaffold monorepo, SvelteKit skeleton, and dev infrastructure
- Turborepo + pnpm workspaces with apps/web and packages/types
- SvelteKit app: Tailwind, Paraglide i18n (en/es), keycloak-js, Supabase client,
  auth/collective stores, PWA service worker skeleton, all route placeholders
- packages/types: domain types (User, Collective, ShoppingList, etc.) and
  database.ts placeholder for generated types
- Justfile with dev, db-*, kc-*, build, backup, restore, deploy recipes
- infra/docker-compose.dev.yml: Postgres 15, GoTrue, PostgREST, Realtime v2.83,
  Storage, Kong (port 8001), Studio, Keycloak 24
- infra/docker-compose.prod.yml, kong.yml, db-init scripts, backup/deploy scripts
- keycloak/realm-export.json with colectivo realm and 5 dev test users
- supabase/config.toml and seed.sql with sample collective and items
- GitHub Actions: ci.yml (lint+typecheck+build) and deploy.yml (GHCR + SSH)
- .env.example documenting all required variables
- Fixed docker-compose issues: Studio image tag, Kong port conflict (8001),
  internal role passwords init script, Realtime METRICS_JWT_SECRET/APP_NAME

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 14:37:51 +02:00
f5903ef442 Add planning docs, design system, and Stitch mockups
- CLAUDE.md: project guidance (stack, domain model, auth, i18n, gotchas)
- DESIGN.md: full design system spec derived from Stitch mockups (slate
  monochrome, Inter, shadcn-svelte, screen patterns for all 5 views)
- README.md: development plan with Justfile commands
- analysis/: functional spec (domain model, use cases, business rules)
- plan/: phase-by-phase implementation plans (Fase 0–4)
- .stitch/designs/: generated mockups (lists, shopping session, notes,
  tasks, list detail with frequency chips)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-12 06:35:07 +02:00