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>
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>
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>
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>
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>
`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>
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>
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>
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>
/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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
Two real race conditions in the People view, both with the same shape:
a fetch can resolve after a newer one has already started, and there
was no guard to stop the older response from clobbering the newer
state. ProjectDetail already had the cancel pattern; these didn't.
- PersonDetail: clicking person A then quickly person B could leave
A's data on screen if A's response landed after B's. Now uses the
same cancelled-flag cleanup as ProjectDetail.
- PeopleGrid: typing "ali" then "alic" then "alice" with a slow API
could show results for "ali" if its response landed last. The
search effect now creates an AbortController and aborts in
cleanup; the search callback bails on abort and on AbortError.
Both are bugs only on slow/jittery connections, but the fixes are
small and the cancel pattern is already the established convention
elsewhere in the codebase.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The route.ts POST/PATCH handlers had their own `readJobsFile()` that
duplicated the read-and-parse logic from `lib/crons.ts:readCronJobs()`,
plus a different return shape (full file vs. just jobs) and crucially
different error handling: the route version had no try/catch, so a
malformed cron file would 500. Worse, since the route then writes
back, a try/catch returning [] would have silently overwritten the
existing jobs with an empty file.
Consolidated both read paths in lib/crons.ts:
- `readCronFile(): CronFileData` — full shape, throws on parse error
(the write-path needs to know if the file is bad before clobbering it)
- `readCronJobs(): CronJob[]` — read-only convenience for display code,
swallows errors and returns []
The route.ts POST/PATCH now use readCronFile() directly. The 500
response on parse failure is appropriate for a write — refusing to
write rather than destroying data is the safe default.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two leftover spots compared values against raw string literals while
the file already imported the canonical constant elsewhere:
- ActionButtons.tsx: useState typed as "approved" | "rejected" — now
derives from typeof ACTION_STATUS.APPROVED | typeof ACTION_STATUS.REJECTED
so a future rename of those values flows through automatically.
- ProjectOverviewTab.tsx: relation filters used "person" — now use
ENTITY_TYPE.PERSON, matching the convention everywhere else.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two display-style maps had keys that the canonical enums already define,
but were typed Record<string,string>. That meant TS could not catch a
missing key when the underlying enum gained a new member — the runtime
fallback would just silently stand in.
- src/app/money/page.tsx: STATUS_STYLE now Record<SubStatus,string>
with computed SUB_STATUS keys; the literal "active" fallback also
routes through SUB_STATUS.ACTIVE.
- src/app/memory/page.tsx: TYPE_COLOR now Record<EntityType,string>
(the existing comment claimed enum-coverage enforcement but the
string-keyed type didn't actually enforce it).
Net: slightly stricter compile-time safety with no runtime change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The map was {daily→"daily", weekdays→"weekdays", weekly→"weekly"} —
key always equals value, so FREQ_LABELS[x] is just x. Three identical
copies (AddHabitForm, HabitRow, habits/page) added zero value over
rendering the frequency string directly.
Per CLAUDE.md ("Premature abstraction is worse than duplication"):
when the abstraction is identity, deletion beats centralization. If
display ever needs to diverge from the persisted value (capitalization,
localization), reintroduce a single shared map at that point.
Net: -23 / +4 lines.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
AskIvyModal had two `eslint-disable-next-line @typescript-eslint/no-
explicit-any` directives plus a `type AnySpeechRecognition = any`
alias because the Web Speech API isn't in lib.dom.d.ts (the spec is
non-standard and vendor-prefixed). The escape hatch worked, but
losing types meant call sites couldn't catch typos in property names.
Declare just the surface we touch — SpeechRecognitionInstance with
the four lifecycle callbacks and start/stop, plus a SpeechResultEvent
shape that matches what `recognition.onresult` actually receives.
Wraps the window-globals dance in a getSpeechRecognitionCtor helper
that uses a typed window cast (no eslint-disable needed) and returns
either the constructor or undefined.
After this, the codebase has zero `any` and zero eslint-disable
directives — the types match the runtime exactly.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Next's default 404 ("This page could not be found") renders inside
the app's dark layout, but as bare unstyled text — visually off from
the rest of the UI and useless as a recovery surface.
Add src/app/not-found.tsx that matches the error.tsx layout (centred
column, large lucide icon, dim labels) and gives the user a clear
link back to /today instead of dead-ending.
Verified: tsc + eslint clean, smoke 18/18, /this-route-does-not-exist
now renders the custom page.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The /memory page hardcoded entity-type strings ("person", "project",
"goal", etc.) as TYPE_COLOR keys, duplicating the ENTITY_TYPE enum in
lib/constants/statuses.ts. Adding a new entity type would silently fall
back to the unknown-colour styling here even after the canonical enum
was updated.
Source the keys from ENTITY_TYPE so the two stay in sync at compile
time. No visual or behaviour change — same map, just typed-derived.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Continues the migration started in 2fd2583. Every remaining route that
read req.json() now validates the body through readJsonBody() with a
colocated zod schema. Removes 10+ ad-hoc `if (!body.x?.trim())` checks
plus several `body as { x?: string }` casts.
Routes migrated:
- /api/people POST + [id] PATCH
- /api/projects POST + [id] PATCH
- /api/goals POST + [id] PATCH
- /api/habits POST + [id] PATCH
- /api/subscriptions POST + [id] PATCH
- /api/commitments POST + [id] PATCH
- /api/events [id] PATCH
- /api/people/[id]/interactions POST
- /api/projects/[id]/interactions POST
- /api/people/[id]/attrs POST + DELETE
- /api/projects/[id]/attrs POST + DELETE
- /api/crons POST + PATCH
- /api/crons/run POST
- /api/ivy POST
PATCH schemas use .refine to enforce "at least one field changed"
where the old hand-rolled code had `if (Object.keys(patch).length === 0)`.
Enums (status/currency/frequency) now reject unknown values at the
boundary instead of trusting the cast.
Verified: tsc clean, eslint clean, prod build passes, smoke 18/18.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
zod has been a phantom dependency (in package.json, used in 0 files).
Every POST/PATCH route hand-rolled `if (!body.name?.trim()) return 400`
checks instead of validating at the boundary, contrary to CLAUDE.md's
"Validate inputs at system boundaries" rule.
Add a readJsonBody<T>(req, schema) helper in lib/api/route-helpers.ts
that mirrors the readIdParam shape — returns parsed+typed data or a
400 NextResponse the caller passes through. Includes a friendlyZodMessage
translation so zod's default "Invalid input: expected string, received
undefined" for missing fields becomes "<field> is required".
Migrate /api/events POST as the first user. Schema is colocated with
the handler. Other routes follow the same pattern in subsequent commits.
Note: dev-server HMR can be sticky for route-helper imports — the
prod build picks the new helper up correctly. Verified with tsc 0
and prod build succeeded; smoke 18/18.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two cleanups in /memory:
1) The compact "5d ago / 2w ago / 3mo ago" relativeDate helper sat in
memory/page.tsx as a private function — but it's a date helper, not
a memory concern, and lib/dates.ts already groups toLocalDateStr
and deadlineLabel. Move it there as compactRelativeDate. Lib is now
the single home for date-derived display strings.
2) The two empty-state placeholders in /memory ("Nothing added yet",
"No interactions logged yet") were the only EmptyState shape that
wasn't routed through the primitive yet — they used <p> instead of
<div> but otherwise matched. Sweep them.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Six exact copies of <div className="text-sm text-white/30">No …</div>
sat in PersonChannelsSection, PersonInteractionsSection, PersonDetailAttrs,
GitHubStatus, CalendarCard, and HabitsList. Centralise as
components/ui/empty-state.tsx:EmptyState — caller passes the copy as
children, the styling lives in one place.
A future tweak to dim-text styling (or wrapping it in an icon, or
giving it spacing) lands in one file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two follow-on cleanups now that the form/fetch primitives are in place:
1) PRIMARY_BUTTON_CLASS — the modal-form submit button had 6 EXACT
identical copies of the same 80-character className across the four
New*Button components plus RunModal and ScheduleModal. Pull the
constant into ui/form.tsx alongside FIELD_INPUT_CLASS and source it
from each call site.
2) Five raw `fetch(url, { method: "DELETE" })` calls (in PersonDetail,
ProjectDetailHeader, DeleteCommitmentButton, SubscriptionActions x2)
slipped past the postJson/patchJson sweep because they have no
body. Route them through deleteJson() too — same SSOT.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The "Content-Type": "application/json" header literal was hand-coded
26 times across 18 files — every component that called a write
endpoint had its own copy of `{ method, headers, body: JSON.stringify(...) }`.
Three lib/api wrapper files (attrs, crons, goals) also each had their
own private JSON_HEADERS const.
Centralise as src/lib/api/fetch.ts:postJson / patchJson / deleteJson.
Each call site shrinks from ~5 lines to 1.
Sweep:
- 18 components: PersonDetail, PersonCard, PersonInteractionsSection,
NewPersonButton, AddEventForm, EventCard, AddCommitmentButton,
CommitmentItem, LogConversationButton, HabitsList, AskIvyModal,
RunModal, JobDetail, ProjectDetailHeader, ProjectOverviewTab,
NewProjectButton, NewSubscriptionButton, SubscriptionActions
- 3 lib/api wrappers: attrs.ts, crons.ts, goals.ts (drop their
private JSON_HEADERS)
Net: -82 lines.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
RunModal's project picker and ScheduleModal's project picker + cron
input matched the existing FIELD_INPUT_CLASS pattern bar a missing
placeholder/transition rule (no-op on selects). Source from the
constant — including the cron input which appends `font-mono`.
Leaves 8 truly one-off variants (search bars with pl-9, rounded-xl
prefix, text-right cells, w-12 progress %); extracting constants for
1-occurrence patterns would be over-engineering.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add the px-2 py-1 sibling to FIELD_INPUT_CLASS_COMPACT for the tightest
inline-edit slots (per-row edit forms, attribute editors, badge inputs).
The tight pattern was hand-coded 26 times across 11 files with three
flavours of accidental drift:
text-white/70 vs /80 — pure copy-paste accident
placeholder:/20 vs /25 — same
with/without resize-none, etc. — caller-specific, kept as suffix
Standardise on text-white/80 + placeholder /20 (the dominant variant).
Visual delta is imperceptible.
Sweep AddHabitForm, PersonInteractionsSection, PersonChannelsSection,
PersonDetailAttrs, PersonCard, CommitmentItem, LogConversationButton,
goal-card-helpers, GoalCard, ProjectOverviewTab, SubscriptionActions —
each now reads `${FIELD_INPUT_CLASS_TIGHT}` plus its width/extras.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Every /api/.../[id]/route.ts handler started with the same three lines:
const { id } = await params;
if (!isValidUuid(id)) return NextResponse.json({ error: ... }, { status: 400 });
23 occurrences across 12 files, with drift between "Invalid id" /
"Invalid ID" / `null` payloads.
Centralise as src/lib/api/route-helpers.ts:readIdParam(params), which
returns the validated id or a 400 NextResponse the caller returns
as-is. Migrate 20 of the 23 sites; three outliers stay hand-coded:
- people/[id] GET and projects/[id] GET return `null` body for 4xx
(consumer contract — `.then(d => setData(d))` relies on null)
- crons/run is a body-field check, not a route param
Capitalisation drift ("Invalid ID" → "Invalid id") collapses to one
canonical spelling. Also: ignore .claude/ session-state files.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The "channel:" string was hand-coded in four people-component sites:
PersonCard's channel filter, PersonChannelsSection's filter / strip /
key-build, and PersonDetailAttrs' "exclude channels" filter. Plus
config/channels.ts stripped the prefix once for CHANNEL_NAMES.
Pull all of that into config/channels.ts:
- CHANNEL_ATTR_PREFIX = "channel:" — the single literal
- isChannelAttrKey(key) — for filters
- stripChannelPrefix(key) — for display ("channel:whatsapp" → "whatsapp")
- withChannelPrefix(name) — for building keys ("whatsapp" → "channel:whatsapp")
- CHANNEL_NAMES now derives via stripChannelPrefix
Sweep the four call sites. Renaming the prefix is now a one-line edit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The /today summary cards each had a "lookahead in days" number that
appeared in three places: the query default, the call-site override,
and the user-visible label. Worse, the defaults disagreed with the
callers (subscriptions defaulted to 7 but every caller passed 14;
events defaulted to 14 but the only caller passed 30) — so the
"defaults" were silent lies.
Introduce three constants in lib/constants.ts:
- GOALS_DUE_SOON_DAYS = 14
- EVENTS_DUE_SOON_DAYS = 30
- SUBSCRIPTIONS_UPCOMING_DAYS = 14
Sweep them through:
- db/queries/today.ts: query defaults + the two inline windows in
getTodaySummary (incl. the ugly `(() => { const d=...; })()` IIFE)
- db/queries/events.ts: getEventsDueSoon default
- components/today/{Goals,Events,Subscriptions}Card: drop the
literal 14 / 30 args and source the label number from the constant
Tweaking a window now lands in one file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ProjectGrid and ProjectDetailHeader each hand-resolved the same two
attrs (production_url/url, repo/github_repo) and applied the same
"bare host → https://, bare slug → https://github.com/" prefixing.
Two extra subtleties made it worse:
- ProjectDetailHeader looked up via `attrs[LINK_ATTRS[0]]` etc., a
fragile array-index pattern that breaks if LINK_ATTRS is reordered.
- The startsWith("http") prefix dance was duplicated four times.
Move both into project-detail-types.ts:getProjectLinks(attrs), which
returns ready-to-use { prodUrl, repo } href strings (or null). Both
call sites now read like {prodUrl} && <a href={prodUrl}>.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
HabitsList (266L) tangled three concerns: per-row toggle/edit/remove,
the new-habit form, and orchestration. Splitting:
- HabitRow.tsx (143L): per-row display + check-off + inline title/
frequency edit (via useInlineEdit) + remove. Owns its own toggling
spinner so edits and toggles can't collide.
- AddHabitForm.tsx (94L): the open/close + form for adding a habit;
takes an emptyState prop for the first-habit CTA.
- HabitsList.tsx (100L): thin orchestrator — owns the optimistic-
update logic, wires onToggle/onEdit/onRemove/onCreated.
Net result: one large file became three single-responsibility files,
the per-row inline edit now uses the shared useInlineEdit lifecycle,
and the file count above 250L drops by one.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The same getFullYear / padStart / getMonth+1 / padStart / getDate
template appeared six times — once in HabitHeatmap.lastNDates and
five times in db/queries/habits.ts (todayDate helper, two streak
windows, two getAllHabitsWithHistory loops).
Centralize as src/lib/dates.ts:toLocalDateStr(date). Habit tracking
relies on the local calendar day (not UTC), so the helper documents
that contract and keeps the formatting consistent in one place.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The habit history window appeared as the literal 30 in five places —
the page query call, the page subtitle, two stat copy strings, the
percent calc, the per-row "/30d" label, the HabitHeatmap DAYS const,
and the query default — meaning a tweak to e.g. 60 needed five edits.
Pull HABIT_HISTORY_DAYS into lib/constants.ts and source from there:
- app/habits/page.tsx (query, subtitle, stat label, pct calc, badge)
- components/habits/HabitHeatmap.tsx (heatmap cell count)
- db/queries/habits.ts (default arg)
While in habits/page.tsx, drop the redundant `=== 0 ? 0 :` ternary in
the percent calc — Math.round((0 / N) * 100) already returns 0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Four components hand-rolled the same `${overdue ? "Overdue" : "Due"}
${formatDistanceToNow(d, { addSuffix: true })}` string plus an `isPast`
check: EventCard, goal-card-helpers' DateInput, GoalsDueCard,
EventsDueCard.
Centralize as src/lib/dates.ts:deadlineLabel(date), returning
{ label, overdue }. Each call site now does one destructuring and
keeps its own wrapping element / colour scheme. Future copy tweaks
(e.g., "Past due" vs "Overdue", or localization) land in one file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Add the compact-form sibling to FIELD_INPUT_CLASS for inline-edit /
tight-row inputs (px-2.5 py-1.5 text-xs). Sweep the 12 exact matches
across AddEventForm, AddCommitmentButton, ProjectPromptsTab, and
PersonCard.
Width modifiers (w-full / flex-1) and extras like font-mono are
appended at the call site via template-literal concatenation. The base
visuals are now SSOT — a tweak to the compact input look lands in one
file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Two more inline editors in goal-card-helpers.tsx still hand-rolled the
editing/draft/saving state machine. Switch them to the shared
useInlineEdit hook from the previous commit.
Behavior preserved, including the special "click X to clear deadline"
path which now goes through ie.commit() outside of edit mode (saving
spinner still flashes thanks to the hook's lifecycle).
goal-card-helpers.tsx: 270 → 259 lines.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>