Commit Graph

129 Commits

Author SHA1 Message Date
xarmian f276745478 fix: sidebar collection counts ignore terminal status settings (#100)
When all items in a collection had terminal statuses (e.g. all bugs
"fixed"), the sidebar showed the total item count instead of 0.

Root cause: ActiveItemCount used `json:"omitempty"`, so a zero value
was omitted from the API response. The sidebar fallback logic then
displayed item_count (total) instead. Additionally, ListCollections
used a hardcoded global terminal status list instead of respecting
each collection's configured terminal_options.

- Remove omitempty from ItemCount/ActiveItemCount so 0 serializes
- Compute active counts per-collection using schema terminal_options
- Show count of 0 in sidebar when collection has items but all are done
2026-04-13 16:47:44 -04:00
xarmian 7ca0463e70 feat: browser-based CLI authentication flow (#97)
Replace the email/password terminal prompt in `pad auth login` with a
browser-based auth flow. The CLI creates a pending session, prints a URL
the user opens in their browser (works for localhost, remote VPS, or
Pad Cloud), and polls until the session is approved.

- Add CLI auth session endpoints (create, poll, approve)
- Add browser approval page at /auth/cli/{code}
- Rewrite `pad auth login` to use browser flow by default
- Keep `pad auth login --interactive` as email/password fallback
- Add login page redirect param support for post-login bounce-back
- Add SQLite and PostgreSQL migrations for cli_auth_sessions table

Closes PLAN-539, IDEA-404
2026-04-13 10:11:16 -04:00
xarmian 1ba9c91992 feat: email unsubscribe for non-transactional emails (#96)
* feat: email unsubscribe for non-transactional emails

Add CAN-SPAM compliant unsubscribe support:

- New email_optouts table (by email address, not user ID) so
  uninvited recipients can opt out without an account
- HMAC-signed unsubscribe tokens (derived from Maileroo API key)
  so links work without authentication
- GET /api/v1/unsubscribe endpoint with simple HTML confirmation page
- Invitation emails now include unsubscribe footer link
- Welcome emails accept unsubscribe URL parameter
- Before sending invitation emails, check opt-out table and silently
  skip opted-out addresses (prevents invite spam)
- Password reset emails are exempt (transactional, user-initiated)

Fixes BUG-256.

* fix: hide "Copy invite link" when code is unrecoverable

For hashed invitations the plaintext code can't be recovered, so the
button was copying a broken URL. Now shows "Sent via email" label
instead. Only shows the copy button when join_url or code is available.

Fixes BUG-255.
2026-04-13 09:14:04 -04:00
xarmian 26af891432 fix: dashboard "New Idea" button now targets first collection (#95)
The dashboard had two buttons that both called requestQuickAdd() with
no argument, so both created tasks. Now:

- "New Task" explicitly targets the tasks collection
- The second button dynamically targets the first non-system, non-task
  collection by sort order (showing its icon and name)
- requestQuickAdd() accepts an optional collection slug, which the
  sidebar respects when choosing the target collection

Fixes BUG-498.
2026-04-12 23:54:00 -04:00
xarmian ac24fb742c fix: breadcrumbs show parent item path for child items (#94)
When viewing a child item (e.g. TASK-101 under PLAN-10), the breadcrumb
now shows "Home / Plans / PLAN-10 / TASK-101" instead of the flat
"Home / Tasks / TASK-101".

- Add parent_slug and parent_collection_slug fields to Go Item model
- Populate them in both single-item and bulk enrichment paths
- Add corresponding TypeScript types
- Update breadcrumb nav to show parent collection and parent item
  when the item has a parent, falling back to the item's own collection

Fixes BUG-516.
2026-04-12 23:53:58 -04:00
xarmian e49a020fc5 fix: mobile UI — sidebar buttons, avatar, share copy (#93)
* fix: mobile UI bugs — sidebar buttons, avatar, share link copy

- Show sidebar + buttons on touch devices using @media (hover: none)
  instead of requiring hover (BUG-537)
- Add user avatar and menu to mobile TopBar header, filling the blank
  space next to the workspace selector (BUG-536)
- Wire ShareDialog copy into existing clipboard fallback utility so
  share link copy works over HTTP (BUG-513)

* fix(mobile): remove extra right padding on mobile topbar

The .topbar has 72px right padding to clear space for the absolutely-
positioned desktop avatar. On mobile the avatar is in the normal flex
flow, so that padding created a blank gap. Override to var(--space-3).
2026-04-12 23:41:35 -04:00
xarmian 1e464ffdac fix: apostrophe in slugs, split auto-close, and move navigation (#92)
- Strip apostrophes in slugify() so "Dave's Workspace" becomes
  "daves-workspace" instead of "dave-s-workspace" (BUG-517)
- Use replaceState when navigating after item move to avoid polluting
  browser history (BUG-538)
- Don't auto-close items when split children are done — splitting work
  out doesn't mean the original is complete (BUG-401)
2026-04-12 23:31:13 -04:00
xarmian da2997c564 fix: check HTTP status in admin settings save (PR #91)
savePlatformSettings used raw fetch which doesn't throw on 4xx/5xx,
so failed saves (CSRF rejection, auth errors) silently showed "Saved".
Now checks resp.ok before reporting success.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-13 01:41:41 +00:00
xarmian b027046605 fix: address review findings for PR #91 (iteration 1)
Ensure make test-pg cleans up Docker containers even when tests fail
by capturing the exit code and running cleanup unconditionally. Remove
dead CSS rules from root page after welcome template simplification.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-13 01:32:12 +00:00
xarmian b2b4feecb9 feat: console navigation, PostgreSQL CI, and operational improvements
- Route root (/) to /console for centralized workspace management
- Update TopBar user dropdown with console nav links (workspaces, settings, billing, admin)
- Move account settings (profile, password, tokens) from workspace settings to /console/settings
- Enhance admin page with email configuration UI and CSRF-protected writes
- Add PostgreSQL CI job to GitHub Actions with race detector on main
- Add `make test-pg` for local PostgreSQL testing via docker-compose
- Expand health/ready endpoint with DB connection pool stats
- Increase item number retry limit for high-concurrency environments
- Add concurrent store benchmarks and FTS search quality tests
- Add AGENTS.md for multi-agent development guidance
2026-04-13 01:29:15 +00:00
xarmian b7808f12a1 fix: address Codex review findings for PR #90 (iteration 2)
Update admin frontend to handle new paginated user list response shape
({ users, total } instead of bare array). Add legacy pad_session cookie
fallback to SessionAuth middleware matching validateSessionCookie. Exempt
/api/v1/plan-limits from RequireAuth so billing page can read limits
without authentication.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-13 01:27:51 +00:00
xarmian 92580905bb feat: cloud hardening and security follow-ups (PLAN-503)
Address 11 issues identified during the PLAN-427 security review:

Critical/High:
- Stripe customer-to-user mapping with indexed lookup (TASK-505)
- OAuth provider linking with explicit consent model (TASK-504)
- CSRF tokens on admin console mutations (TASK-506)
- Rate limiting on cloud admin and OAuth endpoints (TASK-507)

Medium:
- __Host- cookie prefix for subdomain protection (TASK-510)
- Billing portal verifies customer ownership server-side (TASK-515)
- Transactional account deletion with rollback (TASK-509)
- Streaming data export with 60s timeout (TASK-508)
- Migration registration for new columns (TASK-514)

Low:
- Billing page fetches actual plan limits from API (TASK-511)
- Admin user search/filter pushed into SQL with pagination (TASK-512)
2026-04-13 01:03:12 +00:00
xarmian e6f123a4c3 fix: address Codex review findings for PR #89 (iteration 2)
- Exempt /admin/plan from RequireAuth and CSRF middleware so the
  pad-cloud sidecar can call it with cloud_secret body auth
- Add X-CSRF-Token header to admin console PATCH requests
- Send plan_overrides as a JSON string (not parsed object) to match
  backend *string decoder expectation
- Restrict confirm-only account deletion to cloud mode to prevent
  password users from bypassing re-auth

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-13 00:54:21 +00:00
xarmian b2ec0a4f55 fix: address review findings for PR #89 (iteration 1)
Fix admin limits endpoint returning wrong defaults for pro plan, correct
swapped billing page usage numbers, validate expires_at format in plan
endpoint, and handle errors properly in admin stats endpoint.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-04-13 00:24:36 +00:00
xarmian d0518216c5 feat: add cloud infrastructure for hosted Pad (PLAN-427)
Add the foundation for running Pad as a hosted service at app.getpad.dev.
Same binary in cloud mode with a thin sidecar for OAuth and Stripe.

Cloud mode (PAD_CLOUD=true):
- PAD_CLOUD flag with cloud secret for sidecar communication
- Account-level billing: plan field on users, CheckLimit enforcement
- Free/Pro tiers with configurable limits stored in platform_settings
- Three-tier limit resolution: user overrides → DB defaults → hardcoded fallback
- Plan enforcement on workspace, item, member, webhook, and token creation

Authentication & security:
- OAuth login endpoint (POST /api/v1/auth/oauth-login) with cloud secret gate
- Verified email requirement for OAuth, 2FA bypass protection
- Cloud secret rotation support (comma-separated keys)
- TOTP secret encryption at rest (AES-256-GCM via PAD_ENCRYPTION_KEY)
- Rate limiting on OAuth login endpoint
- Bootstrap disabled in cloud mode
- Password max length enforcement (128 chars)
- Config file written with 0600 permissions

Admin & billing:
- Admin user management API (list, detail, update plan/overrides)
- Configurable plan limits API (GET/PATCH /api/v1/admin/limits)
- Platform stats endpoint
- Admin plan endpoint for sidecar to set user plans
- GDPR: account deletion and data export endpoints

Console UI (cloud mode only):
- /console — workspace list with owned/shared sections
- /console/new — create workspace wizard with slug preview
- /console/settings — profile, password, API tokens
- /console/billing — plan status, upgrade/manage links
- /console/admin — user management, plan overrides, limits editor
- OAuth buttons (GitHub/Google) on login page in cloud mode

Auto-create default workspace on signup in cloud mode.
Migration 035: plan, plan_expires_at, stripe_customer_id, plan_overrides on users.
2026-04-12 17:43:40 +00:00
xarmian 94d35509a4 feat: share links with hardened security, anonymous access, and analytics (#88)
* feat: share links with hashed tokens and /s/{token} route

Add share_links and share_link_views tables with CRUD API and
anonymous resolution route (TASK-421).

Data model:
- share_links: token_hash (SHA-256), target_type/id, permission,
  password_hash, expires_at, max_views, require_auth, view tracking
- share_link_views: per-view records with fingerprint/user tracking

Token security:
- 192-bit entropy (crypto/rand), URL-safe base64 encoding
- SHA-256 hashed at rest, raw token returned only once on creation
- Generic 404 for invalid tokens (no info leakage)
- /api/v1/s/ exempt from auth middleware for anonymous access

API endpoints:
- POST /items/{slug}/share-links — create item share link
- POST /collections/{coll}/share-links — create collection share link
- GET /items/{slug}/share-links — list share links for item
- GET /collections/{coll}/share-links — list for collection
- DELETE /share-links/{id} — revoke share link
- GET /s/{token} — resolve share link, return shared content

D8: Anonymous users are ALWAYS read-only. View count and unique
viewers tracked on each resolution.

* feat: anonymous share page + share link management UI

Add minimal-chrome share link viewer page and share link CRUD in
the share dialog (TASK-422 + TASK-425).

Share page (/s/{token}):
- New SvelteKit route at /s/[token] for anonymous viewing
- Renders item (title, fields, markdown content) or collection
  (name, item list) with no app chrome (no sidebar/topbar)
- Handles require_auth links with "Sign in to view" prompt
- Root layout bypasses auth checks for /s/ routes
- "Powered by Pad" footer

Share dialog updates:
- "Share links" section below existing grants
- Create/list/revoke share links for items and collections
- Copy-to-clipboard for share URLs
- Newly created links highlighted with "only shown once" notice
- View count and auth-required badges

API client:
- ShareLink type added
- shareLinks.* methods for CRUD
- share.get(token) for anonymous resolution

* feat: share link constraints + view analytics

Add password protection, expiry, max views, and view history
endpoints for share links (TASK-423 + TASK-424).

Constraints (TASK-423):
- CreateShareLink accepts ShareLinkOptions: password, expires_at,
  max_views, require_auth, restrict_to_email
- Password hashed with bcrypt, verified on /s/{token} resolution
- Password-protected links return {require_password: true} prompt
- Expiry and max_views already validated by ValidateShareLink

Analytics (TASK-424):
- GET /share-links/{id}/views returns view history with fingerprint,
  user ID, and timestamp
- Response includes total_views, unique_viewers, last_viewed_at
- View history stored per-view in share_link_views table

* fix: harden share links — XSS, access control, data leakage, and UX gaps

- Sanitize rendered markdown with DOMPurify before {@html} injection (XSS)
- Force require_auth=true when restrict_to_email is set (access bypass)
- Reject malformed non-empty JSON bodies with 400 instead of failing open
- Return public DTOs on share endpoints to prevent leaking internal IDs,
  creator info, assignees, schemas, and other sensitive fields
- Enforce max_views atomically via conditional UPDATE to prevent races
- Fix collection share rendering: read items from top-level response key
  and map ref/status fields correctly
- Add password prompt UI and X-Share-Password header support so
  password-protected links can actually be unlocked by the frontend

* fix: follow-up hardening for share links

- Sanitize catch fallback in rendered markdown (XSS edge case if marked throws)
- Remove query-string password fallback; accept only X-Share-Password header
  to avoid leaking passwords in logs, browser history, and referrers
- Return 500 on ListItems DB failure instead of swallowing as empty collection
- Normalize restrict_to_email with ToLower/TrimSpace on create and compare
- Fix malformed JSON check for chunked bodies (ContentLength == -1)
  by checking for io.EOF instead of ContentLength > 0
- Remove internal share_link.id from public DTO responses
- Use clientIP(r) helper for consistent fingerprinting instead of raw
  X-Forwarded-For which is spoofable and includes port in RemoteAddr
- Distinguish DB errors from not-found in share link delete handler

* fix: final hardening pass for share links

- Move auth/email gate before password check to prevent unauthenticated
  callers from probing passwords and burning bcrypt CPU
- Wrap view recording (counter increment, unique-viewer accounting, view
  insert) in a single transaction so a failed insert rolls back the
  consumed view count instead of silently losing it
- Add X-Share-Password to CORS AllowedHeaders so cross-origin
  deployments can send the custom header without preflight rejection
- Validate expires_at (RFC3339) and max_views (> 0) on share link
  creation; return 400 for invalid constraints instead of creating
  immediately-unusable links
- Cap view-history endpoint limit to 1000 to prevent unbounded queries
2026-04-11 16:40:18 -04:00
xarmian c6d19837c8 feat: collection & item grants, guest access, share dialog (PLAN-407 Phase 3) (#87)
* feat: collection and item grants tables + permission resolution

Add grant tables, CRUD operations, and permission resolution for
guest access and member overrides (TASK-417).

Data model:
- collection_grants table (id, collection_id, workspace_id, user_id,
  permission, granted_by) with CASCADE on collection/user delete
- item_grants table (same structure, references items)
- Indexes for user/collection/item lookups

Store methods:
- Create/Get/List/Delete for both collection and item grants
- ListUserGrants: all grants for a user across a workspace
- RevokeAllUserGrants: bulk delete for member removal
- ResolveUserPermission: full 5-step resolution per DOC-406
  (owner → item grant → collection grant → membership → deny)

API endpoints:
- GET/POST/DELETE /collections/{coll}/grants — collection grant CRUD
- GET/POST/DELETE /items/{slug}/grants — item grant CRUD
- GET /users/{userID}/grants — all grants for a user in workspace

All grant endpoints are owner-only for creation/deletion.

* feat: grant revocation + member removal with grant choice

Update member removal to support D4: owner chooses whether to revoke
all grants when removing a member (TASK-489).

- DELETE /members/{userID}?revoke_grants=true → remove membership AND
  all collection/item grants (full removal)
- DELETE /members/{userID} (or revoke_grants=false) → remove membership
  but keep grants (user becomes a guest with existing access)
- Audit log records whether grants were revoked
- CASCADE DELETE on collection/item deletion already handles cleanup
  (via ON DELETE CASCADE in the grants migration)

* feat: share dialog UI for items and collections + grant types

Add a share dialog component for managing grants on items and
collections, plus TypeScript types and API client methods (TASK-419).

Frontend:
- ShareDialog.svelte: reusable modal for listing/creating/revoking
  grants, with email input, permission select, and revoke buttons
- Item detail page: "Share" button in meta-actions (owner-only)
- Collection page: "Share" button in header actions (owner-only)

TypeScript:
- CollectionGrant and ItemGrant types added
- API client: grants.listCollectionGrants, createCollectionGrant,
  deleteCollectionGrant, listItemGrants, createItemGrant,
  deleteItemGrant, listUserGrants

Guest home screen (TASK-418) deferred — requires layout-level guest
detection which will be implemented when guest routing is built.

* feat: guest access — grants-based workspace access for non-members

Allow authenticated users with grants (but no workspace membership)
to access workspaces as guests (TASK-418).

Backend:
- UserHasGrantsInWorkspace: checks if user has any collection/item
  grants in a workspace
- GuestVisibleCollectionIDs: returns collections visible to a guest
  via collection grants + collections containing granted items
- RequireWorkspaceAccess: after member-nil check, falls through to
  grant check; sets role to "guest" if grants exist
- VisibleCollectionIDs: non-members now checked for guest grants
  instead of returning empty
- GetUserWorkspaces: includes guest workspaces (is_guest flag)
- GetWorkspacesBySlugForUser: JOINs on grants tables so workspaces
  resolve for guests
- roleLevel: "guest" = 0 (below viewer, blocks role-gated actions)

Frontend:
- Workspace.is_guest field in TypeScript type
- Sidebar: hides Dashboard, Roles, Activity, Settings, and "New
  collection" button for guests; shows "Shared with you" header

* feat: wiki-link rendering with locked icon for hidden items

Update wiki-link rendering to show a 🔒 locked icon when the linked
item is in a collection the user can't see (TASK-420).

- renderMarkdown accepts optional visibleCollectionSlugs parameter
- Items in hidden collections render as "🔒 Title" with tooltip
- Unresolved links still render as broken (no change)
- Username param added to renderMarkdown for correct URL construction
- TimelineCommentCard and CommentThread accept username prop

* fix: harden grant security — 9 findings from Codex review

- Item grants no longer leak collection-wide read access; guests with
  item-level grants see only their granted items, not the full collection
  (GuestVisibleResources two-level filter + ItemIDs in ListItems SQL).
- Edit grants are now enforced: mutating handlers (create/update/delete
  items, comments, reactions, links, versions) resolve grant-based
  permissions for guests via requireEditPermission + ResolveUserPermission.
- Grant list endpoints restricted to owners (collection/item grants) or
  owner-or-self (user grants) to prevent metadata/email enumeration.
- Guests blocked from listing workspace members; invitation details
  restricted to owners only.
- Grant deletion scoped to workspace_id to prevent cross-workspace
  deletion by guessing grant IDs.
- Member removal now revokes grants by default (opt-out with
  ?revoke_grants=false) and propagates revocation errors instead of
  silently discarding them.
- Guest workspace listing properly propagates DB errors instead of
  swallowing them.
- PostgreSQL subquery alias added to UserHasGrantsInWorkspace to fix
  silent guest-access failures on Postgres deployments.

* fix: harden item-level grant isolation — 7 findings from Codex re-review

- /changes endpoint now filters by item-level grants so guests with one
  item grant no longer receive updates for every item in that collection.
- Search results filtered by item-level grants (new ItemIDs field in
  SearchParams) so guests can't discover other items via search.
- Relationship/summary endpoints (item links, children, progress,
  activity, dashboard) all apply item-level visibility checks via
  isItemVisibleToGuest(), preventing metadata leakage through related
  item titles, statuses, and counts.
- Grants now work as member overrides: a viewer with an edit grant can
  edit the granted item (requireEditPermission falls back to
  ResolveUserPermission for members below editor role).
- handleMoveItem now requires edit permission on the target collection,
  not just visibility, preventing guests from moving items into
  view-only collections.
- Member removal + grant revocation is now atomic via
  RemoveWorkspaceMemberAndRevokeGrants() which wraps both operations
  in a single database transaction.
- Guest-access DB errors in middleware now return 500 with slog.Error
  instead of being silently collapsed into a 403 forbidden response.

* fix: close remaining grant isolation gaps — 10 findings from Codex round 3

- Workspace token endpoints (create/list/delete) now require owner role,
  preventing guests from enumerating or revoking API tokens.
- Legacy document endpoints (list, get, context, bulk-read, backlinks,
  links) now require at least viewer role, blocking guests entirely
  since documents are outside the grants model.
- Global search no longer relies on workspaceRole() (which is unset
  outside RequireWorkspaceAccess); detects guests via IsWorkspaceMember
  and applies item-level filtering. Multi-workspace search now uses
  GuestVisibleResources for guest workspaces.
- SSE event filtering now checks item IDs for guests with item-level
  grants, not just collection slugs, preventing live event leaks.
- Role board passes ItemIDs through RoleBoardParams so guests only
  see items they have grants on, not the entire collection.
- VisibleCollectionIDs for members with "specific" collection access
  now merges direct grants (collection + item grants), so grant
  overrides work for restricted members.
- Plans-progress endpoint filters plan items and children by item-level
  grants for guests, preventing one plan grant from exposing all plans.
- Webhook listing now requires owner role since URLs may contain secrets.
- Agent role item counts use item-level filtering for guests.
- Link deletion checks item-level visibility on both endpoints, not
  just collection-level.

* fix: close member grant escalation and remaining edge cases — round 4

- Item grants for restricted members no longer escalate to collection-
  wide visibility. VisibleCollectionIDs now merges only direct collection
  grants (not item-derived collections) into member access. Item-level
  filtering (guestResourceFilter, isItemVisibleToGuest, requireItemVisible)
  now applies to both guests AND restricted members with item grants,
  closing the gap where a member with specific collection access plus
  one item grant could see/edit all items in that collection.
- Guests blocked from workspace-level activity feed (/activity) which
  exposed audit events (member invites, role changes) with operational
  metadata. Requires at least viewer role.
- Global search no longer returns zero results for item-only guests.
  Store.Search early-return now checks both CollectionIDs and ItemIDs
  are empty before short-circuiting, so item-level grants work in
  global (multi-workspace) search.
- UserHasGrantsInWorkspace now excludes item grants on soft-deleted
  items, preventing phantom guest access to a workspace shell with
  no visible content when the only granted item is archived.

* fix: prevent grant filter from overriding member access, close SSE/dashboard/collection leaks — round 5

- guestResourceFilter now returns nil/nil for members with "all"
  collection access, preventing item grants from accidentally replacing
  their full visibility. Only guests and members with "specific"
  collection access get item-level filtering applied. This fixes a
  regression where a normal member receiving one item grant would lose
  access to all other items.
- requireItemVisible uses guestResourceFilter (with the same scoping)
  instead of raw GuestVisibleResources, so the member-access check is
  consistent throughout all code paths.
- SSE event filtering now denies collection-less events (workspace
  updates, legacy document events) for guests, preventing metadata
  leakage through realtime event payloads.
- Dashboard recent activity filters out workspace-level entries (no
  DocumentID) for guests, preventing audit metadata leakage.
- All grant visibility queries (UserHasGrantsInWorkspace,
  GuestVisibleCollectionIDs, GuestVisibleResources) now join the
  collections table and require deleted_at IS NULL, so grants on
  soft-deleted collections no longer provide phantom access.

* fix: make item grants additive for restricted members, close write/search/SSE gaps — round 6

- guestResourceFilter now merges member_collection_access + system
  collections + collection grants into fullCollIDs for restricted members,
  making item grants additive to existing access. Previously, item grants
  replaced the member's normal collections, causing members with one item
  grant to lose all their other collection visibility.
- Added ListSystemCollectionIDs store method for system collection lookup.
- Search (both global and workspace-scoped) now applies item-level
  filtering for restricted members with item grants, not just guests.
  Previously VisibleCollectionIDs included item-granted collections as
  full-access, leaking all items in those collections via search.
- SSE event filtering now builds item-level filters for restricted
  members with item grants (previously only for non-members/guests),
  and merges member collections into the full-access set.
- Role board reorder now uses requireItemVisible + requireEditPermission
  per item instead of collection-only visibility check, preventing
  restricted editors from reordering items in item-granted collections.
- View create/update/delete now check requireEditPermission on the
  collection (via requireViewEditable), not just collection visibility.
- GetUserWorkspaces guest query now joins collections/items tables to
  exclude grants on soft-deleted resources, matching the behavior of
  UserHasGrantsInWorkspace.

* fix: block guests from legacy doc versions/activity, fix ListItems early return, SSE fail-closed — round 7

- Legacy document version handlers (handleListVersions, handleGetVersion)
  and document activity handler (handleListDocumentActivity) now require
  at least viewer role, blocking guests from reading version history and
  activity for unrelated legacy documents.
- ListItems early return now checks both CollectionIDs and ItemIDs are
  empty before short-circuiting, matching the fix already applied to
  Search. This fixes item-only guests seeing zero results from /items,
  dashboard, role board, and agent-role counts.
- SSE item-grant filtering now fails closed on GuestVisibleResources
  errors: installs empty item/collection filter sets instead of falling
  through with nil (which would pass all events through).
- Role board reorder removed top-level requireMinRole("editor") so the
  per-item grant-aware requireEditPermission checks can run for guests
  and viewers with edit grants, consistent with other mutating handlers.
2026-04-11 14:46:24 -04:00
xarmian 0587deba41 feat: UI for managing member collection visibility
Add API endpoints and settings UI for managing per-member collection
access (TASK-416).

Backend:
- GET /members/{userID}/collection-access — returns mode + granted IDs
- PUT /members/{userID}/collection-access — sets mode + collection IDs
  (owner-only)

Frontend:
- API client: getMemberCollectionAccess, setMemberCollectionAccess
- Settings Members tab: "Manage access" button per member (owner-only)
- Expandable inline panel with all/specific toggle
- Collection checkbox list: non-system collections toggleable, system
  collections always checked + disabled with "system" tag
- Save/cancel with optimistic update
2026-04-11 01:35:51 +00:00
xarmian d74431fbb3 feat: collection-level visibility + system collections
Add per-member collection visibility controls and mark conventions/
playbooks as system collections (TASK-413 + TASK-415).

Data model:
- workspace_members: new collection_access column ('all' or 'specific')
- New member_collection_access table (workspace_id, user_id, collection_id)
- collections: new is_system column, set for conventions and playbooks

Store methods:
- VisibleCollectionIDs(workspaceID, userID) — returns nil for "all"
  access, or specific IDs (including system collections) for "specific"
- SetMemberCollectionAccess/GetMemberCollectionAccess for CRUD
- All collection queries include is_system in SELECT/scan
- Export/import handles is_system field

Default collection definitions:
- conventionsCollection and playbooksCollection set IsSystem=true
- New workspaces get system flag on seed

D7: default collection_access is "all" — absence of restrictions
means full access. System collections always visible to members.
2026-04-11 01:02:06 +00:00
xarmian 359876ae1c feat: username editing in account settings
Add username editing to the web UI account settings page and
backend profile update handler (TASK-496).

Backend:
- handleUpdateCurrentUser accepts optional username field
- Validates format, reserved words, and uniqueness (skips if unchanged)
- Returns clear errors for taken/invalid/reserved usernames

Frontend (settings page):
- Username field with @ prefix indicator below name
- Debounced real-time availability checking (400ms)
- Status indicators: checking/available/taken
- Save blocked when username is invalid
2026-04-10 23:54:41 +00:00
xarmian 38e6b4e5b1 feat: rewrite web UI routing to /{username}/{workspace}/... pattern
Restructure all workspace-scoped web URLs to include the owner's
username as a prefix (TASK-411).

Route structure:
- Moved web/src/routes/[workspace]/ → [username]/[workspace]/
- All workspace pages extract both username and workspace from URL
- Auth routes (/login, /register, /join, etc.) unchanged

Backend:
- Workspace model adds OwnerUsername field (populated by JOIN)
- All workspace queries JOIN users table for owner_username
- TypeScript Workspace type updated with owner_username

Frontend (24 files updated):
- All route pages: added username derived, updated URL constructions
- Sidebar, TopBar, WorkspaceSwitcher: use owner_username for links
- ItemCard, TableView, ChildItems, NestedChildren: username in links
- CommandPalette, OnboardingChecklist, CreateWorkspaceModal: updated
- Root page redirect includes owner_username
- Wiki-link markdown utility accepts username parameter

What did NOT change:
- API client (client.ts) — still uses workspace slug for API calls
- Go API routes — unchanged
- CLI — unchanged
2026-04-10 23:47:25 +00:00
xarmian b1357799a9 feat: username validation, reserved words, and registration flow
Add username support to registration with validation, reserved words,
and real-time availability checking (TASK-409).

Backend:
- ValidateUsername() with format/length/reserved word checks
- 35+ reserved usernames (route conflicts, system terms)
- GET /auth/check-username endpoint for real-time validation
- handleBootstrap auto-generates username from name (D1)
- handleRegister accepts optional username, auto-generates if omitted

Frontend:
- Register page: username field with auto-generation from name
- Join/invite page: same username field in register mode
- Debounced availability checking (400ms) via /auth/check-username
- Inline status indicators (checking/available/taken)
- API client: register() accepts username, new checkUsername() method
2026-04-10 23:12:59 +00:00
xarmian 520a7ca27b feat: add owner_id to workspaces with backfill
Add owner_id column to workspaces table and backfill existing
workspaces from membership data (TASK-410 + TASK-480).

- SQLite migration 030 and Postgres migration 010 add owner_id column
  with indexes on (owner_id) and (owner_id, slug)
- Workspace, WorkspaceCreate models updated with OwnerID field
- All workspace SELECT queries include owner_id
- CreateWorkspace INSERT includes owner_id
- handleCreateWorkspace sets owner_id from authenticated user
- backfillWorkspaceOwners extended: sets owner_id using D3 logic
  (earliest owner member → earliest member → first admin)
- TypeScript Workspace type updated

Global UNIQUE(slug) constraint preserved for now; will be replaced
with UNIQUE(owner_id, slug) in TASK-412 when auth-scoped resolution
needs it.
2026-04-10 22:56:32 +00:00
xarmian f80876a52e feat: add username column to users table
Add username field to the user data model as the foundation for
the multi-user permissions system (PLAN-407, TASK-408).

- SQLite migration 029 and Postgres migration 009 add username column
  with partial unique index (WHERE username != '')
- User, UserCreate, UserUpdate Go structs updated
- Store: CreateUser, UpdateUser, scanUser, userColumns updated
- New GetUserByUsername store method (case-insensitive lookup)
- All auth handler JSON payloads include username field
- WorkspaceMember struct and ListWorkspaceMembers query include username
- TypeScript User type and API client inline types updated

Column is empty string by default; TASK-482 will backfill existing
users and TASK-409 will add validation/registration flow support.
2026-04-10 22:40:07 +00:00
xarmian bc8c7090bc fix: use index key for timeline activity changes to avoid duplicate field keys
Activity entries can have the same field changed multiple times (e.g.
status: active → completed; status: completed → planned). The {#each}
block was keyed by change.field which caused each_key_duplicate errors
in Svelte. Switch to array index key since duplicate fields are valid.
2026-04-10 20:57:09 +00:00
xarmian 7432ffb1ec fix: emoji picker dropdown escapes dialog overflow clipping
Portal the dropdown into the nearest <dialog> element so it stays in
the browser's top layer, and temporarily set overflow:visible on the
dialog while the picker is open so it isn't clipped.
2026-04-10 20:06:19 +00:00
xarmian cabb552faf feat: add EmojiPickerButton and replace plain-text emoji inputs
Create a reusable EmojiPickerButton component that wraps EmojiPicker
in a compact dropdown toggle. Replace the plain <input type="text">
emoji fields in quick action icons (EditCollectionModal) and role
icons (roles page) with the new picker for a consistent UX.
2026-04-10 19:24:46 +00:00
xarmian 44f249994e feat: add Pad logo wordmark to topbar
Add PadLogo component to the left side of the workspace top bar.
Shows "Pad" in bold accent-blue; includes a hidden "Cloud" badge
variant for future Pad Cloud branding (TASK-205). Reserve left/right
padding in the topbar so workspace buttons never overlap the logo
or user menu.
2026-04-10 19:20:39 +00:00
xarmian 50975e7b91 UI housekeeping: editor stability, sidebar UX, board DnD, quick-add (#81)
* fix: sidebar + button for new collections, desktop sidebar reopen affordance, auto-resizing title editor

- Add "+" button next to Collections header in sidebar to open CreateCollectionModal (IDEA-130)
- Show a chevron tab at the left edge when sidebar is hidden on desktop so users can reopen it without knowing the keyboard shortcut (IDEA-131)
- Switch item title editor from single-line input to auto-resizing textarea so long titles are fully visible while editing (BUG-27)

* fix: reduce editor save jitter by increasing debounce and wiring up SSE guards

Three root causes for BUG-25 (page jumps, stutters, lost keystrokes while typing):

1. Debounce too short (500ms → 1200ms): fast typists frequently pause
   ~500ms between words, triggering saves mid-thought
2. Item page never updated editorStore.lastSaveTime or dirty flag, so
   the SSE handler's 2-second guard never activated — every self-triggered
   save caused an SSE item_updated → re-fetch → store update cycle
3. saveStatus was set to 'saving' on every keystroke (before debounce),
   causing unnecessary re-renders; now only set when save actually fires

Also sets collectionStore.activeItem from the item page so the SSE
handler's active-item guard works correctly.

* fix: suppress timeline refresh during active content editing

The ItemTimeline's SSE handler was re-fetching the entire timeline on
every item_updated event, including self-triggered content saves. This
caused visible re-rendering/shakiness in the timeline section each time
the debounce fired. Now skips item_updated events within 3 seconds of
the last editor save, matching the existing SSE guard pattern.

* fix: eliminate spurious network requests from self-triggered SSE events

Each content save was causing 3 network requests instead of 1: the save
itself, plus /collections and /children re-fetches triggered by the SSE
item_updated event echoing back from our own save.

- Workspace layout SSE handler: skip all side-effects (loadCollections,
  item refetch) for self-triggered content saves using editorStore.dirty
  and lastSaveTime guards
- ChildItems SSE handler: skip item_updated events from self-saves since
  content edits can't affect children
- Timeline SSE handler: remove item_updated from relevant events entirely
  (version diffs appear on next natural refresh); debounce remaining
  events to prevent rate-limit errors from SSE replay on reconnect

* feat: collapsible topbar, sidebar close buttons, quick-add modal, rate limit bump

- Topbar: centered workspace list, collapsible via chevron button or
  Cmd-\, hover-reveal expand tab when hidden, persisted to localStorage
- Sidebar: added close button in footer for independent hiding
- Cmd-\ now toggles both sidebar and topbar together
- Quick-add: sidebar + buttons and "New Item" button open a modal with
  auto-resizing textarea for title input instead of creating "Untitled"
  items (IDEA-132, IDEA-133)
- Dashboard "New Idea"/"New Task" buttons now link to /new form page
- API rate limit bumped from 100/min to 600/min — more appropriate for
  a local-first tool with SSE-driven UI cascading refreshes

* fix: board view drag-and-drop snap-back and re-render cascade

Root cause: isDragging was set to false before the async onStatusChange
API call, triggering a reactive $effect that overwrote columnData with
stale positions — item snapped back to the original column then bounced
to the new one. Additionally, handleReorder fired per-item API calls
that each triggered SSE events, causing cascading re-renders.

- Add dropCooldown flag that freezes columnData for 2s after a drop,
  preventing the $effect from overwriting the visual state while API
  calls and SSE events settle
- Only persist sort_order for items whose order actually changed
- On failed moves: skip reorder, immediately drop cooldown so the
  original state restores cleanly to the correct position
- handleStatusChange re-throws on failure so BoardView can distinguish
  success from failure

* feat: add theme toggle and quick-add modal to sidebar

- Light/dark mode toggle button in sidebar footer row (sun/moon icon),
  to the left of the notification bell (IDEA-134)
- Quick-add modal with auto-resizing textarea for title input, triggered
  from per-collection + buttons and "New Item" button (IDEA-132, IDEA-133)
- Removed old "Untitled" item creation flow from sidebar

* fix: remove all /new page references, use quick-add modal and inline create

- Empty collection "Create" button now opens the inline quick-create
  input instead of navigating to /new (BUG-29)
- Cmd-N opens the sidebar quick-add modal (defaults to active collection
  or Tasks) instead of navigating to /new
- Dashboard "New Idea"/"New Task" buttons trigger quick-add modal
- Onboarding checklist links go to collection pages instead of /new
- Cleaned up dead quickCreate function and unused imports from dashboard

* chore: remove dead /new page route

All item creation now goes through the sidebar quick-add modal or
collection page inline create. The /new form page is no longer
referenced anywhere.
2026-04-10 11:33:12 -04:00
xarmian 1d26c2b542 feat: add workspace top bar with drag-to-reorder (#80)
* feat: add workspace top bar with drag-to-reorder

Replace the sidebar WorkspaceSwitcher dropdown with a dedicated top bar
that provides fast workspace switching and a user menu.

Desktop:
- Horizontal bar above sidebar + content with workspace icons (colored
  first-letter circles) and names as real <a> links
- Drag-and-drop reorder via svelte-dnd-action
- User avatar on right with dropdown (settings, theme toggle, sign out)
- "+" button to create new workspaces

Mobile:
- Full-width fixed bar at top when sidebar opens (above sidebar/backdrop)
- Tap workspace to navigate and close sidebar
- Reorder button opens full-screen vertical list with drag handles
- Sidebar starts below the top bar with adjusted positioning

Backend:
- Migration 028: add sort_order to workspace_members (per-user ordering)
- GET /workspaces now returns workspaces in user's sort order
- PUT /workspaces/reorder endpoint for persisting order

Sidebar simplified:
- Removed WorkspaceSwitcher component, user section, theme toggle
- Theme initialization moved to root layout
- Cleaner footer with search, settings, and notification bell

Implements IDEA-129, relates to IDEA-126.

* fix: address codex review findings (P1+P2)

- Remove unsupported `direction` option from svelte-dnd-action dndzone
- Add Postgres migration 008 for workspace_members.sort_order
- Handle sql.ErrNoRows gracefully in reorder endpoint for admins who
  aren't members of all workspaces
- Restore mobile sign-out: add user name + logout button to sidebar
  footer on mobile (was only in desktop TopBar user menu)
2026-04-10 01:22:49 -04:00
xarmian 7ef4506cfa fix: replace scattered tab-resume refetches with layered sync system
When the browser tab lost focus and regained it, 5 independent
onTabResume callbacks all fired simultaneously, flooding the server
with redundant requests. This replaces that pattern with a 4-layer
sync architecture:

1. Replay buffer — per-workspace ring buffer stores recent events with
   monotonic IDs. On SSE reconnect, missed events are replayed via
   Last-Event-ID so the client is already caught up.

2. Last-Event-ID support — SSE handler reads the header, replays from
   buffer, or sends sync_required if the gap is too large.

3. Incremental sync — new /changes?since=<ms> endpoint returns only
   modified/deleted items since a timestamp, including archived items
   for view consistency.

4. Centralized sync coordinator — single decision tree replaces 5
   scattered callbacks. Short absences skip sync entirely, SSE-covered
   gaps need no API calls, and full refresh is a last resort.

Key robustness details:
- Global event IDs via Redis INCR for multi-instance safety
- Server-time cursors to avoid client clock skew
- Safe cursor management (only advances on confirmed sync)
- 9 new tests for replay buffer and event ID behavior

Fixes BUG-26.
2026-04-10 04:15:43 +00:00
xarmian 9d90308e20 fix: resolve plan view crash from duplicate children and tiptap link conflict
Three fixes:

1. GetChildItems returned duplicate rows when an item was linked to a parent
   via multiple link types (e.g. both "parent" and "implements"), causing
   Svelte's {#each} to throw each_key_duplicate. Added SELECT DISTINCT.

2. StarterKit v3.20.4 now includes Link by default, conflicting with our
   custom SafeLink extension. Disabled StarterKit's built-in link.

3. Migration runner now tolerates "duplicate column name" errors on
   ALTER TABLE ADD COLUMN, making migrations idempotent when partially
   applied (e.g. server crash mid-migration).
2026-04-09 14:49:03 +00:00
xarmian 1ac0abc305 fix: resolve 2FA Codex review findings (Postgres bools, recovery code race, web login flow)
- Use dialect.BoolToInt() for totp_enabled updates instead of hardcoded
  1/0 integers that fail on PostgreSQL BOOLEAN columns
- Add optimistic locking to ConsumeRecoveryCode to prevent double-spend
  under concurrent requests
- Add 2FA challenge step to web login and join pages so browser login
  works for accounts with TOTP enabled
2026-04-08 20:30:39 +00:00
xarmian 1198f79492 ui: style board view columns to match roles page swim lanes
Add background, border, and border-radius to board columns for a
boxed card-like container look. Round header top corners to match,
tighten card gap, and bump header padding/weight for consistency
with the roles page lane styling.
2026-04-07 22:01:12 +00:00
xarmian 62c85164f9 fix: count implements links as children for progress tracking
Progress bars, child item lists, and parent enrichment all only
counted 'parent' link types. Items connected via 'implements' links
(e.g. tasks implementing a plan) were invisible to the progress
system, showing 0/0 even when all implementing items were done.

Backend: define childLinkTypes ('parent' + 'implements') and update
all 8 SQL queries (GetItemProgress, GetAllItemProgress, GetChildItems,
PopulateHasChildren, GetParentMap, GetParentForItem, and both
terminal-status helpers) to use IN ('parent','implements').

Frontend: remove the standalone "Derived Closure" banner that
duplicated relationship info. Fold closure summary into the matching
relationship group as an inline annotation. Add implements-link
dedup so children shown in ChildItems aren't repeated in Relationships.
2026-04-07 21:54:04 +00:00
xarmian bde15d45ca Rename Phases to Plans, clean up deprecated aliases (#71)
* Rename "Phases" to "Plans" and clean up deprecated phase aliases

Renames the default "Phases" collection to "Plans" across the full stack:
- DB migration renames existing collections in-place (name, slug, prefix PLAN, icon 🗺️)
- Removes all deprecated Phase* backward-compat aliases from models and store
- Removes --phase CLI flag (use --parent instead)
- Updates convention triggers: on-phase-start/complete → on-plan-start/complete
- Updates dashboard API: active_phases → active_plans, /phases-progress → /plans-progress
- Updates all frontend components, types, and documentation

Closes IDEA-124

* Fix CSRF cookie not being cleared on logout

The SessionAuth middleware was re-issuing a CSRF cookie before the
logout handler could clear it, resulting in two Set-Cookie headers.
Skip CSRF re-issue for /api/v1/auth/ paths since auth endpoints
manage their own CSRF cookies (login sets, logout clears).

* Fix migration issues found in Codex review

- P1: Move doc_type UPDATE from migration 024 into 025, which recreates
  the table with the new CHECK constraint first (SQLite enforces CHECK
  on UPDATE, so the old constraint would reject 'plan')
- P1: Add PostgreSQL migration 005 for the collection rename (phases →
  plans) — previously only existed on the SQLite path
- P2: Recreate FTS triggers, indexes, and rebuild FTS after the table
  swap in migration 025 (DROP TABLE drops associated objects in SQLite)

* Fix parent filter field name and sync .agents skill copy

Codex review round 2 findings:
- P1: Parent filter compared against `parent_id` (wrong) instead of
  `parent_link_id` — plan filtering in collection view was broken
- P1: .agents/skills/pad/SKILL.md still had old --phase flags and
  "Phases" references — synced from the updated .claude copy
- P2: Accept legacy 'phase' filter key for backward compat with
  existing saved views that serialized the old key name

* Fix PG migration JSONB casting and add slug collision guards

Codex PR review bot findings:
- P1: PostgreSQL REPLACE/LIKE don't work on JSONB columns — cast
  schema::text and fields::text before string ops, then back to ::jsonb
- P1: If a workspace already has a custom 'plans' collection, the
  rename hits UNIQUE(workspace_id, slug) — added NOT EXISTS guard
  to both SQLite and PostgreSQL migrations
2026-04-07 14:55:23 -04:00
xarmian 063ff92d00 feat: generalized parent/child items with progress tracking (#70)
* feat: generalize parent/child items — any item can have children with progress tracking

Replaces the phases-only task widget with a generalized parent/child system.
Any item (Phase, Idea, Doc, Task, etc.) can now be a parent of child items,
getting automatic progress bars, burndown charts, status grouping, drag-drop
reordering, and recursive expand/collapse up to 3 levels deep.

DB: migrate link_type 'phase' → 'parent' (migration 023)
Store: generalized methods (GetChildItems, GetItemProgress, SetParentLink
  with cycle detection), drop collection filters, per-child terminal status
API: new /items/{slug}/children and /items/{slug}/progress endpoints
Frontend: ChildItems, ChildChart, NestedChildren components replace PhaseTasks
CLI: --parent flag (--phase kept as hidden alias), list/show/changelog updated
Docs: CLAUDE.md, SKILL.md, pad-web updated for parent/child model

Full backward compatibility: old 'phase' link_type, --phase flags, phase_id/
phase_ref JSON fields all still work as deprecated aliases.

Closes PHASE-16 (9 tasks).

* fix: update collection list page to use item_id from phasesProgress response

The TS client return type changed from phase_id to item_id but the
collection list page still referenced p.phase_id, causing svelte-check
type errors in CI.

* fix: address Codex review findings — PG migration, terminal statuses, metrics, CSRF resilience

- Add PostgreSQL migration 003 to rename 'phase' links to 'parent'
- Use schema-defined terminal statuses in GetAllItemProgress instead of hardcoded defaults
- Pass computed terminal statuses from page to ChildItems component
- Only special-case 'parent' field key when not defined in collection schema
- Move MetricsMiddleware before Recoverer so panics are counted
- Always mount ChildItems for SSE subscriptions even with 0 children
- Exclude soft-deleted children from has_children enrichment query
- Re-issue CSRF cookie when session is valid but cookie is missing
- Show actual API error messages in create-item toasts
2026-04-07 09:52:31 -04:00
xarmian 8aa6481421 PHASE-12: Security Hardening for Pad Cloud (#67)
* feat: enforce RBAC role checks on all mutation endpoints (TASK-150)

Add requireMinRole helper and role enforcement to 30+ mutation handlers.
Viewers are now blocked from all state-changing operations, editors can
mutate items/docs/comments/views but not collections/webhooks/workspace
settings, and only owners can perform administrative operations.

Includes 11 integration tests with real auth covering viewer/editor/owner
access across items, collections, documents, comments, agent roles,
item links, and workspace operations.

* fix: scope search results to user's workspaces (TASK-151)

Search without a ?workspace= param previously returned results from all
workspaces in the database. Now the handler resolves the authenticated
user's workspace memberships and passes their IDs to the store query,
ensuring results only include items from workspaces the user belongs to.

Fresh installs (no users) retain unscoped search for backward compat.
Includes integration test proving cross-workspace isolation.

* fix: add webhook URL validation and SSRF protection (TASK-152)

Webhook creation now validates URLs before accepting them: only HTTP(S)
schemes allowed, embedded credentials rejected, private/reserved IPs
blocked (loopback, RFC1918, link-local, cloud metadata 169.254.169.254),
and hostnames are DNS-resolved to verify they don't point to private IPs.

Defense-in-depth check also added to the dispatcher's deliver function
so existing webhooks with unsafe URLs are blocked at delivery time.

* feat: add CSRF protection with double-submit cookie pattern (TASK-153)

Implements CSRF middleware that validates X-CSRF-Token header matches
the pad_csrf cookie on all state-changing API requests. Bearer token
auth, auth endpoints, and fresh installs are exempt. The frontend
client reads the CSRF cookie and attaches the header on mutations.

* feat: add per-endpoint rate limiting middleware (TASK-154)

Adds IP-based rate limiting for auth endpoints (5/min login, 3/hr
password reset, 5/hr registration) and user-based limits for API
(100/min) and search (30/min). Uses golang.org/x/time/rate with
automatic stale-entry cleanup. Adds chi RealIP middleware for
correct client IP behind proxies. Returns 429 with Retry-After.

* fix: sanitize error responses and remove PII from logs (TASK-155)

Replace all writeError(500, err.Error()) calls with writeInternalError
that logs the real error server-side and returns a generic message to
clients. Remove email addresses, user IDs, and password reset tokens
from log output to prevent PII leakage.

* feat: add security headers, configurable CORS, and secure cookies (TASK-160)

Add SecurityHeaders middleware (CSP, X-Frame-Options, nosniff,
Referrer-Policy, Permissions-Policy). Make CORS origins configurable
via PAD_CORS_ORIGINS env var. Add PAD_SECURE_COOKIES for TLS
deployments (sets Secure flag on session/CSRF cookies and enables
HSTS). Also adds X-CSRF-Token to CORS allowed headers.

* fix: address PR review — lazy router init and trusted IP for rate limits

Fix two issues flagged by Codex:

1. CORS/HSTS config was ignored because setupRouter() ran in New()
   before SetCORSOrigins/SetSecureCookies were called. Now uses
   sync.Once to lazily build the router on first ServeHTTP/Listen.

2. Rate limiter read X-Real-IP directly from untrusted headers,
   allowing clients to spoof IPs. Now uses RemoteAddr only (which
   chimiddleware.RealIP already sanitizes from trusted proxy headers).
2026-04-05 10:26:00 -04:00
xarmian 367116b3a0 Unify relation fields and item links into single dependency system (#66)
* feat: unify relation fields and item links into single dependency system

Phase membership (Task→Phase) was previously stored as a UUID in the
item's fields JSON, separate from the item_links table used for
blocks/related/implements relationships. This unifies both into the
item_links table so all item relationships use one system.

Backend:
- Add 'phase' link type to item_links constants
- Migration 021: migrate existing phase field values to item_links,
  strip phase from fields JSON, remove phase field from tasks schema
- Rewrite GetPhaseProgress, GetAllPhasesProgress, GetTasksForPhase
  to JOIN on item_links instead of json_extract(fields, '$.phase')
- Add SetPhaseLink, ClearPhaseLink, GetPhaseForItem, GetTaskPhaseMap
  store helpers with single-phase constraint enforcement
- Create/update handlers intercept 'phase' in fields and route through
  links system; enrich item responses with phase_id/ref/title
- Dashboard orphan detection uses batch GetTaskPhaseMap lookup
- Add PhaseID filter to ItemListParams for link-based list filtering

Frontend:
- Remove relation field type from FieldEditor (no longer needed)
- Add link CRUD UI to item detail page: "Add relationship" inline form
  with link type picker + item search, delete buttons on existing links
- Phase links appear in Relationships section as "In phase"/"Phase"
- ItemCard reads phase from item.phase_title instead of fields.phase
- FilterBar phase filter uses item.phase_id for client-side filtering
- Add api.links.delete to frontend API client
- Fix duplicate {#each} key on dashboard attention list

Implements IDEA-106.

* fix: remove relationLabels prop from BoardView, ListView, TableView

ItemCard no longer accepts relationLabels (phase info now comes from
item.phase_title), so remove the prop from all parent view components
that were passing it through. Also remove unused .cell-relation CSS.

* fix: address PR review — atomic SetPhaseLink, migration safety, error handling

1. Migration 021: remove deleted_at filters so archived tasks and tasks
   pointing to archived phases also get their phase links migrated.

2. SetPhaseLink: wrap delete+insert in a transaction so a failed insert
   doesn't leave the item with no phase link (previously non-atomic).

3. Create/update handlers: return proper HTTP errors when phase link
   operations fail instead of logging warnings and returning 200 OK.
2026-04-04 19:47:57 -04:00
xarmian e21da3c6a4 fix: schema-driven terminal statuses replace hardcoded lists (BUG-17) (#65)
Add `terminal_options` to collection field schemas so each collection
declares which statuses are terminal/finalized. Replaces 10+ inconsistent
hardcoded status lists across backend, CLI, and frontend.

- Add TerminalOptions to FieldDef and centralized helpers in models/terminal.go
- Populate terminal_options on all default and template collections
- Replace hardcoded isDoneStatus/isTerminalItemStatus with schema-aware lookups
- Fix phase progress to count all terminal statuses (not just "done")
- Add terminal status toggle UI in collection field editor (Settings → Fields)
- Redesign collection field editor for cleaner layout and alignment
- Move Platform settings tab before Danger Zone tab
2026-04-04 18:56:30 -04:00
xarmian 8d00ae822d fix: relation field UUID display + link bubble auto-show (BUG-18, BUG-10) (#64)
* fix: show phase title instead of UUID in relation fields

FieldEditor only loaded relation items when the dropdown was opened,
so the initial render showed the raw UUID. Now eagerly fetches relation
items on mount when the field has a value, and shows a loading state
while fetching.

Fixes BUG-18.

* fix: prevent link bubble from auto-showing on page load

The EditorLinkPopover subscribed to the transaction event which fires
during initial document load. If the cursor landed inside a link, the
popover appeared without user interaction. Removed the transaction
listener — selectionUpdate alone correctly handles user-initiated
cursor changes.

Fixes BUG-10.
2026-04-04 16:27:59 -04:00
xarmian 405ef8b629 fix: align editor block drag handle with text and checkboxes (#63)
The drag handle was vertically misaligned because the offset was
hardcoded to -12px (assuming 24px half-height) but the handle is 32px
tall. Also, for flex containers like task list items, the handle
aligned to the full <li> height instead of the checkbox row.

Now uses dynamic handle height and computed line-height for centering,
and for flex/grid containers measures the first child element so the
handle aligns with the checkbox/content row.

Fixes BUG-21.
2026-04-04 16:10:52 -04:00
xarmian edcf2ae8b0 Board view improvements: independent scrolling, unified cards, lane reorder, new-item modal (#61)
* feat: independent board scrolling, unified card style, lane reordering, and new-item modal

- BoardView: switch from CSS grid to flex layout with independent per-column
  scrolling, matching the Roles board UX
- ItemCard: redesign to match Roles board card style — top row with optional
  collection badge + ref, compact meta row with colored status/priority text
- Roles board: replace inline card markup with shared ItemCard component,
  add HTML5 drag-and-drop lane reordering (persisted via new API endpoint),
  rename "Highlight Mine" to "Mine", add "+ New" button with collection
  picker modal
- Backend: add PUT /roles/board/lane-order endpoint and UpdateAgentRoleOrder
  store method for batch role sort_order updates
- Collection page: board view now fills viewport height so columns have
  bounded scroll areas

* fix: resolve svelte-check type error and remove unused CSS selectors

- Add null guard on lane.role in openEditModal onclick
- Remove unused .role-edit-actions, .role-btn-create, .role-btn-cancel CSS

* fix: correct lane reorder insert index when dragging forward

After splicing out the source lane, downstream indices shift left by one.
Adjust the insert index when srcIdx < dstIdx to place the lane at the
correct drop target position.
2026-04-04 13:02:12 -04:00
xarmian 2f9e61ad9c fix: within-lane reorder now persists sort order
The early return for same-lane drops (oldKey === key) was skipping
the sort persistence code entirely. Restructured handleDndFinalize
so the cross-lane role update is a nested conditional, and the sort
order persistence always runs regardless of whether a cross-lane
move occurred.
2026-04-04 14:10:13 +00:00
xarmian 034f169a02 fix: keep isDragging true until lanes state is updated
The $effect that syncs laneData from orderedLanes was firing when
isDragging was set to false, overwriting the optimistic sort order
with stale data. Now isDragging stays true until after lanes state
is updated with the new sort order, so the $effect sees correct data.
2026-04-04 14:07:00 +00:00
xarmian 8b1b46ef22 feat: persistent card ordering within role board lanes
Add role_sort_order column to items for independent ordering in the
role board, separate from the collection sort_order.

Backend:
- Migration 020: role_sort_order INTEGER column on items
- Item model, all SELECT/INSERT/Scan queries updated
- PUT /roles/board/reorder endpoint for batch sort updates
- Board API sorts items by role_sort_order within each lane

Frontend:
- Within-lane drag reorder persists via reorder API
- Cross-lane moves also persist new sort order
- Both operations are optimistic (no page refresh)
2026-04-04 14:00:21 +00:00
xarmian 64ab4fe1d3 fix: remove assignee pills from lane headers, show on cards only
Assigned user names were shown both in the lane header as pills and
on individual item cards. Remove the lane header pills — the card
already shows the assigned user, and duplicating it in the header
added clutter without information.
2026-04-04 13:26:46 +00:00
xarmian 0cf8f34496 fix: center role dialog on mobile, shrink add-role button
- Dialog uses fixed positioning with translate(-50%, -50%) for
  reliable viewport centering on all screen sizes
- Add Role column no longer stretches to full lane width/height —
  sized to its content with align-self: flex-start
2026-04-04 13:24:37 +00:00
xarmian a3e8ccc4ca refactor: per-lane edit buttons and add-column replaces manage modal
Remove the ⚙ Manage button and its full-list modal. Instead:

- Each role lane header has a ✎ edit button (appears on hover)
  that opens a focused dialog for that role's fields + delete
- A dashed "+" column at the far right of the board opens the
  same dialog in create mode
- Empty state has a "Create your first role" CTA
- Dialog is simpler: one role at a time with name, icon,
  description, tools fields, save/cancel/delete
2026-04-04 12:19:30 +00:00
xarmian e958abc20a fix: optimistic drag-and-drop — no page refresh on role reassignment
Replace the loadData() round-trip after dropping with an optimistic
local update. The item moves instantly in lanes state with updated
role fields, and the API call fires in the background. Only reloads
from server on error (revert). No scroll reset, no flash.
2026-04-04 12:06:49 +00:00