Commit Graph

63 Commits

Author SHA1 Message Date
5e2ba3a6d6 feat(fase-10): CU-H07 rename collective + change emoji
Admin gets an editable name input + emoji picker at the top of
/collective/manage. Enter / blur / Save button all flush the PostgREST
UPDATE; Esc reverts to the persisted value. The response payload feeds
both $currentCollective and $userCollectives so the sidebar updates
without reload. Members and guests see no editing affordances at all
(the section is admin-gated; UPDATE policies were already in place from
Fase 2a so no migration is needed).

MC-01a: Ana renames + picks a new emoji, reload preserves both, DB
reflects the change. MC-01b: Borja never sees the editable fields.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 02:07:16 +02:00
2f0847a5a3 feat(fase-10): CU-H06 leave collective — RPC + settings UI
Migration 017 adds public.leave_collective(uuid) with three branches:
- normal member: remove membership row
- sole admin with other members: promote oldest-joined remaining member
  to admin (inline; the existing user-delete trigger does not cover the
  membership-delete path), then remove the row
- sole member: reject with errcode P0001 so the UI can direct the user
  to the dissolve flow (CU-H08)

Settings page gains a "Your collectives" section listing the user's
memberships with a per-row Leave button; the confirmation modal calls
the RPC, drops the collective from local stores, and either switches
to the next collective or sends the user to /onboarding when none
remain. Also seeds the Danger zone scaffolding for Fase 10.5 and adds
all message keys consumed by 10.1, 10.3, 10.5 and 10.6.

pgTAP 010 (7 assertions): member-leave, sole-admin-leave + auto-promote,
sole-member rejected with P0001. Playwright L-01 walks Borja through
the UI flow + checks the seed collective survives (content stays).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 02:04:43 +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
cda7321d37 test(fase-9): WebKit project + swipe-toggle gesture specs
Closes 9.4 (swipe-delete E2E in WebKit — repurposed to the current
swipe-to-check / swipe-to-uncheck gesture, since Fase 5.10 replaced
swipe-to-delete with a double-tap delete flow).

- playwright.config.ts gains a second project named "webkit"
  (devices['iPhone 13']) gated behind RUN_WEBKIT=1 so the suite stays
  green on hosts that do not have the GTK/WebKit system libs
  (libicu74, libxml2, libmanette-0.2-0, libwoff1) installed — those
  need `sudo pnpm exec playwright install-deps`. The chromium project
  ignores `*.webkit.test.ts` so the same file never runs in both.
- Justfile adds `just playwright-install` (chromium + webkit) and
  `just test-webkit` for the on-demand run.
- New tests/e2e/swipe-toggle.webkit.test.ts contains SW-01 + SW-02:
  swipe right on an unchecked row marks it checked; swipe left on a
  checked row marks it unchecked. The handlers in lists/[id]/+page.svelte
  use unified pointer events, so the helper dispatches
  PointerEvent('pointer{down,move,up}') with pointerType:'touch'
  directly — works regardless of the project's hasTouch setting.
- lists/[id]/+page.svelte exposes data-checked and data-name on each
  item-row to give the specs a robust locator without depending on
  text/heading hierarchy.

Note: cannot validate the WebKit runs end-to-end in this sandbox
(missing libicu74/libwoff1 require sudo apt install). The spec is
ready to run under any CI image that has Playwright's standard
linux deps installed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:37:42 +02:00
ed556ce245 feat(fase-9): wire sync_conflicts table + queue logging + debug panel
Closes 9.3 in full: migration 016 + pgTAP test 010 + queue.ts
conflict-detection path + /settings debug panel + integration test.

- Migration 016 adds public.sync_conflicts (append-only audit log of
  last-write-wins conflicts surfaced by the offline mutation queue).
  RLS allows owners to SELECT + INSERT their own rows only; UPDATE
  and DELETE have no policy and are silently denied. collective_id
  is intentionally nullable so user-level conflicts (theme, language
  in future) also fit. Indexed on (user_id, created_at desc) for the
  "show me my last 20 conflicts" query.
- queue.ts gains a `QueueContext` (currentUserId + collectiveId) and
  an optional `preImage` field on UpdateOp. Before sending an UPDATE
  the queue fetches the remote row (limited to the patched fields),
  proceeds with the UPDATE (last-write-wins), then fires a best-effort
  INSERT into sync_conflicts when the remote diverged. Failure to log
  never blocks the UPDATE or pollutes the pending_ops queue. Three
  unit specs (SC-01..SC-03) lock the contract in.
- sync/index.ts exposes setSyncContext(), called from (app)/+layout's
  $effect whenever currentUser / currentCollective change.
- New SyncConflictsPanel.svelte renders the last 20 conflict rows
  for the current user with an "Export JSON" button. Gated on
  import.meta.env.DEV (or a forceShow prop for a future secret
  unlock) — never ships in the production bundle. Slotted into
  /settings just above the Account section.
- Integration tests (packages/test-utils/tests/sync-conflicts.test.ts,
  4 SC-INT specs) exercise the real PostgREST + RLS contract end-to-end
  with the existing seed users (Ana, Borja). Requires fake-indexeddb in
  the test-utils dev deps (queue's IDB shim).
- pgTAP test 010 covers structure, RLS reads/writes, ownership rejection,
  and the append-only invariant (UPDATE/DELETE return 0 rows).
- packages/types/src/database.ts adds the sync_conflicts table type.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:31:35 +02:00
a0e00b8044 feat(fase-9): cap reading column at max-w-2xl on desktop detail routes
Closes 9.2 (desktop reading width).

- (app)/+layout.svelte wraps detail routes (/lists/[id], /tasks/[id],
  /notes/[id]) in a max-w-2xl mx-auto container at the md breakpoint
  and up. Mobile (<md) keeps the existing full-width layout — the
  wrapper only kicks in via md:max-w-2xl. The shopping session
  (/lists/[id]/session) is explicitly excluded so the immersive mode
  still occupies the whole viewport.
- A new readingRoutePattern lives alongside the existing
  detailRoutePattern so the two concerns stay independently testable
  (detail = hide global top bar; reading = cap width).
- RW-01..RW-03 in tests/e2e/reading-width.test.ts measure the
  bounding box of [data-testid="reading-column"] under 1280px and
  390px viewports, and confirm the wrapper is absent from /session.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:20:20 +02:00
9592879ad7 feat(fase-9): wire ThemeToggle into /settings + cross-device theme sync
Closes 9.1.6 (settings UI), 9.1.7 (reactivity), 9.1.8 (Playwright E2E).

- /settings now has an "Appearance" section housing ThemeToggle. The
  onChange callback fires an UPDATE on public.users.theme so the choice
  follows the user across devices. The DB write is best-effort: a failed
  UPDATE does not roll back the immediate localStorage + <html data-theme>
  flip the toggle already performed.
- Root +layout.svelte calls initTheme() once on mount so the JS-side
  stores hydrate from localStorage (the inline anti-FOUC script in
  app.html has already painted the correct theme by this point — this
  just rebuilds the JS state on top so reactive consumers see it).
- (app)/+layout.svelte gains a one-shot effect that reads
  public.users.theme on first hydration and adopts the remote value when
  it differs from localStorage. Defers the PostgREST query through
  setTimeout(..., 0) per the Supabase auth-lock gotcha.
- tests/e2e/theme.test.ts adds T-01 (toggle persists across reload),
  T-02 (system mode follows emulated prefers-color-scheme), and T-03
  (refresh in dark mode never paints a light first frame, including on
  /logged-out which lives outside the (app) group and relies entirely
  on the inline app.html script).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:15:47 +02:00
5873c2fa9f feat(fase-9): ThemeToggle component + anti-FOUC bootstrap
Wires the dark-mode plumbing:

- New $lib/theme module: themePreference + resolvedTheme stores plus
  initTheme() / setThemePreference(). Owns localStorage persistence,
  <html data-theme=...> mirroring, and the matchMedia listener that
  re-resolves "system" when the OS preference flips. Storage-agnostic
  (no Supabase coupling) so the caller persists to public.users.theme
  separately.
- Inline anti-FOUC script in app.html reads localStorage + matchMedia
  synchronously and writes data-theme before the first paint — refresh
  in dark mode no longer flashes white.
- Tailwind switched to darkMode: ['selector', '[data-theme="dark"]']
  so all existing `dark:` utilities resolve from the same attribute.
- :root and :root[data-theme=light] share the light token set; dark
  tokens move into :root[data-theme=dark]. Tokens stay as RGB triplets
  (rgb(var(--token) / <alpha>)) per the repo gotcha — no hsl().
- ThemeToggle.svelte: three-way radiogroup (Light / Dark / System) with
  paraglide messages in EN + ES.

Tests (TDD): 8 new unit specs in src/lib/theme.test.ts cover defaults,
localStorage round-trip, data-theme reflection, system resolution
against matchMedia, invalid-value fallback, and OS preference change
propagation.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:09:19 +02:00
3efe0b9be0 feat(fase-9): migration 015 — users.theme column for dark mode
Adds `theme text not null default 'system' check (theme in
('light','dark','system'))` to public.users. New users get 'system' so
the UI follows the OS preference until they opt in; existing rows
backfill via the default.

Includes pgTAP test 009 (8 assertions covering column existence/type,
default value, valid transitions, and the check constraint rejecting
unknown values). Wires the theme field into the hand-curated
database.ts type so PostgREST queries stay typed.

Also hardens `just db-types` to bail out (instead of truncating
database.ts) when the supabase CLI is missing — the recipe was silently
wiping the file on this dev machine.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-18 01:06:18 +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
0e4ada0083 docs(plan): fase-9 (polish + dark mode) and fase-10 (spec completion)
Fase 9 bundles dark mode as the flagship feature plus the four polish items
parked from Fase 5/6 (sync_conflicts wiring, presence avatars still blocked
on supabase/realtime #1617). Fase 10 closes the completion debt found in the
2026-04-22 audit: CU-H06/H07/H08 (leave/dissolve/transfer admin), trash
restore, reset-from-detail, sidebar create-collective, account deletion, and
automatic language detection.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 18:54:26 +02:00
42509cc7c7 chore(graphify): ignore cache + record auth-flow query output
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-23 18:53:48 +02:00
b660ead40d chore(graphify): knowledge graph of the repo (1398 nodes, 1627 edges)
Generated via /graphify over the full tree (177 files, ~320k words).
Produces graph.html, graph.json, GRAPH_REPORT.md plus per-file
extraction cache so incremental --update runs reuse prior results.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 16:25:53 +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
ca12516005 fix(auth): RP-initiated Keycloak logout + PKCE verifier race
Clicking logout previously only called supabase.auth.signOut(): Keycloak's
SSO cookie was untouched, so the (app) layout's $effect immediately
re-fired login() and Keycloak silently re-authenticated — logout looked
broken. That same chain also surfaced "PKCE code verifier not found in
storage" on prod, since signOut()'s async storage clear could race
signInWithOAuth()'s verifier write, or the $effect could double-fire and
overwrite verifiers mid-flight.

- logout(): signOut() then redirect to Keycloak's end_session endpoint
  (client_id + post_logout_redirect_uri=/logged-out). Keycloak shows a
  one-click "Do you want to log out?" confirmation because GoTrue's proxy
  flow does not expose the id_token, so we can't pass id_token_hint.
- isLoggingOut flag + guard in (app) layout $effect: prevents auto-relogin
  during the logout navigation.
- New public /logged-out route, outside the (app) group.
- A-05 rewritten, new A-07 (fresh login must prompt for credentials after
  RP-initiated logout).
- pgTAP 008 extended with 4 assertions for migration 014's UPDATE trigger.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-21 09:35:17 +02:00
9067ab8f0c fix(auth): also default role/aud on auth.users UPDATE, not just INSERT
GoTrue v2.158.1 emits an UPDATE right after inserting an OIDC-provisioned
user (pop ORM resends the full struct incl. the zero-value role=''),
which bypassed migration 013's BEFORE INSERT trigger and left prod users
with role='' — breaking every PostgREST call with `role "" does not exist`.
Add a matching BEFORE UPDATE trigger reusing the same guard function, and
re-backfill the rows already clobbered.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-20 15:51:21 +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
74e919aa71 feat(deploy): ambrosio production stack (erosi.oier.ovh)
Self-contained compose for a single-VPS deploy behind the host's Caddy.
App + Supabase API share erosi.oier.ovh; Keycloak on auth.oier.ovh.

- infra/docker-compose.erosi.yml — full stack bound to 127.0.0.1 only
  (db, auth, rest, realtime, storage, imgproxy, kong, meta, keycloak, app)
- infra/caddy/erosi.Caddyfile — host-Caddy snippet with TLS + path routing
  (/auth /rest /storage /realtime /graphql → kong, rest → app)
- infra/scripts/deploy-erosi.sh — rsync + first-run secret generation +
  build + migrations + Caddy snippet install
- keycloak/realm-export.erosi.json — prod redirect URIs, registration on,
  client secret as __KEYCLOAK_CLIENT_SECRET__ placeholder (deploy sub'd)
- .env.erosi.example — env template with placeholders

Supporting fixes to make the deploy work on a clean Supabase-postgres volume:

- infra/db-init/00-role-passwords.sh — rewrote as idempotent bootstrap:
  CREATE the Supabase service roles if missing, set passwords on pre-existing
  ones, enable pg_cron/pgcrypto/uuid-ossp, create auth/storage/graphql_public/
  _realtime/realtime schemas, create empty supabase_realtime publication,
  set per-role search_path (auth→auth, storage→storage). Old version only
  ALTERed passwords and relied on the roles already existing — worked for a
  grandfathered dev volume, failed on a fresh prod init.

- infra/db-init/00-role-passwords.sql — removed (folded into .sh).

- apps/web/vite.config.ts — PWA strategy generateSW (was injectManifest).
  The plugin's injectManifest hardcodes the SW source filename to
  service-worker.js and ignores the filename: 'sw.ts' override, making the
  production build fail. generateSW's auto-generated precache-only SW is
  functionally equivalent to our 5-line src/sw.ts.

Tested end-to-end on ambrosio: all 9 containers up, 11 migrations applied,
https://erosi.oier.ovh returns 200, Keycloak OIDC discovery serves the
correct issuer, /auth/v1/settings lists Keycloak as the sole external
provider.
2026-04-14 19:41:33 +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
1f5b34d55d docs(fase-6): propuesta — deploy readiness (PWA + rate-limit + JWT rotation)
New plan file closing out the Fase 4 deferrals with specifics confirmed
by user on 2026-04-14:
  - 6.1 PWA injectManifest, MINIMAL scope (precache shell only; Supabase
    GETs stay network-only since $lib/sync + SyncBanner already cover
    offline writes + the offline indicator)
  - 6.2 manifest.webmanifest + neutral placeholder icons (192/512/180 +
    maskable 512) + iOS meta tags
  - 6.3 Kong rate-limiting — 10/min + 60/hour on /auth/v1/token per IP,
    30/min on /auth/v1/authorize per IP, 20/hour on invitations POST
    per authenticated user
  - 6.4 JWT rotation — dev rotate now + .env.production.example template
    + infra/scripts/rotate-jwt.sh
  - 6.5 Lighthouse PWA ≥ 90 + scripted rls-audit.sh (curl edition of
    Vitest's rls-audit.test.ts)
  - 6.Z verification

Explicitly out of scope (recorded at bottom of the plan):
  - Push notifications (no current use case)
  - Ephemeral-Docker CI (deferred)
  - Runtime caching of Supabase in the SW (deferred)
  - Final production icon art (placeholders land now; real art before
    public launch)

README phase table + index updated; plan total now 11–16 weeks.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 03:39:32 +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
73bc51e0ab feat(detail): drop "ACTIVE LIST" / "TASK MANAGER" eyebrow; show status via pill + strikethrough
Detail views (/lists/[id], /tasks/[id]) no longer show the editorial
uppercase label above the editable title. The title moves up into that
space for a cleaner top.

Status signaling on /lists/[id] (replaces the hardcoded "ACTIVE LIST"):
  - list.status === 'completed'  → title renders text-text-secondary + line-through
  - list.status === 'archived'   → muted pill next to the title
    (data-testid="list-status-pill", slate-200 bg)
  - list.status === 'active'     → no extra chrome, just the title

/tasks/[id] has no status on task_lists — just the label drop.

Verified: just test-all → exit 0, 233 green, 2 skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 03:21:27 +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
3a11914fc5 feat(lists+tasks): inline add-form at end of list, suggestions below input
UX change per direct user request:

  - Add-item / add-task form no longer sticks to the bottom of the viewport.
    It's now the last element of the unchecked/pending section, sitting
    just above the Checked/Completed section (option `a` of the review).
  - On /lists/[id] the frequency suggestion chips moved from ABOVE the
    input to BELOW it, forming a two-line block (input row on top, chips
    on the second line). Chips keep their responsive behavior — horizontal
    scroll on mobile, wrap on desktop (ItemSuggestions already handles
    that).
  - Empty-state message still shows when the list has no items; the form
    renders below it so you can add the first item without scrolling.
  - The form disappears while selection mode is active on /lists/[id]
    (selection chrome takes over the bottom).

Implementation
  /lists/[id]/+page.svelte
    - Removed the `absolute bottom-0` sticky form block.
    - New `addItemForm` Svelte snippet rendered at the end of unchecked
      items AND in the empty-state branch, gated by `!selectionMode`.
    - ItemSuggestions moved inside the snippet, below the input.
    - pb-32 scroll padding reduced to pb-16/md:pb-6 (no more sticky
      overlapping the last row).
  /tasks/[id]/+page.svelte
    - Same treatment with an `addTaskForm` snippet (no suggestions).

Tests
  All existing D- / T-UI- / selection tests pass unchanged: the locators
  are placeholder-based and the form is still findable regardless of
  placement. `data-testid="add-item-form"` / `"add-task-form"` added as
  future-proof hooks.

Verification
  just test-all → exit 0, 233 green, 2 skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 03:05:07 +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
ab8ac08226 fix(tasks): match /lists + /notes create pattern
Two concrete problems the user hit:
  1) /tasks overview had no visible "create" button — only an enter-to-submit
     input hidden behind a decorative Plus icon.
  2) /tasks/[id] add-task form had no visible submit button either.

Both now mirror the /lists + /notes pattern:

  /tasks — new "New list" button in the masthead (bg-slate-900 primary
    style matching "New list" on /lists and "New note" on /notes). Click
    creates an empty task_list and navigates to /tasks/[id] where the
    user names it inline via the new big editable title input
    (autosaves after NAME_SAVE_DEBOUNCE_MS, 500 ms — same hook as
    /lists/[id] and /notes/[id]).
  /tasks/[id] — sticky add-task footer gains a filled "+" submit button
    on the right; clicking it or pressing Enter both fire handleAdd.
    Input is now wrapped in the same rounded-lg card used on /lists/[id]
    so the two screens look identical.

i18n
  tasks_new_list = "New list" / "Nueva lista" (en / es).

Tests
  tasks.test.ts helper updated to drive the new button-then-title flow
  (same shape as lists.test.ts). T-UI-01..03 all pass.

just test-all → exit 0, 228 green, 2 skipped.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 02:25:14 +02:00
3dd4f64cb2 test: remove obsolete mobile-swipe-delete.test.ts
The file tested a Fase 2b.5 interaction — full-swipe commits a delete
with an undo toast — that Fase 5.10 replaced. Swipes on the list detail
view are now a symmetric check/uncheck toggle; delete lives in the
double-tap overlay and in selection mode. The two tests were
describe.skip'd since Fase 5.10 and the UX they describe doesn't exist
anymore.

The swipe-toggle gesture that replaced it is still untested at the E2E
level because Chromium touch emulation can't drive pointer/touch events
into Svelte's component handlers reliably. Adding `playwright install
webkit` to CI would unblock a fresh `mobile-swipe-toggle.test.ts` with
M-06 swipe-right-check, M-07 swipe-left-uncheck, and M-08 wrong-
direction snapback. Noted in plan/fase-5-mobile-ux.md §5.10.b.

Verification
  just test-all → 228 green, 2 skipped (both are the upstream
  Realtime presence bug in realtime-presence.test.ts; everything else
  passes).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 01:22:21 +02:00
a86b296ecd fix(e2e): pin Playwright baseURL to localhost regardless of PUBLIC_APP_URL
Root cause of the recurring "just test-all shows 27/16, playwright alone
shows 43/0" split:

  Justfile loads .env with dotenv-load, which sets PUBLIC_APP_URL to the
  LAN IP from the phone-preview config. playwright.config.ts was reading
  that env and using it as baseURL. The resulting LAN-IP OAuth round-trip
  (browser → GoTrue → Keycloak → browser) adds ~hundreds of ms of
  loopback routing per hop and pushes the $currentCollective hydration
  past Playwright's first synthetic keystroke, producing a silent early
  return in handleAdd (name typed but Enter never triggers a write).

  Running playwright directly skipped dotenv-load, baseURL fell back to
  localhost, and everything passed. Same code, same machine, different
  wrapper.

Fix
  apps/web/playwright.config.ts: baseURL hardcoded to 'http://localhost:5173'.
    The LAN IP stays in PUBLIC_APP_URL for on-device phone previews (step
    2/3 of the mobile-testing recipe in CLAUDE.md), but e2e always hits
    the loopback so the timing profile is deterministic.
  apps/web/tests/fixtures/login.ts: origin-check hardcoded to localhost
    to match.

Verification
  just test-all → exit 0, 228 tests green (34 pgTAP + 140 Vitest
    integration + 11 Vitest unit + 43 Playwright), 4 skipped (upstream
    Realtime presence + WebKit-only touch gestures).
  just test-e2e alone → 43 passed.
  pnpm exec playwright test alone → 43 passed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 00:48:10 +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
f3e8234b70 feat(fase-5.11): selection mode + bulk actions (delete / move / mark-checked)
Long-press on mobile or the new header toggle on desktop puts
/lists/[id] into multi-select mode. Rows render a checkbox on the left,
the stepper + drag handle go away, and swipes + double-tap are disabled.

Chrome during selection mode
  Mobile: header turns into a dark slate-900 action bar with "N selected"
    + Cancel on the left, and a bottom action bar (Delete / Move / Check)
    appears above the BottomTabBar. The sticky add-item form is hidden.
  Desktop: same dark header with Cancel + inline action icons on the right.

Bulk actions
  Delete — one scheduleUndoable with a batch restore (re-inserts all
    snapshots) / batch commit (bulkDeleteItems). Single undo toast.
  Move — opens a bottom sheet / dialog with the collective's other active
    lists + a "Create new list" row that creates an empty list and moves
    into it in a single gesture.
  Mark checked — flips only the selected unchecked items
    (bulkCheckItems with is_checked=false filter), no toggle.

Store helpers (apps/web/src/lib/stores/lists.ts)
  bulkDeleteItems(ids)           → DELETE .in('id', ids)
  bulkMoveItems(ids, newListId)  → UPDATE list_id .in('id', ids)
  bulkCheckItems(ids, userId)    → UPDATE is_checked=true where !is_checked

Entry / exit
  Long-press 500 ms on a row enters with that row pre-selected. Movement
    cancels the long-press intent so it never fights the swipe.
  Single-tap toggles selection while active (instead of invoking the
    no-op short-tap / dbltap-overlay path).
  Cancel button exits + clears selection.

Tests
  apps/web/tests/e2e/selection.test.ts (3 desktop tests)
    SEL-01 toggle enters, row click toggles, Cancel exits
    SEL-02 bulk delete → row gone + undo toast visible
    SEL-03 mark checked → row gains strikethrough
  Mobile long-press tests deferred until WebKit install lands (same
  reason as the swipe-toggle M-series).

i18n additions
  list_select, list_cancel_selection, list_selection_count({n}),
  list_bulk_delete/move/mark_checked, list_undo_bulk_delete({n}),
  list_move_title, list_move_create_new (en/es).

Verification
  just test-e2e → 43 passed + 2 skipped (was 40 + 2).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:33:46 +02:00
1cb408acc2 feat(fase-5.10): /lists/[id] row redesign — buttons + swipe-toggle + overlay
Replaces the checkbox/hover-delete model with an explicit gesture+overlay
flow on /lists/[id].

Row anatomy (new)
  [drag-handle]  [name as button]  [qty stepper  − N +]
  - No checkbox in normal mode.
  - Checked items render with strikethrough + muted text.
  - Drag handle always visible on mobile; revealed on hover on desktop
    (md:opacity-0 md:group-hover:opacity-100). The handle owns the drag
    (pointerdown → dragEnabled=true), so row swipes + taps keep working.

Swipe gestures (symmetric toggle, no delete)
  unchecked + swipe RIGHT → mark checked (green success reveal)
  checked   + swipe LEFT  → mark unchecked (neutral reveal)
  opposite direction for each state is a no-op (snaps back).
  SWIPE_COMMIT_THRESHOLD=120 (was 200 for delete); REVEAL_WIDTH=96.
  Symmetry means undo is the inverse swipe — no undoQueue on toggles.

Double-tap overlay (name + delete + confirm)
  Short tap: no-op. Two taps within DOUBLE_TAP_WINDOW_MS (300 ms) open a
  full-screen dialog (bottom sheet on mobile) with:
    - X close button (top-right)
    - name input
    - Delete button (red) → scheduleUndoable → UndoToast
    - Confirm button (primary) → updateItem({ name })
  Click outside / Escape / X all dismiss without saving.

Tests
  items.test.ts
    D-03 rewritten: double-tap opens overlay, value matches, X closes.
    D-04 rewritten: overlay Delete removes the row; toast locator scoped
      out of itemRow so it doesn't shadow the assertion.
  realtime.test.ts
    R-E-02 updated: Ana renames via overlay → Borja sees new name over
      Realtime UPDATE. (The check/uncheck path is now gestural only and
      chromium touch emulation is too flaky to drive it in E2E; Vitest
      integration R-02 still covers the UPDATE-row-payload invariant.)
  mobile-swipe-delete.test.ts stays describe.skip — will be renamed and
  rewritten for the new semantics once WebKit install lands in CI.

i18n
  list_qty_decrease, list_qty_increase, list_reorder_handle,
  list_edit_item, list_confirm, list_close — en/es.

Verification
  just test-e2e → 40 passed, 2 skipped (same as pre-change).
  Type-check clean.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:20:55 +02:00
d14d6cd5ab feat(fase-5.8): /lists big-button create — match /notes pattern
Remove the sticky bottom create input from /lists. The masthead now hosts
a primary "New list" button next to the Trash icon, styled identically to
the "New note" button on /notes. Click → createList with an empty name →
goto /lists/[id], where a prominent editable title input (above To buy /
Checked) autosaves on blur / input with a 500 ms debounce.

Changes
  apps/web/src/routes/(app)/lists/+page.svelte
    - remove `newListName`, `nameInput`, `handleKeydown`
    - remove the absolute-positioned sticky bottom block
    - handleCreate now creates with name = '' and navigates to the detail
    - actions snippet gains the primary New list button; Trash button
      demoted to ghost icon
  apps/web/src/routes/(app)/lists/[id]/+page.svelte
    - new listName / scheduleNameSave / flushNameSave state (mirrors the
      /notes editor pattern)
    - big editable title <input> at top of content, autosaves on blur
      via renameList
    - contextual header h1 trimmed to a secondary caption-size preview
      on mobile (so the user still sees the list name at the top)
    - flushNameSave on component destroy so unsaved renames commit
  apps/web/messages/{en,es}.json: lists_new_list = "New list"/"Nueva lista"

Tests
  apps/web/tests/e2e/lists.test.ts: createList helper now clicks the
    button, fills the title input, blurs, waits for autosave, and goes
    back to /lists to present the same "list-is-on-the-overview" state
    that C-11 / C-12 expect. C-07 picks up the reload check.
  apps/web/tests/e2e/session.test.ts: S-03 mirrors the new flow for its
    fresh-list setup.

Verification
  just test-e2e → 40 passed, 2 skipped (swipe-delete .skip remains).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:09:33 +02:00
4cc5f694d3 feat(fase-5.12): detail-view chrome — hide MobileTopBar, sticky contextual headers
On /lists/[id], /tasks/[id], /notes/[id], /lists/[id]/session the global
MobileTopBar (hamburger + collective + avatar) is hidden on mobile. The
route's own contextual header (back + title + actions) becomes the only
top chrome and is now sticky with glassmorphism, matching the look of
the MobileTopBar it replaces. BottomTabBar stays visible so the user can
still hop between sections.

Detection: a regex over the path — /^\/(lists\/[uuid](\/session)?|
tasks\/[uuid]|notes\/[uuid])\/?$/ — in (app)/+layout.svelte.

Headers touched:
  - apps/web/src/routes/(app)/lists/[id]/+page.svelte (px-4 on mobile,
    px-8 on md+, transparent/no-border on md+ since the masthead
    provides its own spacing)
  - apps/web/src/routes/(app)/tasks/[id]/+page.svelte
  - apps/web/src/routes/(app)/notes/[id]/+page.svelte

Tests
  tests/e2e/mobile-shell.test.ts gains M-08: on /lists/bbbb..., the
  mobile-hamburger element has count 0 (MobileTopBar removed) while the
  detail's back link + BottomTabBar remain visible. All 5 shell tests
  green.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:02:06 +02:00
d6cea5146f feat(fase-5.10.0): drop shopping_items.unit column
The unit field had no edit path under the redesign (only name + qty
remain in the row; the double-tap overlay is name-only). Users can encode
the unit inside the name when it matters — e.g. "Milk 1L", "Eggs 1 doz".

Changes
  supabase/migrations/011_drop_shopping_items_unit.sql — DROP COLUMN
  supabase/seed.sql — unit values folded into names where relevant
  supabase/tests/002_item_frequency_trigger.sql — remove unit from INSERT
  packages/types — remove unit from ShoppingItem Row/Insert/Update
  apps/web/src/lib/stores/lists.ts — addItem/updateItem signatures
  apps/web/src/routes/(app)/lists/[id]/+page.svelte — purge newUnit /
    editUnit state + inputs + display
  apps/web/src/routes/(app)/lists/[id]/session/+page.svelte — simplify
    quantity-only render
  apps/web/messages/{en,es}.json — remove list_unit_label

Verification
  just test-db  → 34 pgTAP green
  just test-integration → 140 + 2 skipped
  just test-unit → 11 green
  just test-e2e → 39 + 2 skipped

The generated search tsvector on shopping_items.search already indexes
only `name`, so full-text search coverage is unchanged.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 19:00:08 +02:00
5a63e5fc4a feat(dev): expose full auth stack on LAN IP for on-device preview
The dev stack previously mixed two hostnames (`localhost` in some places,
`keycloak` in others). That only worked because the laptop's /etc/hosts
maps `keycloak` to 127.0.0.1. Phones, tablets, or a second laptop had no
such mapping, so the OAuth flow broke the moment you tried to log in from
any non-laptop device.

Switched the SPA, Kong, GoTrue, and Keycloak client to all agree on a
single external host — the laptop's LAN IP (192.168.1.167) — so the full
Keycloak → GoTrue → Supabase → SvelteKit round-trip works from any device
on the same Wi-Fi.

Changes
  .env (root, ungitignored): PUBLIC_SUPABASE_URL / PUBLIC_KEYCLOAK_URL /
    PUBLIC_APP_URL now use the LAN IP (updated locally; tracked via
    apps/web/.env.development below).
  apps/web/.env.development: mirror the LAN IP so `$env/static/public`
    resolves the same on laptop and phone.
  apps/web/vite.config.ts: `server.host: true` — bind Vite to 0.0.0.0.
  apps/web/playwright.config.ts: `baseURL: PUBLIC_APP_URL ?? localhost`
    so E2E uses the same origin the stack is configured with.
  apps/web/tests/fixtures/login.ts:
    - wait for the collective button in the sidebar to render before
      returning (LAN-IP latency surfaced a pre-existing race in
      `handleCreate` where Enter fired before `$currentCollective`
      hydrated, silently no-op'ing).
    - derive expected app origin from PUBLIC_APP_URL.
  apps/web/tests/e2e/items.test.ts: scope D-04 delete assertion to the
    `[role="listitem"]` locator — with undoQueue enabled the toast text
    "Deleted <name>" also matches `getByText(itemName)` and shadowed the
    original check.
  infra/docker-compose.dev.yml:
    - GOTRUE_EXTERNAL_KEYCLOAK_URL and REDIRECT_URI now read from
      PUBLIC_KEYCLOAK_URL / PUBLIC_SUPABASE_URL so they follow the same
      host as the rest of the stack.
    - NEW: GOTRUE_URI_ALLOW_LIST with `/auth/callback` on both the LAN
      IP and localhost. Without an explicit allow-list GoTrue rejected
      `redirect_to=.../auth/callback` and fell back to SITE_URL root,
      stranding `?code=` at `/` and re-triggering signIn → infinite loop.
  keycloak/realm-export.json: `colectivo-web` client gains LAN-IP
    redirectUris and webOrigins (alongside the existing localhost
    entries). Persisted + live-applied via admin API.
  .gitignore: add .claude/ (per-project scheduler runtime state).

Verification
  just test-all → 224 passed, 4 skipped:
    34 pgTAP
    140 Vitest integration + 2 skipped (Realtime presence, upstream bug)
    11 Vitest unit
    39 Playwright + 2 skipped (mobile-swipe touch, WebKit-only)
  Phone sanity check: open http://192.168.1.167:5173 on a LAN device,
  log in as a seed user, full RLS-respecting session.

Caveats
  LAN IP (192.168.1.167) is DHCP-assigned — if it rotates, rerun the
  Keycloak admin API update (realm-export.json needs a new entry) and
  update the three PUBLIC_* URLs. Consider a Tailscale magic-DNS name
  as a stable replacement for the prod-deploy sprint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 16:09:32 +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
3afc911cfc fix(test-utils): bump waitFor default timeout to 10s
Under full `just test-all` load the Phoenix socket can take a beat to
propagate a new subscription's filter to the backend before a mutation
fires, so R-01 occasionally timed out at 5s. Passing runs still resolve
instantly on event arrival — this only widens the flake window.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-13 11:45:54 +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