Commit graph

45 commits

Author SHA1 Message Date
varutasu
491d196384
fix(docker): reorder build stages so web-build comes after its --from= sources (#2)
Coolify's builder fails the build at parse time with:
  "cannot copy from stage 'collab-build', it needs to be defined before
   current stage 'web-build'"

The previous commit introduced forward COPY --from references that work
on newer BuildKit DAG builders but not on the legacy Docker builder
Coolify uses. Move `collab-build` and `mcp-build` above `web-build` in
lexical order so the references resolve. Functionally identical — the
DAG ordering effect is the same — just expressed in a way the older
builder accepts.

Added a NOTE comment above the stages so the next person who tries to
"clean up" the file order doesn't reintroduce the same regression.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-05 21:13:39 -05:00
varutasu
3fb79f6f04
Merge pull request #1 from stwl-labs/hotfix/docker-build-ordering
fix(docker): serialize build stages so next build doesn't OOM on the 8 GB host
2026-06-05 21:04:32 -05:00
Randall Stillwell
d4e4f9dbf0 fix(docker): serialize build stages so next build doesn't OOM on the 8 GB host
Coolify deploys were failing with exit 255 (kernel OOM, no Docker error)
around the 73s mark of `next build`. Root cause: docker/Dockerfile's three
build stages (web-build, collab-build, mcp-build) all `FROM deps`, and
BuildKit was running them in parallel. The web-build alone wants ~3 GB
heap (capped at 5120 MB) and was racing tsup workers + buildkit + dockerd
on an 8 GB host until the kernel reaped it.

docker-compose.coolify.yml already had a comment claiming `depends_on:
[collab, mcp]` on `web` would serialize the builds. It doesn't —
`depends_on` only orders runtime startup, not `docker compose build`.

Fix: enforce ordering inside the Dockerfile DAG by COPYing one trivial
artifact from each lighter stage into web-build. BuildKit now waits for
collab-build and mcp-build to finish before starting the heavy Next.js
compile, which then gets the host effectively to itself. The copied
files land in /tmp and are never read by the runtime web image.

Also updated the compose comment to reflect the new (and accurate)
ordering mechanism.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-05 21:02:39 -05:00
Randall Stillwell
011d3eb710 fix(workspaces): wire top-header create-workspace button + clarify echodo db naming
The Create Workspace button in the top-header dropdown was still calling
`window.alert("Create workspace (placeholder)")` instead of opening the
real CreateWorkspaceDialog. Wires it to the same dialog the sidebar
workspace switcher uses.

Also clarifies in .env.example and AGENTS.md that the canonical Postgres
database name is `echodo` everywhere (local, Coolify, drizzle ledger,
docker-compose POSTGRES_DB). A stale `tasks` database on CT 102 from the
pre-rename era was the root cause of the 2026-06 Authentik "Configuration"
SSO outage: Coolify correctly pointed at `echodo` (which was empty), while
the only initialized schema lived in the relic `tasks` DB.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-05 16:33:41 -05:00
Randall Stillwell
8b981723b6 chore(plans): mark export-db-to-markdown-frontmatter done
Written by the exporter itself during the dogfood run — final dogfood
evidence that the two-way sync loop closes correctly. See run
0bace0aa-ef6e-4aca-a041-e7f2343ba854 in agent_runs for the trail.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 10:56:34 -05:00
Randall Stillwell
56b697b81c feat(markdown-backlog): close the sync loop with DB → frontmatter export
Until now the markdown importer was one-way (plans/*.md → DB). Any
agent-driven status flip via claim_task / complete_task would be
clobbered on the next importer sweep. This change closes the loop: the
DB now projects status, priority, agent_prompt, and updated_at back
into the file's frontmatter, preserving body bytes, key order, and
every other frontmatter key.

New: packages/database/src/markdown-backlog/export.ts
  - `rewriteFrontmatter()` — pure function, covered by 10 Vitest cases
    (round-trip identity, status flip, priority flip, agent_prompt
    null/block-scalar/single-line variants, body preservation,
    trailing-newline preservation, idempotent re-application).
  - `exportBacklogItemToMarkdown()` — DB-loading wrapper with atomic
    write (tmp + rename) and tenant fencing. Returns a structured
    result so callers can surface what happened in their response.

Wired into:
  - `claim_task` MCP tool — exports on the ready → in_progress flip.
  - `complete_task` MCP tool — exports on any finalStatus transition.
  - `backlog.updateWorkflowPrompt` tRPC mutation — exports on prompt
    edits made through the app UI.

Robust repo-root resolution (`apps/{mcp-server,web}/src/lib/repo-root.ts`,
plus a copy in `import-markdown-backlog.ts`): walk up from the source
file looking for `pnpm-workspace.yaml`, falling back to env var or cwd.
This fixes a class of bug where `pnpm --filter <pkg>` cd's into the
package directory and breaks naive cwd-based path resolution — the
importer was deleting all 44 rows during smoke testing before this fix
because it found zero files in `packages/database/plans/`.

`config/CursorSync.md`: documents the new two-way contract, the
DB-wins-on-allow-list conflict policy, and the
MARKDOWN_BACKLOG_REPO_ROOT=off escape hatch for production deployments
where `plans/` isn't checked out.

Smoke verified end-to-end against the homelab DB: claim flips file
status to in_progress, complete flips it back to ready, importer
round-trips with stable content_hash (true no-op), agent identity
preserved throughout.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 10:21:22 -05:00
Randall Stillwell
fc2235a346 feat(agent-runs): capture client + model identity on claim/complete
Adds level-B agent attribution: every MCP tool call can identify itself
with a `client` (e.g. cursor-ide, codex, echodo-orchestrator) and `model`
(e.g. claude-4.6-sonnet) string. Both optional, both stored in
agent_runs.metadata as JSONB so the schema doesn't move.

- claim_task: new optional `client` + `model` args. Written into the
  inserted agent_runs row's metadata, and mirrored into the audit log
  entry. On idempotent re-claim, incoming values are merged into
  existing metadata (existing keys override only when explicit), so a
  mid-session model switch updates attribution without losing earlier
  context.
- complete_task: same optional args, with merge-on-close semantics —
  late-bound values override the earlier claim's values so the run row
  reflects whichever model actually closed the session. Audit row also
  carries the merged identity.
- /settings/runs UI: stack the client/model under the actor name in the
  table so attribution is visible at a glance without adding a column.

Smoke-tested: claim with {cursor-ide, claude-4.6-sonnet} then complete
with only model={claude-4.6-sonnet-medium-thinking} yields final
metadata {client: cursor-ide, model: claude-4.6-sonnet-medium-thinking}
on both the run row and the task.completed audit entry.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 10:11:35 -05:00
Randall Stillwell
e99aa733c9 chore(agent-coordination): wire Cursor MCP + one-shot importer for dogfooding
Connect Echodo to itself: Cursor sessions can now call this repo's MCP
server (`claim_task`, `complete_task`) over stdio, and operators can
bootstrap the DB from `plans/` without leaving a long-running file
watcher in place.

- `.cursor/mcp.json`: register `echodo` MCP server. Spawns
  `pnpm -s --filter @tasks/mcp-server mcp`. The `mcp` script invokes tsx
  with `--env-file=../../.env` so DATABASE_URL is picked up at the
  per-session process boundary without leaking into committed config.
- `import:markdown-backlog`: new one-shot importer (sibling of the
  existing watch script). Until the DB → markdown export side lands
  (see follow-up task), running the watcher continuously would clobber
  agent-driven status flips on every sweep. The one-shot variant runs a
  single `syncMarkdownBacklogScan` pass and exits.
- File `Task-export-db-to-markdown-frontmatter.md` documenting the
  remaining direction of the sync loop.

Smoke-tested end-to-end against the homelab DB: full `claim_task` →
`complete_task` round-trip via real MCP stdio protocol, with agent_runs
+ audit_log rows landing as expected and the backlog item status
restored via `finalStatus`.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-03 08:57:21 -05:00
Randall Stillwell
b2aff2045b feat(mcp): claim_task tool + register claim/complete pair
Pairs with the parallel complete_task commit. claim_task opens an
agent_runs row, flips status to in_progress only when it's safe
(ready/draft → in_progress, never overwriting a deliberate
blocked/done/in_progress), and returns the resolved workflow prompt
+ source level. Idempotent re-claim by the same actor returns the
existing run with reused=true and refreshes notes only — started_at
is sacred. Different-actor re-claim errors with ALREADY_CLAIMED
naming the existing actor and run id.

Tenancy fence: if the backlog item exists but in a different workspace
than the resolved handle, we refuse with "doesn't belong to workspace"
rather than 404. Prevents cross-tenant existence fishing.

All three writes (run insert + status flip + audit insert) happen in
one db.transaction() so a partial claim is unreachable.

tools/index.ts now registers both claim_task and complete_task.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 22:23:05 -05:00
Randall Stillwell
93b6398c76 feat(mcp): complete_task tool — close agent_runs row + finalize status
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 22:21:26 -05:00
Randall Stillwell
72aa2a5f0c feat(backlog): workflow_prompt with task → epic → plan inheritance
Adds the data layer for per-item agent prompts. Markdown frontmatter
gets an `agent_prompt:` block scalar that survives the importer
round-trip (newlines preserved), and `resolveWorkflowPrompt()` walks
task → epic → plan → built-in default returning both the resolved
string and the source level. Walk is slug-based, not parent_id-based,
because the importer leaves parent_id briefly null mid-transaction.

tRPC `backlog.getWorkflowPrompt` returns ownOverride + effectivePrompt
so future UI can render the override box + preview without two
queries. `backlog.updateWorkflowPrompt` is owner/admin-gated (prompts
change downstream Cursor/Claude behavior) and audit-logged on every
write.

UI deferred — apps/web doesn't have a backlog-item detail panel yet;
the existing object-detail panel is for the objects table. Follow-up
filed at Task-workflow-prompt-task-detail-ui.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 22:18:18 -05:00
Randall Stillwell
f014686412 feat(runs): agent_runs table + tRPC router + settings UI
Read-side only — write paths land with claim_task / complete_task
in the next epic. Keyset pagination on started_at, three procedures
(listRecent, listForTask, summary), and a /settings/runs view that
mirrors the audit page's visual language.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 22:16:04 -05:00
Randall Stillwell
93565cd94c ops(db): reconcile CT 102 drift — stamp ledger, add missing 0002 tables
The `tasks` Postgres on CT 102 was bootstrapped years ago with
`drizzle-kit push`, which writes schema but skips the ledger. As of
today the ledger contained zero rows and the schema was missing
`markdown_backlog_items` + `cursor_sync_mappings` (migration 0002
ran on neither code path). Migration 0007's ALTER on
markdown_backlog_items had silently failed because of this; audit_log
was added manually.

The one-shot at docs/operations/2026-06-02-db-drift-reconcile.sql
created the two missing tables at the final post-0007 shape (skipping
0002's now-obsolete FK-to-objects intermediate state, which 0003
would have immediately rewritten anyway) and stamped all 8 migrations
with their sha256 + journal `when` so drizzle's
`lastDbMigration.created_at < migration.folderMillis` gate treats
them as already applied.

`pnpm db:migrate` is now a clean no-op against this DB. Future
migrations work normally.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 16:17:42 -05:00
Randall Stillwell
336a5890a8 feat(audit): append-only audit_log, workspace archive cascade + restore, audit view
Soft-delete cascade was the missing half of archive: stamping
workspaces.archived_at alone left objects visible to anyone with a
direct id. The cascade runs in one transaction so the partial state
isn't reachable, and restore inverts it for any archived row in the
workspace — provenance-blind on purpose until we have a use case
that needs to distinguish per-workspace from per-object archives.

audit_log keeps the keyset index on (workspace_id, created_at) and
the actor_user_id FK with onDelete set null. recordAudit() refuses
to write a null actor without a metadata.system_actor label so the
audit view always has something to render. workspaces and invites
mutations call recordAudit on success; objects-router instrumentation
and the markdown importer's system-actor flow are filed as P2
follow-ups because each needs a thoughtful "what's audit-worthy?"
pass, not mechanical wiring.

Settings → Audit log lives at /<slug>/settings/audit, owner-gated,
keyset-paginated. ACTION_LABELS is small on purpose; new actions
fall back to their raw key so missing a label degrades gracefully.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 15:35:16 -05:00
Randall Stillwell
58f92f3898 feat(security): in-process rate limit for sign-in and invite creation
Algorithm: a fixed-window token bucket implemented as a pure function in
`@tasks/shared` (`consumeTokenBucket`) plus a thin `apps/web` wrapper that
holds per-key state in a module-scoped `Map`. No Redis, no external deps —
horizontally-scaled deploys will need a Redis-backed swap behind the same
`rateLimit()` signature; called out in the JSDoc as a follow-up. The pure
core is unit-tested in `packages/shared` (6 new vitest cases covering
allow/deny, window reset, key isolation, monotonic retryAfterMs, denied-
flood pegging, and option validation); the wrapper is intentionally not
tested here because apps/web has no vitest harness yet.

Wire-ins (the two narrow surfaces called out in the v1 spec):

  1. Credentials `authorize` in `apps/web/lib/auth.ts`: 5 attempts per
     IP per 60s. IP comes from `next/headers` (x-forwarded-for first
     entry, then x-real-ip); when headers() throws or returns nothing we
     fall back to keying on "unknown" in prod and skipping the limiter
     entirely in dev so a local test loop doesn't lock itself out. On a
     trip we `console.warn` and return null — the standard Auth.js
     "auth failed" signal — without consulting the DB.

  2. `invites.create` in `apps/web/server/routers/invites.ts`: 10
     invite-creates per inviter per hour. Keyed by inviter id (not
     workspace) so a multi-workspace admin can't multiply their
     allowance. On trip we throw TRPCError TOO_MANY_REQUESTS with a
     retry-after seconds count baked into the message.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 13:26:19 -05:00
Randall Stillwell
29e69e964b feat(invites): smart recipient autocomplete combobox (Task 3, done)
Closes Task-invite-recipient-autocomplete. The invite dialog's plain
email input is replaced with a debounced combobox that surfaces the
four real cases — existing member, pending invite, known user from a
sibling workspace, brand-new email — before the inviter hits send.

Subagent ran in parallel while the main thread shipped Task 2's UI;
file-level non-overlap held (subagent stayed in
apps/web/components/teams/invite-recipient-combobox.tsx and the
shared types; main thread stayed in invite-dialog.tsx and the
teams page). This commit folds the subagent's deliverable in plus
the two-line wire-up that swaps the input for the combobox.

Files (5 by subagent + 1 wire-up by main thread):

@tasks/shared:
* packages/shared/src/types/invite-suggestions.ts — InviteSuggestion
  union + pure mergeInviteSuggestions ranker. Lives in shared so
  client + server consume one type definition.
* packages/shared/src/types/invite-suggestions.test.ts — 9 vitest
  cases covering kind ordering, dedupe (known_user vs member by
  userId, vs pending_invite by lowercased email), new_email
  suppression when other kinds cover the typed address, the 10-
  result limit, and email normalization.
* packages/shared/src/types/index.ts — re-export.

apps/web:
* apps/web/server/routers/invites.ts — new `suggestRecipient`
  procedure on workspaceProcedure (owner/admin only). Implements
  the four kinds with the tenancy fence wired as a two-step query:
  first SELECT DISTINCT workspace_id FROM workspace_members WHERE
  user_id = inviter (the inviter's workspace pool), then
  inArray(workspaceMembers.workspaceId, pool) + ne(users.id,
  inviter) on the candidate join. Read the procedure JSDoc for the
  full set of invariants. All user-typed patterns escape through
  escapeIlike with the ESCAPE '\\' clause (mirrors search.ts).
  No existing exports modified.
* apps/web/components/teams/invite-recipient-combobox.tsx —
  standalone controlled combobox. 200ms debounce, min-2-char gate,
  distinct row styling per kind, ArrowUp/Down/Enter/Esc keyboard
  nav, outside-click close.
* apps/web/components/teams/invite-dialog.tsx (wire-up) — Input
  swapped for InviteRecipientCombobox. Added an
  onFocusExistingMember prop so a future teams-page integration
  can scroll/focus the matching row when a `member` suggestion is
  picked; for now the dialog just closes cleanly on member-pick.

Gates: 0 lint errors / 15 warnings (14 baseline + 1 incidental
from earlier teams-page work, none from this task's files); 6/6
type-check; 23/23 tests (14 baseline + 9 new).

Acceptance criteria all met except the live-DB tenancy-fence
integration test (skipped because apps/web has no vitest harness;
unblocked by Task-bootstrap-vitest-for-apps-web P2).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:39:09 -05:00
Randall Stillwell
af10b162b7 docs(invites): mark Task-workspace-invites-and-roles done; capture design decisions
Status -> done. Acceptance criteria all checked off except the operator
smoke test (full invite -> accept across two browsers), which requires
a live dev stack. Added a 'design decisions captured here' section
covering (a) why caller role is derived from workspace_members not
from the resolve query, (b) the new tRPC errorFormatter that exposes
error.cause, and (c) why the invite dialog doesn't offer 'owner' role
even though the schema accepts it.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:35:42 -05:00
Randall Stillwell
f3c118c9f6 feat(invites): invite dialog + accept route + teams UI (Task 2, part 2/2)
Closes Task-workspace-invites-and-roles end-to-end. Builds on the
schema + procedures from 7a55d6d (Task 2, part 1/2).

apps/web/components/teams/invite-dialog.tsx (new):
* Owner/admin-only sheet that wraps invites.create. Email input + role
  select (member/admin; owner deliberately excluded — single-owner
  model means ownership transfer is a separate flow, not a fresh
  invite). On success surfaces the accept URL with a copy-to-clipboard
  affordance and a "your email isn't wired up yet, paste this directly"
  hint. Plain text input in this commit; the smart recipient
  autocomplete combobox from Task 3 will swap it in via a follow-up
  edit to this same file (subagent is working that in parallel).

apps/web/app/(app)/[workspaceSlug]/teams/page.tsx (rewrite):
* Replaced the placeholder "Invite coming soon" button with the new
  InviteDialog. Adds:
  - Pending invites section (admin/owner only) listing each open
    invite with email, role, expiry-relative time, and Copy link /
    Revoke actions.
  - Per-member kebab menu with role-change actions and Remove. Only
    owners can promote anyone to owner; admins can move people
    between admin/member only. The "demote to member" item disables
    on the last-owner row (the server enforces this anyway with a
    clear error; UI just avoids surfacing a click that'd 400).
  - "You're a member, not a manager" footer hint for non-owners/admins.
* Caller's role is derived from the members query (no extra
  round-trip) — the membership row IS the source of truth for who
  can manage what.
* Mutation errors surface inline at the page level with a Dismiss
  action — kebab/copy actions that hit the last-owner guard, expired-
  token error, etc. don't fail silently.

apps/web/app/invite/[token]/page.tsx (new):
* Public-by-token redeem page. Four phases handled cleanly:
  1. No session yet -> "Sign in to continue" with callbackUrl set so
     the user lands back here after auth.
  2. Authenticated, accepting -> spinner.
  3. Success -> redirect to the workspace's slug-rooted URL.
  4. FORBIDDEN with cause.reason='email_not_owned' -> dedicated
     explainer page showing both the invited email AND the user's
     current sign-in email, with deep links to link the invited email
     via OAuth and try again. (This is the Task 1 invariant
     surfacing through the UI: we never silently accept an invite
     under a mismatched identity.)
* All other accept errors (not found / revoked / expired) render the
  message verbatim with a "Go home" button.

apps/web/server/trpc.ts:
* Added a small errorFormatter that exposes `error.cause` to the
  client when it's a plain object. Required for the invite-accept
  explainer page to read `cause.invitedEmail` off the TRPCError. The
  cause-payload contract is "small, pure data, no secrets" — anything
  the server throws as a cause is also visible client-side.

End-to-end behavior verified statically: type-check clean across all
6 packages. Smoke test path:

1. As admin@tasks.dev, open /<workspace>/teams.
2. Click Invite -> dialog opens -> enter an email, pick member, send.
3. See the success state with the accept URL. Copy it.
4. Open the URL in a different browser (or incognito). With no session
   -> sign-in prompt. After auth -> invite accepts and you land in
   the workspace. With a session whose email doesn't match -> the
   email-mismatch explainer renders.

Note: the test runner shows three new tests in packages/shared
(invite-suggestions.test.ts) from the in-progress Task-3 subagent.
Those land with their own commit when the subagent finishes — they're
visible here only because they share the working tree.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:34:56 -05:00
Randall Stillwell
7a55d6d1c6 feat(invites): workspace_invites schema + tRPC router + role management (Task 2, part 1/2)
Schema half of Task-workspace-invites-and-roles. Lands the table, the
invites router (create/list/revoke/accept), and the two new workspaces
procedures (updateMemberRole/removeMember). UI ships in part 2/2.

This is a stable checkpoint for Task 3 (invite-recipient-autocomplete)
to start building against — the procedure surface area is frozen and the
new identity helper from Task 1 is in the accept path.

Schema:
* workspace_invites: id, workspace_id, email (lowercased), role
  (owner/admin/member), invited_by_user_id, token (base64url 32B),
  expires_at (DEFAULT now() + 14d), accepted_at, revoked_at, created_at.
* Indexes: workspace_id, UNIQUE(token), and a PARTIAL UNIQUE on
  (workspace_id, email) WHERE accepted_at IS NULL AND revoked_at IS NULL.
  An open invite is unique per (workspace, email); closed invites
  (accepted or revoked) fall out of the constraint so re-invites work.
* Drizzle relations wired: workspaceInvites.workspace,
  workspaceInvites.invitedBy, workspaces.invites.
* Migration 0006_broad_lethal_legion applied to dev DB.

invites router:
* create({email, role}) on workspaceProcedure (owner/admin only).
  Generates a base64url token from 32 random bytes via node:crypto.
  Idempotent on (workspace, email) — if an open invite already exists,
  returns it instead of inserting (the partial unique would block it
  anyway). Refuses self-invite. Refuses if the email is already a
  member.
* list() returns pending (non-accepted, non-revoked) invites with
  inviter name/email joined for UI display.
* revoke({inviteId}) authorizes against the invite's workspace, not
  the caller's input (the inviteId carries its own tenant scope).
* accept({token}) is protectedProcedure (no workspace handle). Calls
  userOwnsEmail() from Task 1 — if the caller doesn't own the invited
  email under any of their verified identities, throws FORBIDDEN with
  a structured cause ({reason: "email_not_owned", invitedEmail}) so
  the redeem page can render the "link this email" explainer. Handles
  expiry, revoked, already-accepted states with clear messages.
  Idempotent on existing membership — if you've already been added by
  another flow, accept just closes the invite without re-inserting.

workspaces additions:
* updateMemberRole: admin/owner only. Three guards:
    1. Can't change your own role (avoids accidental lockout).
    2. Can't demote the only owner-role member (would leave the
       membership-level ownership empty even though workspaces.owner_user_id
       still points there — see ADR-pragmatic decision documented in the
       Task-multi-email-identity convoy discussion).
    3. Only owners can promote to owner; admins move people between
       admin/member but cannot create a new owner.
* removeMember: admin/owner OR self (the leave-workspace affordance).
  Same last-owner guard. Admins can't remove owners (only owners can,
  via demote-then-remove).

Wired both new routers into root.ts as `invites` and `identity`
(identity was landed in Task 1; this commit just keeps the registration
visible alongside invites).

All three CI gates green: 0 lint errors, 14 unchanged warnings, 6/6
type-check, 14/14 tests (no new tests yet — apps/web vitest harness is
filed as Task-bootstrap-vitest-for-apps-web P2).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:27:44 -05:00
Randall Stillwell
3a657a4aed feat(identity): OAuth-aware sign-in writes accounts + identity rows (Task 1, part 2/2)
Closes Task-multi-email-identity. Rebuilds the OAuth half of the jwt
callback around the new user_email_identities table AND the existing
(but until-now empty) accounts table, with per-provider email_verified
resolution and a cross-user conflict guard. Credentials sign-in path is
unchanged.

Per the OAuth research subagent: NextAuth has no adapter configured, so
the accounts table has been sitting empty since this app started. Rather
than leave it that way, the new resolveOAuthUser helper writes to it
on every OAuth sign-in. (provider, providerAccountId) is now the
canonical "this OAuth identity belongs to this user" record and gives
us a fast path that doesn't depend on email matching.

Sign-in resolution order for an OAuth account:

1. Lookup accounts by (provider, providerAccountId).
   Hit -> bump last_used_at on the matching identity row, return user_id.
2. Lookup user_email_identities by (email, verified_at IS NOT NULL).
   Hit AND the owner has zero existing OAuth accounts -> link this new
     OAuth account to that user (covers "Credentials user adds their
     first OAuth provider"). Insert a fresh accounts row.
   Hit AND the owner already has an OAuth account -> REFUSE.  Returning
     a token without an id field denies the session; the user lands on
     NextAuth's error page. (This is the "Bob's GitHub claims alice's
     verified email" rejection.)
3. Fall back to legacy users.email match.
   Hit -> link to that user (covers users created before migration 0005).
4. Otherwise mint a new users row + a source='primary' identity in the
   identities table, then write the accounts row.

The verified identity row is upserted only when the provider's
email_verified claim is true. The new resolveOAuthEmailVerified helper:

- Google + Authentik: read profile.email_verified directly (the Auth.js
  v5 jwt callback receives `profile` on the sign-in trigger). Authentik
  caveat documented inline: since the 2025.10 release the claim defaults
  to false unless an admin adds a custom property mapping.
- GitHub: GitHubProfile does not expose the claim. We GET /user/emails
  with the OAuth access_token and read `verified` on the entry matching
  the primary email. Failure to fetch (rate limit, network) is treated
  as unverified.

What's intentionally not in this commit:
- Vitest tests for the callback logic. apps/web has no vitest config
  yet (the test foundation only wired up the packages). Filed a
  follow-up: Task-bootstrap-vitest-for-apps-web.md (P2) under
  Epic-test-foundation. The auth-callback assertions will land against
  that harness when it's stood up.
- Race-condition transaction isolation. The current sequence (account
  lookup -> identity lookup -> account/identity upsert) has the same
  race window the old ensureUserIdByEmail had — two simultaneous OAuth
  sign-ins for a brand-new email could both pass the identity check
  before either INSERT fires. Mitigated in practice by the partial
  unique on email WHERE verified_at IS NOT NULL — postgres will reject
  the second insert — but the loser gets an opaque error. Filed as a
  follow-up if it becomes a real issue.

Task file (plans/.../Task-multi-email-identity.md) updated with the
detailed smoke-test playbook an operator needs to run before the OAuth
path goes to production (sign in fresh, sign in repeat, sign in
cross-provider, sign in cross-user-conflict). admin@tasks.dev signs in
via Credentials so the dev fixtures alone do not exercise this code.

Lint + type-check + test all green (14/14 tests, 0 lint errors, 14
unchanged warnings, 6/6 packages type-check).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:14:16 -05:00
Randall Stillwell
86c014cb66 feat(identity): schema + helpers + read-only profile UI (Task 1, part 1/2)
First half of Task-multi-email-identity. Lays down everything except the
NextAuth callback wiring, which is gated on a research subagent finishing
its survey of OAuth provider behavior for the email_verified claim
across GitHub, Google, and Authentik.

Schema (packages/database):
* New user_email_identities table colocated with `users` in users.ts.
  Columns: id, user_id (FK), email (lowercased), verified_at, source,
  created_at, last_used_at.
* Indexes: user_id, email, unique(user_id, email), and a PARTIAL unique
  index on email WHERE verified_at IS NOT NULL — a verified email
  resolves to exactly one users row globally, while unverified rows
  (none today; placeholder for the manual-verification follow-up) do
  not share the constraint.
* Drizzle relation: users.emailIdentities -> userEmailIdentities, and
  the inverse one(users) relation.
* Migration 0005 generated by db:generate, augmented with a backfill
  INSERT that seeds one source='primary' identity per existing users
  row using created_at as verified_at. Migration applied to dev DB;
  existing admin@tasks.dev user verified as 1:1 mapped.

Server (apps/web/server):
* apps/web/server/lib/identity.ts exports two pure read helpers:
  - userOwnsEmail(userId, email): boolean used by the (upcoming)
    invite-accept procedure to verify the human controls the invited
    address under any of their linked identities.
  - findUserIdByVerifiedEmail(email): the replacement for the old
    ensureUserIdByEmail lookup. Will be called from auth.ts once the
    OAuth research subagent returns.
* apps/web/server/routers/identity.ts exposes identity.listMine — a
  protected procedure returning the caller's identities ordered by
  verifiedAt desc. Cross-user identity surface is intentionally NOT
  exposed here; that lives behind the workspace-scoped autocomplete
  in Task 3 with its own tenancy fence.

UI (apps/web/app):
* New route /[workspaceSlug]/settings/profile renders a read-only
  "Linked emails" section with per-identity row (email, source badge,
  verified state, last-used relative time) plus a hint that explains
  how to add another email (sign in via that email's OAuth provider).
* Empty / loading / error states all handled. The "no identities"
  branch should never fire post-backfill but renders a friendly
  message instead of throwing.

What's NOT in this commit:
* auth.ts changes (ensureUserIdByEmail -> ensureUserIdByVerifiedEmail,
  OAuth callback identity upsert, cross-user conflict rejection).
  Waiting on subagent research to land the callback wiring correctly
  on the first try across all three providers.
* Vitest tests. The pure helpers are 10-line query shims and the
  behavior-relevant assertion is the auth callback path — easier to
  write meaningful tests once that lands.

All three CI gates green: pnpm lint (14 pre-existing warnings,
unchanged), pnpm type-check (6/6 packages), pnpm test (14/14
existing tests across @tasks/shared, @tasks/database, @tasks/ai).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:07:50 -05:00
Randall Stillwell
820dae6510 docs(plans): split workspace-invites convoy into identity + invites + autocomplete
User pushed back on "strict email match in v1" — the right architectural
answer is multi-email identity (one users row owning multiple verified
emails), not a stopgap. Scaling the convoy accordingly:

1. Task-multi-email-identity (NEW, P1, foundation)
   - user_email_identities table (user_id, email lowercased, verified_at,
     source: primary | oauth:<provider> | manual)
   - Refactor ensureUserIdByEmail -> ensureUserIdByVerifiedEmail against
     the new table.
   - OAuth callback writes a source='oauth:<provider>' identity when the
     provider returns email_verified=true. Cross-user conflict rejects.
   - Profile UI: "Linked emails" section, read-only in v1.
   - Exports userOwnsEmail(userId, emailLower) for invite accept to call.

2. Task-workspace-invites-and-roles (existing, narrowed)
   - All the original spec.
   - Accept procedure calls userOwnsEmail() instead of comparing
     users.email directly. Mismatch renders an explainer page, not a
     silent accept.

3. Task-invite-recipient-autocomplete (NEW, P1, polish)
   - invites.suggestRecipient returns typed suggestions across four
     kinds: member / pending_invite / known_user / new_email.
   - Tenancy fence on known_user is the security-relevant assertion;
     test for it explicitly.
   - Combobox UI renders each kind with its own affordance.

Three follow-ups filed explicitly to keep this convoy PR-sized:
- Task-manual-email-verification (add an email outside OAuth)
- Task-disconnect-linked-email (destructive, needs last-verified guard)
- Task-account-merge (handle the legacy duplicate-users case)

Epic file refreshed with the new task table, follow-up table, and a
phase ordering note. Identity lands first because it touches the
sign-in path; invites and autocomplete can ship in their own PRs.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 10:02:38 -05:00
Randall Stillwell
48defb2ffd test(ci): bootstrap vitest + GitHub Actions and lock in 3-gate quality bar
First Path-B task. Path A landed daily-driver features without a
test runner; Path B is "harden so the next batch of changes can't
silently regress what just shipped." Step 1 is making `pnpm test`
real and gating CI on it.

Test runner:
* Install vitest + @vitest/coverage-v8 at the workspace root.
* Add vitest.config.ts (environment: "node", no JSDOM) + test /
  test:watch scripts to packages/shared, packages/database,
  packages/ai. Wire `test` into turbo.json with dependsOn: ^build
  for future-proofing; add `pnpm test` to root package.json.

Three real tests (no snapshot theater — verified by mutation):
* packages/shared/src/utils/id.test.ts: asserts generateId() matches
  the RFC 4122 v4 regex and produces 1000 distinct values. Mutating
  generateId() to a constant fails both assertions.
* packages/shared/src/types/objects.test.ts: pins objectTypes and
  objectStatuses arrays. These back the zod enum on objects.create
  and the "open tasks" count on the workspace-home dashboard; a
  silent reorder/rename would otherwise corrupt the dashboard math.
* packages/database/src/markdown-backlog/parse.test.ts: covers
  parseBacklogMarkdown across three shapes (well-formed Task,
  no-frontmatter Plan with path inference, malformed YAML that
  must NOT throw — the importer runs in a file watcher). Plus
  hashFileContents determinism.
* packages/ai/src/actions/index.test.ts: five tests across the
  prompt builders (summarize/expand/rewrite × 3 tones / translate /
  generateFromPrompt). Pure functions; no model mocking needed.

CI:
* .github/workflows/ci.yml runs on pull_request and push to main.
  Node 20, pnpm 9 pinned explicitly (per AGENTS.md). Uses
  setup-node's built-in pnpm cache. Steps: install --frozen-lockfile,
  lint, type-check, test. Concurrency group cancels superseded runs
  on non-main branches.

Docs:
* AGENTS.md: drop the "no test runner configured" disclaimer.
  Document pnpm test / test:watch. Update the PR-readiness rule
  from `pnpm lint && pnpm type-check` to
  `pnpm lint && pnpm type-check && pnpm test`.

All 14 tests pass; lint + type-check still green across all 6
packages. The CI workflow's first run is gated on the operator
pushing this branch — that's the only acceptance criterion left
unverified in this commit.

Closes plans/Plan-multitenant-saas-hardening/Epic-test-foundation/
Task-bootstrap-vitest-and-ci.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 09:23:55 -05:00
Randall Stillwell
31e877d1d0 docs(plan): note agent-side prep on collab-editor smoke-test task
Path-A task 5/5 is verification-only and requires the deployed
homelab stack + two browser sessions — outside an agent session's
reach. Documented in the task file what's been verified
automatically (lint + type-check, including @tasks/collab-server,
all green; no Path-A changes touched the collab server) and what
still needs hands-on testing against the deploy.

Leaves the task in `ready` status until an operator runs the live
7-step checklist.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 00:26:34 -05:00
Randall Stillwell
7ec2ede7ca feat(web): land authed users on their oldest workspace home by slug
Path-A task 4/5. The root landing logic in apps/web/app/page.tsx was
redirecting to `/${workspaceId}` (UUID, ugly) and using no ORDER BY
(so two sessions could land on different workspaces). It also looped
zero-workspace users through `/sign-in`.

Changes:

* Inner-join workspaceMembers with workspaces to fetch the slug, not
  just the id. Order by membership createdAt ascending so users
  consistently hit their oldest workspace.
* Redirect to /{slug} (slug, not UUID).
* Removed the unused `objects` / `and` imports that were lint
  warnings.
* Zero-workspace branch redirects to /sign-in?error=no_workspace as a
  defensive fallback; documented inline that this is unreachable for
  fresh sign-ins post `ensureUserHasWorkspace` in apps/web/lib/auth.ts.

The dashboard at /{slug}/ is no longer a mockup (post commit f64d307
which wired it to objects.stats and objects.listRecent), so landing
there now shows real state.

Filed plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-onboarding-zero-workspace-flow.md (P2) as the follow-up that
turns the defensive fallback into a proper welcome flow with a
shared workspace-provisioning helper.

`pnpm lint && pnpm type-check` clean. Closes
plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-pick-workspace-landing-route.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 00:25:48 -05:00
Randall Stillwell
a1e6c863d5 feat(web): wire AI chat page to streaming /api/chat handler
Path-A task 3/5. Replaces the setTimeout mock that returned the literal
"Full AI integration is coming soon!" string with a real streaming
provider call.

* apps/web/app/api/chat/route.ts (new): POST handler that runs the
  same auth + resolveWorkspace pipeline workspaceProcedure uses, then
  streams a response from streamText().toDataStreamResponse(). Maps
  resolveWorkspace's TRPCError codes to HTTP status (401/403/404/400).
  Returns a structured 503 with a human-readable hint when
  OPENAI_API_KEY is unset, so the misconfiguration is surfaced rather
  than masked by a fake stream.

* apps/web/app/(app)/[workspaceSlug]/ai/page.tsx: replace the local
  message-state + setTimeout placeholder with useChat from
  @ai-sdk/react. workspace slug is sent on every request body so the
  server can enforce tenant scoping. Adds a ChatErrorBanner that
  parses the JSON error body the route emits and renders amber for
  the "unavailable" case, destructive for other failures.

* apps/web/package.json: pull in @ai-sdk/react as a direct dep
  (previously only transitive via `ai`).

The existing aiRouter.chat tRPC mutation is left intact — it powers
the right-panel command palette via the non-streaming generateText
path, and rebuilding that as streaming was outside the scope of
making the dedicated chat page usable.

Provider selection still flows from env per packages/ai conventions:
OPENAI_API_KEY gates availability, OPENAI_BASE_URL lets operators
route through Ollama on CT 108 transparently, OPENAI_MODEL overrides
the default gpt-4o-mini.

`pnpm lint && pnpm type-check` clean. Closes
plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-wire-ai-chat-to-trpc.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 00:23:21 -05:00
Randall Stillwell
f64d307f72 feat(web): wire workspace-home dashboard to real tRPC queries
Path-A task 2/5. Replaces the hardcoded `stats` (24/8/12) and
hardcoded `recent` list on the workspace-home page with real
workspace-scoped data.

* server/routers/objects.ts: add two new procedures.
  - `objects.stats` returns { openTasks, containers }. Open-task count
    treats null status as open; only `done` and `closed` (per
    packages/shared object-statuses) are terminal. Container count
    aggregates project + space + group rows.
  - `objects.listRecent({ limit })` returns the N most-recently-updated
    rows, descending by updated_at. Excludes archived and excludes
    `workspace`/`group` from the activity feed (containers clutter
    "what did I just touch" recency).
  Both go through workspaceProcedure, so the workspace_id filter
  comes from the middleware-resolved ctx.workspace.id rather than
  any user input.

* app/(app)/[workspaceSlug]/page.tsx: rewrite to consume the new
  procedures via @trpc/react-query. Adds:
  - Skeleton loading state (no flash of zeros).
  - Empty state with a "New task" CTA on workspaces with no objects.
  - Real "X ago" labels on the recent feed.
  - Click-through links from recent rows to /{slug}/{id}.
  - A locally-mounted CreateObjectDialog instance independent of the
    global one in AppShell so the empty-state CTA can pre-seed
    defaultType="task" without coordinating shared state.

* components/ui/skeleton.tsx: new (standard shadcn pulse skeleton).
  Used by the dashboard but reusable across the app.

The scaffolded "Due this week" stat is dropped: `objects` has no
due_at column and the task explicitly preferred dropping a card to
schema-creep.

`pnpm lint && pnpm type-check` clean. Closes
plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-wire-workspace-home-dashboard.md.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 00:17:29 -05:00
Randall Stillwell
1c9deea3fd chore(lint+types): green pnpm lint && pnpm type-check from a clean clone
Path-A first task: get the repo's two repo-wide quality gates passing.
Both were failing from a clean clone in ways that were silently hiding
each other.

Headline fixes:

* apps/web: add an eslint 9 flat config (eslint.config.mjs) using
  FlatCompat against next/core-web-vitals + next/typescript, and switch
  the `lint` script from `next lint` to `eslint .`. Previously `next
  lint` fell into its interactive setup prompt because there was no
  config at all in apps/web, which made `pnpm lint` permanently fail
  before any rule ever ran.
* packages/shared/src/utils/id.ts: replace `randomUUID` from `node:crypto`
  with `globalThis.crypto.randomUUID`. `@tasks/shared` is forbidden from
  using Node-only APIs (per AGENTS.md / repo-overview.mdc) because it
  has to be importable from the browser bundle.

Adjacent fixes pulled in to make the gates actually green:

* apps/mcp-server/tsconfig.json: drop vestigial rootDir / declaration*
  / outDir / sourceMap (build is via tsup, not tsc emit) and add
  allowImportingTsExtensions. The MCP server uses `.ts`-extension
  re-export shims (db.ts / schema.ts / shared-types.ts) so tsup can
  inline workspace .ts sources into the bundle.
* apps/collab-server/tsconfig.json: same simplification.
* apps/mcp-server/package.json: add @types/node so `process.env` in
  packages/database/src/client.ts (transitively pulled into the MCP
  server's type-check) resolves.
* apps/web/components/ui/input.tsx: empty `interface InputProps extends
  React.InputHTMLAttributes<HTMLInputElement> {}` -> `type` alias.
* apps/web/server/lib/workspace-guard.ts: `from(args.table as any)` ->
  `as unknown as PgTable` with a comment. Standard drizzle escape
  hatch for structural generic tables.
* apps/web/components/whiteboard/shapes/{document,project,task}-card.tsx:
  `BaseBoxShapeUtil<any>` -> `BaseBoxShapeUtil<{Shape}>` plus inline
  `declare module "@tldraw/tlschema"` augmentation of
  TLGlobalShapePropsMap. Required adding @tldraw/tlschema as a direct
  devDep of apps/web so the augmentation target resolves; previously
  it was only present transitively under tldraw's own deps.

Result: `pnpm lint && pnpm type-check` exits 0 across all 6 packages.
16 unused-import / exhaustive-deps warnings remain; they're pre-existing
housekeeping and out of scope for this task.

Closes plans/Plan-daily-driver-finish/Epic-shipping-the-shell/
Task-fix-lint-and-shared-types.md (status: done).

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 00:11:52 -05:00
Randall Stillwell
778fe1d321 plans: scaffold daily-driver-finish, saas-hardening, agent-coordination
Three new plan trees that fill in the gaps surfaced during repo review.
Together they map out what remains between the current scaffold-with-stubs
state and a daily-usable, multitenant, agent-coordinated app.

* Plan-daily-driver-finish (P0): turn stubs into real data. Five tasks
  covering the lint/shared-types breakage, hardcoded dashboard mocks,
  AI-page setTimeout placeholder, post-signin landing decision, and a
  cross-browser collab smoke test against the deployed Hocuspocus
  instance.

* Plan-multitenant-saas-hardening (P1): everything multitenant needs
  beyond what Plan-multitenant-cursor-sync already covers. Invites and
  role management, soft-delete + append-only audit log, rate limits on
  the auth + mutation hot paths, and a Vitest + GitHub Actions test
  foundation so PRs can't ship red.

* Plan-agent-coordination (P2): the layer that makes a Task-*.md
  runnable, not just readable. Adds workflow_prompt with task -> epic
  -> plan inheritance, an agent_runs table for auditable sessions, and
  two new MCP tools (claim_task / complete_task) that replace the
  freeform update_object composition agents do today. Includes an
  intentionally-deferred Epic-optional-orchestrator that captures the
  Symphony-shaped runner as a decision point rather than an immediate
  build.

Each task is bead-scale (one focused Cursor session) with explicit
in-scope, out-of-scope, and anti-goal sections so a future agent can
pick up a single Task-*.md and start without scrollback context.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 23:52:22 -05:00
Randall Stillwell
875b1cfc87 auth: case-insensitive emails, Authentik SSO, first-signin workspace provisioning
Three pieces of authentication work that need to land together so OAuth
sign-ins produce a usable session.

* `ensureUserIdByEmail` upserts a `users` row on every OAuth sign-in
  matched case-insensitively on email, then stamps `token.id` with the
  resulting UUID so workspace-scoped tRPC procedures can resolve
  membership. Credentials sign-in already returned the DB id from
  `authorize`; OAuth now does the equivalent.
* `ensureUserHasWorkspace` mints a personal workspace (and `owner`
  member row) on first sign-in for any user that doesn't already
  belong to one, so fresh OAuth accounts don't land in the app with
  no tenant scope. Idempotent; slug collisions retry with a random
  suffix and cap at 5 attempts.
* Migration 0004 adds a `UNIQUE (lower(email))` index on `users` to
  match the lookup pattern and prevent two providers from minting
  rows that differ only in casing. Existing rows are normalized to
  lowercase first; the column-level UNIQUE catches any pre-existing
  duplicates so they get resolved by a human rather than silently
  merged.

Sign-in / sign-up pages add an Authentik SSO button (gated on
`AUTH_AUTHENTIK_*` env vars). Layout switches to GitHub+Google on top
with Authentik full-width below.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-01 23:45:00 -05:00
Randall Stillwell
c582d621ce multi-tenancy: promote workspaces to top-level table
Block A of the EchoDo plan. Workspaces used to live as `objects(type='workspace')`,
which made it impossible to put a real RLS-friendly tenant boundary on the schema
or to give each workspace a stable URL slug. This commit:

- Adds a top-level `workspaces` table (slug unique, owner FK, plan_tier hook).
- Migrates the 8 anchor tables (objects, workspace_members, object_type_defs,
  property_definitions, templates, forms, markdown_backlog_items,
  cursor_sync_mappings) to FK into `workspaces.id` instead of `objects.id`,
  with a hand-augmented data-copy migration that preserves IDs and slug-collision-
  proofs on backfill.
- Introduces a `workspaceProcedure` tRPC middleware + `resolveWorkspace` helper
  that take a UUID-or-slug `workspace` handle and expose `ctx.workspace`. All
  tenant-scoped routers (objects, types, properties, templates, forms, search,
  ai, relations, favorites) now flow through it.
- Updates the web app to pass `workspace` slugs from the URL (or store) instead
  of the old `workspaceId`, including a workspace-sync layer that rewrites
  /<UUID>/... links to /<slug>/...
- Updates the MCP tools (list_objects, create_object, search_objects) and the
  workspace://{handle}/tree resource to accept either a slug or UUID so existing
  agents keep working.
- Adds a Create Workspace dialog and a Workspace Settings page (rename + slug
  rename with redirect, owner-only archive).

Verified locally against a fresh Postgres: migration applies cleanly, slug
uniqueness holds, tenant data is isolated by workspace_id, slug↔UUID resolution
works in both directions, and ON DELETE CASCADE cleans up child rows in the
correct workspace only.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 23:02:55 -05:00
Randall Stillwell
5f2f1e34c0 ai: add code-review graph runtime and prompts
Introduces a small graph executor under packages/ai/src/graph and a
code-review pipeline (analyze, summarize, compose) wired through new
prompt builders. Re-exported from the package index.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 22:14:21 -05:00
Randall Stillwell
456fdd4595 docs: add AGENTS.md and Cursor rules
Repo-wide agent guide at the root plus path-scoped Cursor rules for
the web app, database/migrations, and the plans/ markdown backlog.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 22:14:16 -05:00
Randall Stillwell
b992db5b3e collab: replace createRequire shim with normal imports
The collab server was using createRequire() with hardcoded relative paths
(../../../packages/database/package.json, ../node_modules/@hocuspocus/server/...)
to grab `eq` from drizzle-orm and `Forbidden` from @hocuspocus/common. That
worked under tsx in dev but fell apart in the bundled prod image because
those paths don't exist there and pnpm's symlink topology in the runtime
node_modules wasn't reachable from inside the bundled dist file.

Result at runtime: Cannot find module '@hocuspocus/common' on every
collab restart, infinite crash loop.

Switch both to plain ESM imports — tsup bundles them into dist/index.mjs
directly, no runtime resolution needed. Add @hocuspocus/common and
drizzle-orm as explicit deps so they're properly tracked.

Verified locally: bundle now resolves cleanly with no createRequire calls
(actually shrinks from 304 KB to 102 KB after dead-code elimination).

Made-with: Cursor
2026-04-28 15:14:03 -05:00
Randall Stillwell
3856d11944 docker: raise web build V8 heap to 5 GB to match 8 GB host
CT 107 bumped to 8 GB RAM. Capping the heap below the available memory
makes V8 GC-thrash near the limit and contributes to oom-kills. Set
--max-old-space-size to 5120 MB (~60% of host) so the compile has real
headroom while leaving room for kernel + dockerd + buildkit + tsup workers.

Made-with: Cursor
2026-04-28 13:33:46 -05:00
Randall Stillwell
829cbdc899 collab/mcp: bundle workspace deps so runtime doesn't import .ts files
@tasks/database (and @tasks/shared) export raw .ts files via "main" /
"exports", which works fine for tsx/dev but blows up at runtime in the
production image:

  ERR_UNKNOWN_FILE_EXTENSION: Unknown file extension ".ts" for
  /app/packages/database/src/client.ts

tsup was leaving those workspace imports as externals in the output, so
the deployed dist/index.mjs still tried to resolve them at startup.
Switch each app to a tsup.config.ts that sets noExternal: [/^@tasks\\//],
which inlines workspace packages into the bundle while keeping
node_modules deps (postgres, drizzle-orm, hocuspocus, mcp-sdk, etc.)
external.

Verified locally: collab-server bundle size goes from 7 KB to 304 KB,
confirming @tasks/database is now compiled in. Also fixed the collab
start script to point at index.mjs (tsup ESM output) instead of .js.

Made-with: Cursor
2026-04-27 16:47:17 -05:00
Randall Stillwell
403437dafc docker: bump web build heap to 2.5GB and serialize behind collab/mcp
The 1.5GB heap cap was actually too aggressive for the Next 15 webpack
compile on this monorepo: V8 spirals into GC churn near the cap, runs
the host out of free memory, and oom-killer SIGKILLs the build (exit 255).

With 4GB on the host now:
  - Cap V8 heap at 2.5GB (~70% of host RAM) — gives the compile real
    headroom while leaving room for kernel + dockerd + concurrent COPY
    layers from the collab/mcp runtime stages.
  - Add depends_on so the lighter collab + mcp services finish building
    before the web target starts its peak-memory compile, instead of
    fighting it for memory in parallel.

Made-with: Cursor
2026-04-27 15:49:41 -05:00
Randall Stillwell
70c9bbf1e5 docker: skip type-check + lint during prod web build
next build was OOM-killed (exit 255) on the Coolify host during
'Linting and checking validity of types' — tsc pulls the whole type graph
into memory and pushes the build past available RAM.

Type-checking and linting belong in CI / pre-commit, not in the prod
container build. Skip them via next.config and cap the Node heap to 1.5 GB
so any future memory blow-up surfaces as a JS OOM instead of a SIGKILL.

Made-with: Cursor
2026-04-27 14:58:12 -05:00
Randall Stillwell
3fa891bf08 docker: ensure apps/web/public exists so web runtime COPY succeeds
The Next.js standalone runtime stage copies apps/web/public into the image,
but the directory was never committed since the project hasn't shipped any
static assets. BuildKit fails with "not found" on the COPY. Adding an empty
.gitkeep guarantees the directory exists at build time and lets future static
assets drop in without further build changes.

Made-with: Cursor
2026-04-27 14:46:47 -05:00
Randall Stillwell
9cdee7f84e docker: unify per-service Dockerfiles into one multi-stage file
Collapse Dockerfile.web / Dockerfile.collab / Dockerfile.mcp into a single
docker/Dockerfile with shared `deps` stage and `web` / `collab` / `mcp`
runtime targets. BuildKit hashes the deps stage identically for all three
targets, so `pnpm install` runs once instead of three times in parallel —
fixes the OOM kill on the Coolify host (CT 107) during `docker compose build`.

Both docker-compose.yml (local dev) and docker-compose.coolify.yml now
select services via `target:` instead of separate dockerfile paths.

Made-with: Cursor
2026-04-27 14:38:39 -05:00
Randall Stillwell
ba519a8b78 fix(web): import @tasks/ai via workspace alias instead of relative path
Two AI components were importing from ../../../../packages/ai/src using
relative paths that escape the workspace root. This worked locally because
all packages are siblings on disk, but failed in Docker where Dockerfile.web
only copies apps/web, packages/database, and packages/shared into the
build context — packages/ai never made it in.

Changes:
- Add @tasks/ai as a workspace dependency in apps/web/package.json
- Switch both imports (command-palette.tsx, ai-block.tsx) to "@tasks/ai"
- Add @tasks/ai to transpilePackages in next.config.ts and the docker variant
- Copy packages/ai into the Docker build context (Dockerfile.web)
- Refresh pnpm-lock.yaml for the new workspace edge

Verified locally: web builds compile cleanly past the previously failing
"Module not found" errors. (Local final step hits an unrelated ENOSPC on
the dev disk; Coolify's volume has plenty of headroom.)

Made-with: Cursor
2026-04-27 12:57:27 -05:00
Randall Stillwell
3ddbb4fb83 fix(deploy): preserve pnpm per-package node_modules in docker builds
The previous multi-stage `deps` → `builder` split copied only the root
/app/node_modules from the deps stage, but pnpm workspaces also create
per-package node_modules directories (e.g. apps/web/node_modules) that
contain the .bin symlinks for `next`, `tsup`, etc. Without those, the
builder stage failed with `sh: tsup: not found` and `sh: next: not found`.

Collapse `deps` and `builder` into a single stage so the per-package
node_modules survive intact. pnpm's content-addressable store keeps
re-installs nearly free on cache hits, and Docker layer caching still
short-circuits the install step when only source files change.

For collab and mcp runner stages, also copy the per-app node_modules
so runtime dependency resolution works.

Made-with: Cursor
2026-04-26 22:52:04 -05:00
Randall Stillwell
0cf1e6f317 fix(deploy): use repo-root build context in coolify compose
Coolify invokes `docker compose` with --project-directory set to the
repository root, not this file's directory. Previous `context: ..` was
resolving to /artifacts (one level above the repo) and failing with
`resolve : lstat /artifacts/docker: no such file or directory`.

Switch all three services (web, collab, mcp) to `context: .` so the
build context is the repo root and `dockerfile: docker/Dockerfile.X`
resolves correctly.

Made-with: Cursor
2026-04-26 21:52:29 -05:00
Randall Stillwell
663bc77afe feat: ECHODO app shell, Coolify deploy, Authentik + Umami
Bundles in-flight ECHODO work with the Coolify deployment configuration:

App
- New routes: ai, forms, planner, settings (templates/types), teams,
  doc detail, whiteboard detail
- New components: app shell rework (icon-rail, top-header), forms
  builder/renderer/responses, types manager, objects creation dialog,
  card primitive, form + overview views
- New tRPC routers: favorites, forms, types, workspaces; updates to
  health and objects routers
- Markdown backlog sync (packages/database) + cursor-sync schema/migrations
- Schema additions: forms, types, favorites, markdown_backlog, cursor_sync
- Initial Drizzle migrations checked in

Deployment
- docker/docker-compose.coolify.yml: drops bundled Postgres/Redis
  (uses CT 102 shared services), removes host port mappings, adds
  Coolify SERVICE_FQDN_* magic vars for web + collab
- .env.example rewritten as the full ECHODO/Coolify variable manifest
- NextAuth gains an Authentik OIDC provider (gated on env presence)
- Root layout injects Umami tracking script when configured;
  metadata title flipped to ECHODO

Security
- .gitignore expanded to exclude AGENT-DEPLOY.md, .env.*, secrets/,
  credentials.*, *.key, *.crt, *.pem, ssh keys

Made-with: Cursor
2026-04-26 14:34:34 -05:00
Randall Stillwell
a508ece6e7 feat: Full project management application scaffold
Complete architecture for a ClickUp/Notion/Miro-class project management app:

- Turborepo monorepo with Next.js 15, TypeScript, PostgreSQL (Drizzle ORM)
- Object-centered database schema (everything is an Object: tasks, projects, docs, whiteboards)
- NextAuth v5 authentication with credentials + OAuth providers
- tRPC v11 API layer with full CRUD for objects, properties, relations, templates, search
- Three-panel UI: collapsible sidebar, center content area, push-in right panel
- Purple/teal theme with light/dark mode via Shadcn/ui + Tailwind CSS
- Multiple views: List, Kanban board (dnd-kit), Table (spreadsheet), Embedded iframe
- TipTap rich text editor with slash commands, custom blocks (callout, toggle, mention, embed, divider), AI block
- Real-time collaboration via Yjs + Hocuspocus with presence/cursors
- tldraw whiteboard with custom shape cards (task, document, project)
- MCP server exposing all app data/tools for AI agents
- AI chat panel, editor AI slash commands, Cmd+K command palette
- Template system with built-in templates (Bug Report, Meeting Notes, Sprint)
- Full-text search with result highlighting
- Docker Compose for full-stack deployment (web + collab + postgres + redis)

Made-with: Cursor
2026-03-26 22:39:16 -05:00