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>
The previous README implied `npx tsx scripts/seed.ts` was a
self-contained step. It isn't — the script reads from
~/.openclaw/knowledge.sqlite and ~/.openclaw/workspace/data/
contact-resolver.json, which are George's personal artefacts that
live outside the repo and aren't checked in.
A fresh clone hitting that command would ENOENT.
Update Setup so the contract is honest: schema push works for anyone,
seed works only if you bring those files yourself, and an empty
database is a fully-supported state because every page renders an
empty-state when the underlying table is empty (we wired up the
EmptyState primitive earlier exactly for this).
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>
Status-only smoke missed a real failure mode: when a Server Component
throws, Next.js renders src/app/error.tsx ("Something went wrong")
INSIDE a 200 response. The page is broken from the user's perspective,
but smoke would mark it ok.
Refactor into a check_route helper that pages call with body-content
checking enabled. Greps the response body for the error-boundary
marker; failing-when-found means the run page doubles as a sanity
check on every server component, not just the route resolver.
API routes skip the body check (the marker is HTML-only and an API
that returned the literal string would be unusual).
Verified: all 18 routes still pass; the grep would catch a fake
error response if one were served.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The README was still create-next-app's default ("This is a Next.js
project bootstrapped with create-next-app... edit app/page.tsx") even
though the codebase has grown into a 10-route life OS with custom
infrastructure, an Ivy AI integration, scheduled crons, and so on.
Misleading for anyone who lands on the GitHub repo.
Replace with a concrete description: stack, views table (mirroring
CLAUDE.md), architecture sketch, setup, dev commands, and a pointer
to CLAUDE.md as the deeper contract for substantive changes.
CLAUDE.md remains the canonical reference for working in the repo;
README is the human-facing one-pager that says what this thing is.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds .github/workflows/audit.yml — runs `npm audit --audit-level=high`
every day at 07:13 UTC plus on-demand via the Actions tab. Fails when
a HIGH or CRITICAL severity vulnerability enters the dep graph.
The off-the-hour minute (13 vs 0) spreads fleet load. Moderate vulns
are intentionally not the trigger — the chronic transitive-noise from
esbuild-via-drizzle-kit and postcss-via-next would flap the workflow
constantly without giving us actionable signal.
A failing run is the cue to either run `npm audit fix` (if non-breaking)
or evaluate the breaking-fix path. Verified: workflow YAML parses,
`npm audit --audit-level=high` currently exits 0 since b53421d patched
the Next.js DoS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Patch-level bump within the 16.x line. npm flagged it as outside the
stated dep range only because package.json pinned exactly "16.2.2";
relaxing to "16.2.4" lets the security patch land without --force.
Fixes the high-severity advisory:
next Denial of Service with Server Components
GHSA-q4gf-8mx6-v5v3
Vulnerability count: 6 (5 moderate, 1 high) → 6 (all moderate).
The remaining moderates are transitive (esbuild via @esbuild-kit
inside drizzle-kit, postcss-via-next on a different branch) and need
larger major-version bumps that aren't safe to do automatically.
Bumps eslint-config-next in lockstep (same 16.2.2 → 16.2.4) since
they're released together and stay version-synced.
Verified: tsc clean, eslint clean, smoke 18/18.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Non-breaking semver-range updates to three transitive deps that had
moderate-severity advisories. All transitive — no direct package.json
change needed.
@hono/node-server 1.19.12 → 1.19.14 GHSA-92pp-h63x-v22m
hono 4.12.10 → 4.12.15 (multiple GHSAs in chain)
postcss 8.5.8 → 8.5.10 GHSA-qx2v-qp2m-jg93
Vulnerability count drops from 8 → 6. The remaining 6 (5 moderate, 1
high — Next.js DoS via Server Components, GHSA-q4gf-8mx6-v5v3) need
`npm audit fix --force` which is a breaking dep upgrade (next major)
and warrants the user's call before shipping.
Verified: tsc clean, eslint clean, prod build passes, smoke 18/18.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The first run of cca3113 failed because /events (and likely every other
DB-backed page) does its DB query during Next's static pre-render,
hitting the stub DATABASE_URL with ECONNREFUSED.
Two options to fix:
A) Mark every DB-backed page `export const dynamic = "force-dynamic"`.
Real fix, but it's a prod-behavior change (every request re-fetches
instead of serving cached HTML).
B) Drop `next build` from CI and rely on Vercel's deploy build —
which has a real DB attached — to catch build issues.
Going with B. Pre-commit + CI now gate type/lint (cheap, fast,
DB-independent); Vercel gates build (slow, DB-aware). Layered checks,
each at the right place.
If the DB-time-of-render coupling becomes a problem later — e.g. a
contributor breaks the build but Vercel doesn't deploy that branch —
revisit and add postgres-service + drizzle-push to the workflow.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Pre-commit (bceacc8) catches local commits, but anything pushed with
--no-verify or arriving via a PR from a fork bypasses it. Add a
GitHub Actions workflow that runs the same checks on origin (push to
main and every PR) plus a `next build` to catch issues that only
surface during compilation.
- Node 22 with npm cache (subsequent runs reuse node_modules)
- Concurrency: cancels in-progress runs on the same ref so quick
commit chains don't waste minutes
- DATABASE_URL is set to a syntactically-valid stub so src/db/index.ts
doesn't throw at module-load; postgres-js pools lazily, no real
connection happens during build
Belt-and-suspenders with the husky hook and Vercel's own build —
covers the case where Vercel is down or the PR author skipped local
hooks.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Adds husky as a dev dep and wires .husky/pre-commit to run:
npx tsc --noEmit
npx eslint src/
Both must pass for the commit to land. Smoke is intentionally NOT in
the hook because it needs a live dev server — run `npm run smoke`
manually before opening a PR.
Catches the regressions a 100-commit refactor sweep can introduce
(broken zod schema, missed import, accidentally-disabled rule)
before they reach origin/main, complementing the human / cron /
agent commit flow we've established.
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>
Static-list smoke caught compile + db breakage but missed regressions
specific to [id] route handlers — readIdParam errors, per-row drizzle
queries, the parameter-handling lifecycle, etc.
Discover the first person id from /api/people (already smoked), then
GET /api/people/<id> and assert 2xx/3xx. Skipped silently if jq isn't
installed or the list is empty, so the script stays portable.
Other dynamic GETs (/api/projects/<id>) aren't smoked because no list
endpoint exists to derive an id without an extra DB roundtrip.
18 routes total now pass.
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>
Page-only smoke caught compile-time route breakage but missed
server-side regressions: a broken Drizzle query would render every
page as "Error" yet still return 200. Add the DB-backed API GETs:
/api/goals, /api/habits, /api/people, /api/events, /api/crons,
/api/system
Tool-dependent endpoints (/api/calendar, /api/weather, /api/github)
stay out of the default run because they need the local Ivy gateway
and would flake on machines that don't have it.
Verified: all 17 routes (11 pages + 6 APIs) return 200 against the
running dev server.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Until now the codebase had zero automated coverage; every refactor
relied on a manual curl loop. scripts/smoke.sh runs that loop in one
command: probe BASE/, then GET every page route and assert 2xx/3xx.
- Routes match config/navigation.ts NAV_ITEMS plus the / redirect
- BASE env var override for prod smoke (defaults to localhost:3000)
- Fast-fails with a clear "start the dev server first" message if
the base is unreachable, instead of dribbling 11 curl errors
- No new dependencies — bash + curl only
Verified: all 11 routes return 200 against the running dev server.
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>
Audit caught documentation drift:
- Views table listed 7 routes; the codebase ships 10. Add Habits,
Events, Prompts and refresh the Status column for the routes whose
capabilities have grown (inline editors, daily habit check-off,
archive flow, etc.).
- Architecture tree missed components/{events,habits,goals,money,
prompts,system}, the projects subdir's split, and the new hooks
beyond useFetch (useCreateMutation, useInlineEdit). Updated.
- SSOT Rules block didn't list the new shared primitives or helpers
worth knowing — Modal/Drawer, Field/FIELD_INPUT_CLASS{,_COMPACT},
HABIT_HISTORY_DAYS, useInlineEdit, useCreateMutation, lib/dates.ts.
CLAUDE.md is the project-root contract for future sessions and
contributors; keeping it in sync is a real user-impact fix.
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>
Six inline-edit toggles across two files all hand-rolled the same
state machine: editing/draft/saving + start/cancel/setSaving wrap.
Pull that into hooks/use-inline-edit.ts.
Migrated:
- ProjectInlineEditors.tsx: NameEditor, DescriptionEditor, StatusEditor,
MaturityEditor (4 editors, 221 → 200 lines)
- PersonDetail.tsx: name and description toggles (-30 lines of plumbing)
Each call site keeps its own validation/equality/transform — the hook
only owns the lifecycle. Net: -32 lines across the two files, and
adding a new inline editor anywhere is now ~3 calls of useInlineEdit.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Every "New X" form repeated the same label-wrapping div and an 80-char
Tailwind className for inputs/selects/textareas — 15 call sites with
the exact same string. Pull that into components/ui/form.tsx:
- FIELD_INPUT_CLASS: shared className constant
- <Field label required>: label + child wrapper
The four migrated forms (Person, Project, Goal, Subscription) now read
as the form, not the form-styling. A future global tweak to input
visuals lands in one place.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The four "New X" buttons (Person, Project, Goal, Subscription) all
hand-rolled the same flow: setSaving(true), POST, decode { ok, error },
router.refresh(), surface a fallback "Failed to create <thing>". Pull
that into hooks/use-create-mutation.ts.
Each consumer now declares only its body type, the request fn (or a
typed lib helper like createGoal), and an errorLabel. The reset-fields
+ close logic stays per-component since the field shape varies.
Net: -20 lines across the four call sites, and adding a fifth "New X"
button is now a one-page implementation.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PromptRow and FeaturedCard each repeated the same showRun/showSchedule
useState pair plus the conditional <RunModal>/<ScheduleModal> renders.
Extract usePromptModals(template, projects) returning openRun,
openSchedule, and a modals JSX node. Both call sites now have one line
of state setup and one {modals} render — adding a third modal type
later means changing one file.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
When a child (e.g. an inline attribute editor) calls onReload(),
loading was no longer flashing because the loading derivation
(data?.id !== projectId) stays false during a same-projectId refetch.
That left the user with no feedback that the save updated the
displayed source-of-truth.
Add a separate `refetching` state set during every fetch and a small
animated Loader2 anchored to the drawer's top-right while refetching
with stale data on screen. The full-page loader still triggers on the
initial-load case (no data yet).
The setRefetching(true) call is wrapped in Promise.resolve().then() to
defer it off the synchronous effect path, satisfying
react-hooks/set-state-in-effect.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ProjectDetailHeader.tsx (323 lines) tangled four inline-editing widgets
(name, description, status pill, maturity slider) with a tab bar and
the action toolbar in a single component. Splitting:
- ProjectInlineEditors.tsx (221L): Name/Description/Status/Maturity
editors as named exports. Each owns its editing/draft/saving state
and exposes a single onSave(next) callback. Container keeps the
optimistic-override state so the UI updates immediately on commit.
- ProjectDetailTabBar.tsx (50L): tab strip with overview/prompts/goals
badges.
- ProjectDetailHeader.tsx (156L): orchestration — resolves displayed
values from data + overrides, wires the four save handlers, and
composes the editors with the action toolbar and tab bar.
No behavior change. All three files are now under 300 lines with a
single concern.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
PromptLibraryClient.tsx (359 lines) housed four concerns: a compact
list row, a featured card, a category filter bar, and the search/scope
container. Splitting:
- PromptRow.tsx (89L): compact row with run/schedule/preview actions
- FeaturedCard.tsx (61L): larger card for the Quick Access grid
- CategoryBar.tsx (52L): "All (n)" + per-category filter chips
- PromptLibraryClient.tsx (148L): search, scope filter, and orchestration
Each file is now under the 300-line god-component threshold and owns a
single concern. ALL_CATEGORIES moved to CategoryBar and re-exported.
No behavior change.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
EventsGrid.tsx (371 lines) housed three concerns: an event card, an
inline create-event form, and the search/filter container. Splitting:
- EventCard.tsx (97L): presentation + delete + archive for one event
- AddEventForm.tsx (124L): self-contained inline create form
- EventsGrid.tsx (153L): search, type-chip filter, and list orchestration
Each file is now well under the 300-line god-component threshold and has
one job. No behavior change — purely a structural refactor.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
CLAUDE.md is explicit: 'Use shadcn theme tokens — never hardcode hex'.
The modal/drawer surface colors #0f1117 and #0c0e14 were duplicated
across 10 files, violating SSOT.
- globals.css: add --surface-modal / --surface-drawer custom properties
in :root and .dark, register as Tailwind colors via @theme inline
- 10 components: bg-[#0f1117] → bg-surface-modal,
bg-[#0c0e14] → bg-surface-drawer
A future palette tweak now changes 1 file, not 10.
Verified bg-surface-{modal,drawer} classes are present in the prod CSS.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ESLint went from 6 errors / 17 warnings to 0/0:
react-hooks/set-state-in-effect (3 sites)
- ProjectDetail: derive loading from data?.id !== projectId, replace
reload() helper with a reloadKey trigger so the effect owns the fetch
- AskIvyModal speech recognition: defer setSupported via queueMicrotask
- AskIvyModal useElapsedTimer: defer setElapsed(0) reset via queueMicrotask
react-hooks/static-components (1 site)
- WeatherCard: extract WeatherIcon as a module-level component instead
of assigning a Lucide icon to a render-scope variable
react/no-unescaped-entities (2 sites)
- ProjectGrid: replace bare quotes around {query} with “/”
Plus: removed 14 unused imports/vars across 10 files.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>