Commit Graph
1545 Commits
Author SHA1 Message Date
g-butandClaude Sonnet 4.6 1acf9c602d fix(projects): show name-save errors inline instead of silently reverting
Same pattern as PersonDetail: NameEditor now manages saving/error state
locally instead of delegating to useInlineEdit.commit (which always exits
edit mode in finally, swallowing API errors).

saveName in ProjectDetailHeader now throws on non-ok response so the
editor can catch and display the message (e.g. "A project with that name
already exists"). Also removes onBlur auto-save which prevented clicking
Cancel when an error was shown.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 17:04:22 +02:00
g-butandClaude Sonnet 4.6 9e1dcc2fc4 fix(people): show inline-edit errors instead of silently reverting
useInlineEdit.commit always calls setEditing(false) in finally, so a 409
(duplicate name) or any other API error was silently swallowed — the drawer
closed edit mode and showed the old value with no feedback.

Replace nameEdit.commit / descEdit.commit with local saving+error state.
The hook still manages editing/draft/start/cancel; the async work now runs
directly so errors can be displayed inline and edit mode stays open until
the user either fixes the input or cancels.

Also removed onBlur=commitName which would re-submit on click-away, making
it impossible to click Cancel when an error was shown.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:53:38 +02:00
g-butandClaude Sonnet 4.6 514eae74eb fix: PATCH 404 guards + subscription frequency/nextDue editing
Bug fixes:
- events/[id] PATCH: return 404 when record not found instead of
  { ok: true, event: undefined } — EventCard uses json.event directly
  so undefined would corrupt client state on stale IDs
- commitments/[id] PATCH: same guard for consistency

Feature:
- SubscriptionActions edit form now includes frequency (select) and
  nextDue (date) fields; both are sent in the PATCH and the API+schema
  already handled them — only the UI was missing

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:47:19 +02:00
g-butandClaude Sonnet 4.6 47d45dee15 fix(ux): discoverability + empty-state improvements
- AddHabitForm/AddCommitmentButton: lift trigger text from text-white/20-25
  to text-white/35-40 so "Add habit" / "Add commitment" links are visible
  without hover
- PersonCard Log button: sm:opacity-0 → sm:opacity-50 so the CRM's primary
  action is dimly visible on desktop instead of completely hidden until hover
- CommitmentsCard: replace flat "No active commitments" text with centered
  icon + sub-hint pointing to the add button below
- PeopleGrid: add proper empty state with Users icon; filtered-empty shows
  a "Clear filters" inline link to restore results

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:33:25 +02:00
g-butandClaude Sonnet 4.6 4f58b109ab fix(ux): readability + click target fixes from UX audit
1. Typography: bump text-[9px]/text-[10px] category/date labels to
   text-[11px] in EventsDueCard; lift "Open Events/Goals →" link opacity
   from text-white/25 to text-white/40 so they're visible without hover.

2. Click targets: p-1 → p-1.5 on all icon-only action buttons
   (EventCard, CommitmentItem, FulfillCommitmentButton, HabitRow pencil/X);
   add p-1 + rounded to the bare habit-toggle button so tap target is ~26px.

3. Truncated text: add title= to truncated person name, profession/location,
   and goal title so hover reveals the full string.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:26:10 +02:00
g-butandClaude Sonnet 4.6 aafb3e86bc feat(events): add inline editing for name, deadline, description, url
Events were previously immutable after creation — only archive and delete
were available. PatchEventBody now accepts all editable fields; the API
route spreads them into the DB update; EventCard gains an edit mode
(pencil icon → form → Save/Cancel) that optimistically updates local state.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 16:14:19 +02:00
g-butandClaude Sonnet 4.6 70dc5e14f7 refactor(ssot): derive NewProjectButton/NewPersonButton input types from Zod schemas
Exports CreateProjectInput and CreatePersonInput (z.infer<>) from their
canonical query files and replaces the inline anonymous generics in each
button component. All useCreateMutation<T> calls now use named types.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 15:58:16 +02:00
g-butandClaude Sonnet 4.6 a14e392f48 fix(ux): expose notes field in NewSubscriptionButton; derive input types from Zod
NewSubscriptionButton was missing the 'notes' field — users could set notes via
the inline edit (SubscriptionActions) but not at creation time.

Simultaneously cleans up the last inline body type definitions in components:
- AddCommitmentButton: import type CreateCommitmentInput from db/queries/today
- NewSubscriptionButton: import type CreateSubscriptionInput from db/queries/money
- lib/api/goals: use CreateGoalInput (import type from db/queries/goals)
All three query files export z.infer<> type aliases as the canonical types.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 15:47:44 +02:00
g-butandClaude Sonnet 4.6 f80c86e19d feat(ux): link all SummaryBar pills + extract DEFAULT_TIMEZONE constant
- pendingDrafts pill now links to /today (where ActionQueueCard lives)
- overdueCommitments pill now links to /today (where CommitmentsCard lives)
- urgentAlerts pill now links to /system
- Extract DEFAULT_TIMEZONE="Europe/Zurich" to lib/constants.ts; use it in
  crons route instead of hardcoded string

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 15:23:23 +02:00
g-butandClaude Sonnet 4.6 2c93c85d1c refactor(ssot): derive cron body types from Zod schemas, remove stale interfaces
lib/api/crons.ts had CreateCronJobBody/PatchCronJobBody interfaces that were
missing model, timeoutSeconds, and tz fields present in the canonical Zod schemas.
Now exports z.infer<> types from lib/crons.ts via import type (erased at build
time, no risk of bundling fs code into client bundles).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 15:14:19 +02:00
g-butandClaude Sonnet 4.6 599083a68e fix(ssot): use HEALTH_ACTIVE_DAYS constant in ActionQueueCard reasoning
Replaces hardcoded "30+ days" string with the HEALTH_ACTIVE_DAYS constant
so the threshold stays consistent with the rest of the codebase.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 15:03:32 +02:00
g-butandClaude Sonnet 4.6 3b6496ecc5 refactor(ssot): remove duplicated CreateGoalBody interface from lib/api/goals
The interface duplicated the Zod schema in db/queries/goals.ts.
Inline the type in createGoal's parameter; let TS infer the generic
in useCreateMutation from the request function signature.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 14:42:08 +02:00
g-butandClaude Sonnet 4.6 8220602485 refactor(ssot): extract remaining inline schemas; fix unused var
- CreateCommitmentBody + PatchCommitmentBody → db/queries/today (where commitment queries live)
- CreateCronBody + PatchCronBody + RunCronBody → lib/crons (where cron helpers live)
- Remove unused pct variable in MemorySummaryCard (eslint warning)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 14:24:44 +02:00
g-butandClaude Sonnet 4.6 94bfe6d9c6 refactor(ssot): extract PatchProjectBody to db/queries/projects
Completes the schema sweep — all inline Zod schemas in route files that
have a corresponding db/queries/ file now live there instead.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 14:10:40 +02:00
g-butandClaude Sonnet 4.6 612cd54256 refactor(ssot): extract inline Zod schemas to their query files
CreateProjectBody, CreatePersonBody, PatchPersonBody → db/queries/{projects,people}
PatchGoalBody → db/queries/goals (alongside MilestoneSchema + CreateGoalBody)
Route files now import schemas instead of defining them inline.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:57:58 +02:00
g-butandClaude Sonnet 4.6 f1c3f90e46 feat(nav): move Memory from sidebar into System page
Memory (knowledge graph telemetry) was occupying a sidebar nav slot but
isn't daily user content — it's infrastructure stats. Removed the Memory
nav item and embedded a compact MemorySummaryCard (entities, relations,
type breakdown) at the bottom of System, with a "View details →" link to
the full /memory page which is preserved for direct access.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:36:39 +02:00
g-butandClaude Sonnet 4.6 ca30ba7e12 fix(ux): rename Action Queue buttons from Approve/Reject to Done/Skip
"Approve" and "Reject" implied a review workflow. The actual meaning is
"I did this / mark complete" and "skip this action". Done/Skip is clearer
especially for check-in prompts where users aren't approving a draft —
they're just logging whether they reached out. Compact tooltips updated too.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:20:31 +02:00
g-butandClaude Sonnet 4.6 c017f6a1cf feat(ux): make SummaryBar pills navigable links
Goals, goal-due-soon, and events-deadline pills were static divs with no
navigation affordance. Wired them to /goals and /events respectively.
Drafts/overdue/alerts intentionally left static — they point to cards
already visible on the Today page, so linking would be a no-op reload.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:08:36 +02:00
g-butandClaude Sonnet 4.6 676673bc35 fix(habits): add habit creation to /habits page — remove dead-end empty state
The /habits page empty state said "Add habits from the Today page" with no
link and no form — a dead end. Added AddHabitButton (thin client wrapper
around AddHabitForm) and wired it into both the empty state and the bottom
of the habits list, so habits can be created from the dedicated page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 13:00:06 +02:00
g-butandClaude Sonnet 4.6 35497c2041 fix(ux): promote "Log a conversation" from ghost link to visible pill button
The button was text-white/25 — nearly invisible against the dark background.
This is the primary daily action that feeds the entire contact-health loop
(stale alerts, action queue, relationship scores). Made it a pill with
subtle bg/border at white/55 so it reads as clickable without competing
with the page header.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 12:45:52 +02:00
g-butandClaude Sonnet 4.6 1b17f467c5 fix(ux): improve contrast and text wrapping on Today page cards
- CommitmentItem: truncate → line-clamp-2 so commitment text wraps instead
  of being silently cut off mid-sentence
- ActionQueueCard: bump grouped check-in body preview from white/30 to
  white/50 and switch to line-clamp-2 for multi-line visibility
- EventsDueCard: event.type label white/25 → white/40 to meet minimum
  contrast for secondary labels

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 12:30:56 +02:00
g-butandClaude Sonnet 4.6 3d39538aad refactor(ssot): extract CreateGoalBody/CreateEventBody/PatchEventBody to query files
Goals: CreateGoalBody added to db/queries/goals.ts alongside MilestoneSchema —
route now imports from there, removing the inline z.object.

Events: CreateEventBody + PatchEventBody (with EVENT_STATUSES cast) added to
db/queries/events.ts — both route files slimmed to just the import.

Also: session panel now renders the todos field (in amber) when non-zero, so open
TODOs are visible from the project overview drawer.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 12:08:00 +02:00
g-butandClaude Sonnet 4.6 b5e23b98e0 feat(projects): surface Claude session state in project overview tab
Adds GET /api/sessions?project=<name> which reads ~/.claude/sessions/<name>.md
(case-insensitive, dash-tolerant match) and parses done/next/tests/todos/health.

ClaudeSession component in ProjectOverviewTab fetches this on mount and renders a
compact status panel — visible for Cockpit, OrangeCat, kivvi, and any other project
that has an active session file. Projects without a session file render nothing.

Also fixes a DRY violation in SubscriptionActions where the delete-record handler
was duplicated verbatim as an inline arrow function in the permanent DeleteButton.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-27 11:48:55 +02:00
g-butandClaude Opus 4.7 e5f9d09d51 refactor(ssot): extract subscription schemas next to money.ts helpers
CURRENCIES_ENUM and FREQUENCIES_ENUM casts were byte-identical in both
/api/subscriptions/route.ts and /api/subscriptions/[id]/route.ts —
same pattern as habits FREQUENCIES fixed in 597c356.

CreateSubscriptionBody and PatchSubscriptionBody (which consume those
casts plus a SUB_STATUSES tuple) now export from db/queries/money.ts
next to cancelSubscription and calculateMonthlyBurn. Both route files
drop z import, both enum cast locals, and the full schema bodies.
money.ts gains one z import in exchange for being the single place
where subscription field validation lives.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 10:15:44 +02:00
g-butandClaude Opus 4.7 597c3565c9 refactor(ssot): extract habit/goal schemas next to helpers, use RESERVED in ProjectGrid
Three SSOT violations fixed:

1. habits routes: FREQUENCIES cast tuple was byte-identical in both
   /api/habits/route.ts and /api/habits/[id]/route.ts.
   CreateHabitBody + PatchHabitBody now export from db/queries/habits.ts
   next to createHabit/updateHabit. Both routes drop z import + cast.

2. goals route: MilestoneSchema was inline in /api/goals/[id]/route.ts,
   mirroring the Milestone TS type in db/schema/goals.ts.
   MilestoneSchema now exports from db/queries/goals.ts where
   GoalWithChildren already imports Milestone from the schema.

3. ProjectGrid: attr-key exclusion list ["production_url","url","repo",
   "github_repo","owner","description"] was a partial duplicate of RESERVED
   from project-detail-types.ts (which already covers all reserved keys).
   Replaced inline array with the imported RESERVED constant.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 10:07:24 +02:00
g-butandClaude Opus 4.7 bb35acf14e refactor(api): extract SetAttrBody/DeleteAttrBody schemas next to their helpers
Same shape as the just-shipped CreateInteractionBody extraction
(6472ee9). The attrs routes' runtime was deduped in 2e1859b
(upsertEntityAttribute / deleteEntityAttribute helpers) but the two
zod schemas — SetAttrBody (key+value) and DeleteAttrBody (key) — were
left inline and byte-identical across both /api/<entity>/[id]/attrs
routes.

Both schemas now export from db/queries/utils.ts next to the helpers
that consume them. Each route shrinks ~3 lines and drops the z import
entirely. Net: -3/+9 (only +9 because the new shared definitions are
counted once instead of twice).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:14:36 +02:00
g-butandClaude Opus 4.7 6472ee9395 refactor(api): extract CreateInteractionBody schema next to the helper
Last interactions-route dedup (a6850ef) extracted the runtime
helper but kept the 12-line zod validator + DIRECTIONS cast tuple
inline in both routes. With the validator only consumed by the
two byte-identical sibling routes that already share
createEntityInteraction(), there was no reason to keep the schema
duplicated.

CreateInteractionBody now exports from db/queries/utils.ts next to
its single-consumer helper. Each route shrinks to ~17 lines of
HTTP shell with no validator code, no DIRECTIONS cast, no zod
import.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:09:46 +02:00
g-butandClaude Opus 4.7 a435dfc716 chore(ssot): centralize "cockpit-ui" source label, default to PROJECT_CHANNELS[0]
Two small SSOT cleanups:

- The `source: "cockpit-ui"` literal that tags rows created via the
  Cockpit UI was repeated in 5 .insert callsites (people, events,
  projects, commitments routes + the shared upsertEntityAttribute
  helper). Now `SOURCE_COCKPIT_UI` in lib/constants.ts. A future audit
  query like "rows I created via the app" pivots off one constant
  rather than hoping no one typo'd "cockpit_ui" in a sixth callsite.

- ProjectOverviewTab seeded its activity-log channel state with the
  literal "work-session". The PROJECT_CHANNELS tuple is imported in
  the same file with "work-session" as element [0]; using
  PROJECT_CHANNELS[0] makes the relationship explicit and survives
  a future reordering.

scripts/seed.ts's "knowledge.sqlite" / "contact-resolver" labels stay
as inline literals — that's a one-shot import script where the strings
genuinely describe the source-of-truth of those rows, and centralising
would be moving labels for the sake of moving them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:05:09 +02:00
g-butandClaude Opus 4.7 a985055c14 fix(db): hot-reload-safe singleton client, cap pool at max=5
Investigated the 17/18 smoke regression I'd attributed to a stale
Next dev server last turn. Real cause was a Postgres connection-slot
leak: `pg_stat_activity` showed 94 connections from postgres.js to
the cockpit DB, and any new query — psql included — failed with
"remaining connection slots are reserved for roles with the
SUPERUSER attribute" (53300).

Root cause: src/db/index.ts created a fresh `postgres()` client at
module load. Next.js dev re-evaluates server modules on every
change, and postgres.js defaults to a 10-connection pool per client
instance — pools stacked up across hot reloads and eventually
exhausted Postgres slots. /api/people/[id] failed first because it
issues 5 parallel queries via Promise.all and was the route most
likely to hit a saturated pool.

Fixes:
- Memoize the client on globalThis so module reloads in dev reuse
  one pool instead of stacking new ones.
- Set `max: 5` so the footprint is small and any real connection
  leak surfaces quickly rather than after a day of dev.

The user still needs to restart their existing `npm run dev` to
release the 94 already-leaked connections — this fix prevents the
leak from recurring after that restart.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 23:00:07 +02:00
g-butandClaude Opus 4.7 5d86c6a9fe refactor(actions): introduce ACTION_TYPE enum, sweep 5 literal sites
The actions.type column listed its valid values only in a doc comment
("send_message, send_email, create_event, create_commitment,
follow_up, other") — no canonical enum. Five literal sites used the
strings directly: ActionQueueCard's TYPE_ICONS keys + the check-in
filter (2 spots) + the standalone group's `type`, plus actions.ts's
INTERACTION_ACTION_TYPES Set.

Now ACTION_TYPE + ActionType live in lib/constants/statuses, the
schema column gets `.$type<ActionType>()` (the doc comment is gone —
the type is the source), TYPE_ICONS is `Record<ActionType, ...>` so
TS forces a covering icon for every member (caught: OTHER had no
icon, now points at Inbox), the SEND_MESSAGE check + group type
go through the constant, and the Set is explicitly typed
`new Set<ActionType>([...])` so .has() accepts any ActionType
(without the explicit type, TS narrowed the Set to a 3-member
literal-union that .has() then rejected for ActionType inputs).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:56:29 +02:00
g-butandClaude Opus 4.7 00735be6a0 refactor(money): $type<> currency + frequency, drop "one-time" literal outlier
Final pair of text columns missing `.$type<>()`:

- subscriptions.currency: now $type<SubscriptionCurrency>(). The
  literal "CHF" default stays as-is — it's already the canonical
  default and the type is ["CHF","USD","EUR","GBP"], so the literal
  cannot drift.
- subscriptions.frequency: now $type<SubscriptionFrequency>() with
  the default routed through FREQUENCY.MONTHLY (SSOT).

Side-effects:
- Both subscriptions API routes' `CURRENCIES_ENUM` and
  `FREQUENCIES_ENUM` were typed `readonly [string, ...string[]]`,
  so z.enum widened to string and the tightened `.set()` rejected
  it. Tightened to the typed tuples — matches what every other
  enum cast in /api now does.
- scripts/seed.ts gains two boundary casts for sqlite legacy data.
- SubscriptionActions had `frequency === "one-time"` — the only
  literal outlier in that file (every other branch already used
  FREQUENCY.X). Now also goes through FREQUENCY.ONE_TIME.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:49:13 +02:00
g-butandClaude Opus 4.7 109fbaac6c refactor(people): centralize SortMode, dedupe two parallel definitions
`type SortMode = "recent" | "name" | "health"` was defined in two
places (queries/people.ts and components/people/PeopleGrid.tsx) and
the corresponding values list appeared twice more (SORT_ORDER in
PeopleGrid, VALID_SORTS in api/people/route). Four places to update
when adding a new mode.

Canonical home is now lib/constants/statuses.ts as `SORT_MODE` +
`SortMode` — same shape as every other domain enum. Critically,
this lets client components (LogConversationButton) import the
values directly; queries/people.ts re-exports for callers that
already point there.

Hit one runtime regression along the way and reverted on the spot:
my first version put SORT_MODE in queries/people.ts, but a value
import from there into a "use client" file pulls in the server-only
db module → all 18 routes 500'd until I moved the definition to
the client-safe constants file. Recorded here so future work knows
why this enum lives in lib/ not in queries/.

While there: searchPeople's default `sort: SortMode = "recent"`
and the API route's `?? "recent"` fallbacks now route through
SORT_MODE.RECENT, and the inline `?sort=recent` URL string in
LogConversation goes through `${SORT_MODE.RECENT}`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:45:11 +02:00
g-butandClaude Opus 4.7 21c0fdf0fd refactor(interactions): introduce INTERACTION_DIRECTION enum, sweep 9 literal sites
The "inbound"/"outbound" union was repeated as raw string literals
across nine sites (useState type params, two zod schemas, helper
function signatures, JSX comparisons, optimistic-update payloads)
even though every other domain enum (HABIT_FREQUENCY, GOAL_STATUS,
SUB_STATUS, ENTITY_TYPE, etc.) was centralized in
lib/constants/statuses. This was the obvious gap.

Added INTERACTION_DIRECTION + InteractionDirection to the constants
file, tightened the schema's `direction` column with `.$type<>()`,
typed the two query helpers (createInteraction, createEntityInteraction)
and the two API zod enums against the union, and replaced literals
in the four consuming components (PersonCard, PersonInteractionsSection,
LogConversationButton, ProjectOverviewTab) plus actions.ts and
memory/page.tsx.

Net: every "inbound"/"outbound" literal in src/ outside the constants
file itself is gone. A future rename of the persisted values now flows
through the type system.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:38:32 +02:00
g-butandClaude Opus 4.7 30e7c73394 chore(events): replace 2 hardcoded "archived" literals with EVENT_STATUS.ARCHIVED
Two stragglers from the SSOT-tightening lane: EventCard.tsx passed
`status: "archived"` in the archive PATCH body, and EventsGrid.tsx
optimistically set the same string when moving an event into the
archived list. Both now route through the EVENT_STATUS.ARCHIVED
constant — same convention as the rest of the codebase, and a future
rename of the value flows through automatically.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:30:37 +02:00
g-butandClaude Opus 4.7 a6850ef703 refactor(api): dedupe byte-identical interactions routes + close ownership gap
Last turn I claimed "interactions are already shared" while looking
at this lane — wrong. /api/people/[id]/interactions and
/api/projects/[id]/interactions were byte-identical (`diff` returned
no output) and neither verified that the entity belongs to the user
before writing.

The unverified write was a small hole — for a single-user app today
it doesn't matter, but it diverged from the attrs routes that I
just standardised on the verify-then-write pattern.

Extracted createEntityInteraction() into db/queries/utils.ts: it
checks entity ownership, inserts, and returns the row (or null →
caller 404s). Both routes now ~25 lines of HTTP shell, matching
the attrs-route shape.

Net: byte-identical files collapsed into one helper + two thin
shells, and a write-without-ownership-check gap closed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:27:44 +02:00
g-butandClaude Opus 4.7 2e1859bd62 refactor(api): extract upsert/delete entity-attribute helpers, dedupe attrs routes
/api/people/[id]/attrs and /api/projects/[id]/attrs were 76-line files
with effectively identical bodies — verify the entity belongs to the
user, then upsert/delete a row in `attributes`. The "person vs
project" distinction in the routes was purely lexical (different
variable name and a comment); both already operate on the shared
`entities` table without filtering by entity type.

Extracted upsertEntityAttribute() and deleteEntityAttribute() into
db/queries/utils.ts (next to the existing fetchAttributesByEntityIds
helper). Both routes now ~40 lines of pure HTTP shell — parse params,
parse body, delegate, return.

Net: ~75 lines removed; the route shells are now near-identical (which
is fine and intentional — they're separate URLs by Next.js routing).
A future "set an attribute on any entity" generic route would be a
trivial third caller of the same helpers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:25:00 +02:00
g-butandClaude Opus 4.7 097d3ff940 refactor(habits): type updateHabit's set object to schema, not Record
Last commit caught the same pattern in 5 PATCH route handlers but
missed updateHabit in queries/habits.ts: its `set: Record<string,
unknown>` similarly bypasses drizzle's typed .set(). Now
`Partial<typeof habits.$inferInsert>` like the rest, so the
schema-tightened HabitFrequency union flows all the way through
the helper too.

Net: every drizzle .set() callsite in src/ that builds its payload
incrementally now goes through a typed Partial<$inferInsert>.
The remaining `Record<string,unknown>` in src/ are the schema's
metadata jsonb columns (genuinely generic) and the client-side
patchGoal helper (different concern from server-side .set).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:22:02 +02:00
g-butandClaude Opus 4.7 983d6aabd4 refactor(api): type PATCH patch objects to the schema, not Record<string,unknown>
Five PATCH route handlers built their drizzle `.set()` payload as
`patch: Record<string, unknown>`. This was the type-safety hole that
made the schema $type<>-tightenings I shipped over the last several
turns essentially decorative — drizzle's set() accepts the wide type
without checking, so the typed status columns stopped enforcing at
the API layer.

Now each patch is `Partial<typeof <table>.$inferInsert>`, which:
- propagates the schema's typed columns (status: GoalStatus, etc.)
- catches typo'd field names (patch.tilte = ... no longer compiles)
- keeps the existing partial-update semantics

Side-catch in /api/goals/[id]: PatchGoalBody.milestones was
`z.array(z.unknown())`, so the inbound shape was unvalidated. The
new tighter patch type rejected the assignment, which surfaced the
gap. Replaced with a proper MilestoneSchema (`{title, done, date?}`)
that enforces the actual shape — fixing a real validation hole, not
just papering over the type error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:19:48 +02:00
g-butandClaude Opus 4.7 b4d10fa2a6 refactor(api): tighten Object.values widening casts to their union types
Three sibling /api/[resource]/[id] PATCH handlers still cast their
status/frequency enum tuples as `[string, ...string[]]`, so z.enum's
inferred output narrowed to `string` rather than the canonical union.
The /api/events/[id] equivalent was already tightened last turn —
bringing habits, subscriptions, and goals in line.

Now z.enum(STATUSES) on each route returns the typed union directly
(HabitFrequency / SubStatus / GoalStatus), matching the schema column
types I just $type<>-tightened.

While there: updateHabit's helper signature still typed
`frequency?: string`, even though createHabit was tightened to
HabitFrequency last week — fixed for SSOT consistency.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:16:22 +02:00
g-butandClaude Opus 4.7 b0060a539c refactor(schema): finish $type<> coverage on the remaining 4 status columns
Last turn I claimed this lane was done — it wasn't. goals.status,
commitments.status, events.status, and actions.status were still
plain `text("status")` while their canonical unions sat next door
in lib/constants/statuses (GoalStatus, CommitmentStatus, EventStatus,
ActionStatus). Now consistent with the just-tightened entities.type
and subscriptions.status.

Each gains `.$type<XStatus>()` and the literal default ("active",
"draft") routes through the constant (XSTATUS.ACTIVE / .DRAFT) — so
the SSOT is the `as const` enum, not duplicated literals.

Two boundary follow-ups:
- scripts/seed.ts: two more `as XStatus` casts where sqlite legacy
  data crosses into Postgres.
- /api/events/[id]: `STATUSES = Object.values(EVENT_STATUS)` was
  typed `[string, ...string[]]` so z.enum produced `string` and
  drizzle's tightened .set() rejected it; tightened to
  `[EventStatus, ...EventStatus[]]`.

Net: every text-status column in the codebase is now `.$type<>`-
typed, and the literal defaults all derive from the enums.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:13:12 +02:00
g-butandClaude Opus 4.7 20dda22aa1 refactor(schema): type entities.type and subscriptions.status with their unions
Same pattern as the just-shipped habit-frequency tightening — two more
text columns with canonical union enums in lib/constants/statuses but
no `.$type<>()` annotation, so Drizzle inferred plain string and the
unions only existed in display/comparison code.

- entities.type: now $type<EntityType>(). Drops the `type as EntityType`
  cast inside TypeBadge in memory/page.tsx — TypeBadge prop is now
  EntityType directly.
- subscriptions.status: now $type<SubStatus>(). Drops the `as SubStatus`
  cast in money/page.tsx; the literal `"active"` default also now
  routes through SUB_STATUS.ACTIVE (SSOT).

scripts/seed.ts gains two boundary casts (`as EntityType`, `as SubStatus`)
for the legacy sqlite import — sqlite is the system boundary where
unvalidated string data enters, so casting there is appropriate.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:08:38 +02:00
g-butandClaude Opus 4.7 bf727bc251 refactor(habits): type frequency end-to-end as HabitFrequency, not string
The frequency column was stored as text without a TypeScript-level
constraint (`text("frequency")`), so Drizzle inferred plain `string`
everywhere it was read. The doc comment "/** daily | weekdays | weekly */"
was the only place that knowledge lived in code form. Consequence:
- HabitRow.tsx had to `as HabitFrequency` when feeding `habit.frequency`
  to the inline-edit draft.
- HabitWithStatus / HabitWithHistory / createHabit / isDueToday all
  hand-typed it as `string`, losing the union narrowing.

Now `.$type<HabitFrequency>()` on the schema column propagates the
union through Drizzle inference. The query-projection types and
helper signatures use HabitFrequency directly. Default literal
`"daily"` now goes through HABIT_FREQUENCY.DAILY (SSOT). The
HabitRow cast is gone. The two remaining `as HabitFrequency` are on
HTML select `e.target.value`, which is genuinely string→union narrowing
at a system boundary and unavoidable.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 22:03:37 +02:00
g-butandClaude Opus 4.7 e9dfad9040 refactor(goals): single source of truth for the Milestone shape
The `{title, done, date?}` shape was defined three times: inline in
the schema's `.$type<>`, inline in queries' GoalWithChildren, and as
the exported Milestone type — only the third was reused. Because
they were independent declarations, GoalCard had to cast
`goal.milestones as Milestone[]` to bridge them, even though the
shapes happened to be identical.

Now the Milestone type is defined once at the top of the schema
file, the schema's `.$type<Milestone[]>()` references it directly,
and queries/goals.ts imports and uses it for GoalWithChildren. The
cast in GoalCard.tsx is gone — goal.milestones is now structurally
Milestone[] | null and assigns to useState<Milestone[]> without help.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:58:49 +02:00
g-butandClaude Opus 4.7 83a6f47701 refactor(events): one type definition for EventRow, not two
The same `events.$inferSelect` type was being defined twice — once as
`Event` in db/schema/events.ts (entirely unused, and clashes with the
DOM Event global) and once as `EventRow` in db/queries/events.ts (the
de facto public name, imported by 4 components). They computed the
same thing but neither knew about the other.

Now defined once in the schema file (renamed to `EventRow` to avoid
the DOM clash and match the established public name) and re-exported
from queries/events.ts so existing imports keep working.

`NewEvent` similarly renamed to `NewEventRow` for naming consistency
with `EventRow`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:55:46 +02:00
g-butandClaude Opus 4.7 ce0fb36b65 refactor(actions): export ActionPayload type, drop two widening casts
Two `as Record<string, unknown> | null` casts in ActionQueueCard were
actively widening the schema-defined payload type — Drizzle already
infers payload as `{to?: string, channel?: string, body?: string,
subject?: string, eventTitle?: string, ...} | null` from the schema's
`.$type<...>()` annotation, but the local ActionGroup type used the
generic Record, forcing the casts.

Extracted the payload shape as a named `ActionPayload` export from the
schema and used it in ActionGroup instead. Both casts go away, and
field accesses (`payload.to`, `payload.body`) are now properly typed
as `string | undefined` rather than `unknown` — `String(payload.to)`
is now a string→string call rather than unknown→string coercion.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:52:19 +02:00
g-butandClaude Opus 4.7 a2326c9467 chore(api): align 3 outlier zod messages with the established convention
Across ~25 .min(1, "...") schemas the convention is:
- POST: "<field> is required"
- PATCH: "<field> cannot be empty"
All lowercase field names.

Three outliers diverged: "Missing message" (ivy), "Missing id" (crons
PATCH), "Description cannot be empty" (commitments PATCH, capital D).
These messages bubble up to users via the friendlyZodMessage helper,
so the inconsistency was visible.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:47:41 +02:00
g-butandClaude Opus 4.7 10928b50c7 refactor(today): route AddCommitmentButton through useCreateMutation
Every other "New X" entry point in the app (NewPersonButton,
NewGoalButton, NewSubscriptionButton, NewProjectButton) goes through
useCreateMutation for the saving + error + decode + router.refresh
flow. AddCommitmentButton was the lone holdout, hand-rolling all four
pieces of state and the response decoding.

Now consistent with the established pattern. Net -6 lines, same
behaviour. AddEventForm and AddHabitForm intentionally don't fit —
they hand the created entity back to parent state via callback rather
than triggering a full router refresh, which is a different concern.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:42:14 +02:00
g-butandClaude Opus 4.7 884ae402ca fix(dates): route 5 inline today-as-YYYY-MM-DD sites through toLocalDateStr
The same `new Date().toISOString().split("T")[0]` pattern appeared in
five places — interaction-log defaults, project activity defaults, and
the goal target-date input — to get "today as YYYY-MM-DD". That formula
returns the *UTC* day, not the local one. For a Swiss user logging an
interaction at 01:00 CET, UTC is still on the previous day, so the
date-picker silently defaulted to yesterday.

`lib/dates.ts:toLocalDateStr` already exists for exactly this — its
docstring even calls out "toISOString is wrong here" for the habit case.
Rerouted all five sites through it.

Net: one fewer correctness foot-gun, five fewer hand-rolled formatters.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:38:14 +02:00
g-butandClaude Opus 4.7 3381326dec refactor(api): two GET handlers route through readIdParam, clients check res.ok
The GET handlers in /api/people/[id] and /api/projects/[id] were the
last two [id] routes still running their own inline isValidUuid check
instead of going through readIdParam (which every PATCH/DELETE in the
same files already used). Routed both through the helper.

Side effect: bad UUIDs now return `{error: "Invalid id"}` instead of a
null body. The two clients that consume these routes (PersonDetail,
ProjectDetail) used to rely on null-throws (`d.interactions` blowing
up on a null response) to fall through to .catch(). With a non-null
error body, that throw doesn't happen and the UI crashes at render
time. Hardened both clients to check `res.ok` before parsing — same
pattern useFetch already uses, and now resilient to whatever shape
the server returns on non-2xx.

404s still return null body (the only client paths consuming these
handlers expect "no result" → null on the wire).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:34:49 +02:00
g-butandClaude Opus 4.7 f31931e729 fix(today): cancel stale fetches in LogConversation search
Same race shape just fixed in PeopleGrid: a slow earlier response
could clobber a faster later one when the user types continuously
through the 200ms debounce window. Previous note ("wait for it to
actually misbehave") underestimated how easy this restructure is —
collapsing the useCallback + useRef + separate effect into a single
debounced effect with AbortController is fewer lines, not more.

Now consistent with PersonDetail / PeopleGrid / ProjectDetail:
all four fetch-in-effect components use cancellation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 21:30:33 +02:00