Commit Graph
1545 Commits
Author SHA1 Message Date
g-butandClaude Opus 4.7 6286cdf031 fix(people): cancel stale in-flight fetches to stop out-of-order races
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>
2026-04-26 21:28:03 +02:00
g-butandClaude Opus 4.7 950944e766 refactor(crons): centralize cron-file I/O, fix subtle write-path foot-gun
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>
2026-04-26 21:23:41 +02:00
g-butandClaude Opus 4.7 a0ba2ffef8 refactor(ssot): replace remaining hardcoded status/entity literals
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>
2026-04-26 21:19:51 +02:00
g-butandClaude Opus 4.7 7826eeb1f5 refactor(ssot): tighten Record<string,…> style maps to their enum types
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>
2026-04-26 21:16:31 +02:00
g-butandClaude Opus 4.7 67be21582e refactor(habits): drop FREQ_LABELS identity maps duplicated across 3 sites
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>
2026-04-26 21:12:35 +02:00
g-butandClaude Opus 4.7 78fb60701b refactor(shell): type the SpeechRecognition surface, drop both any escapes
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>
2026-04-26 21:01:42 +02:00
g-butandClaude Opus 4.7 d2b0cc5710 docs(readme): be honest about the seed dataset's external dependencies
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>
2026-04-26 20:58:53 +02:00
g-butandClaude Opus 4.7 d1eba178be feat(ui): custom 404 page in cockpit's design language
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>
2026-04-26 20:56:24 +02:00
g-butandClaude Opus 4.7 2df42d77e3 chore(smoke): also fail when error.tsx boundary renders inside a 200
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>
2026-04-26 20:53:04 +02:00
g-butandClaude Opus 4.7 40535dca58 docs(readme): replace boilerplate with actual project description
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>
2026-04-26 20:49:40 +02:00
g-butandClaude Opus 4.7 ac800a161c chore(ci): daily Audit workflow surfaces new CVEs as they land
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>
2026-04-26 20:45:44 +02:00
g-butandClaude Opus 4.7 b53421dfb5 chore(deps): bump next 16.2.2 → 16.2.4 (high-severity DoS CVE)
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>
2026-04-26 20:42:42 +02:00
g-butandClaude Opus 4.7 851b6b8509 chore(deps): npm audit fix — patches @hono, hono, postcss CVEs
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>
2026-04-26 11:52:45 +02:00
g-butandClaude Opus 4.7 aa75af712f fix(ci): drop the build step — needs a live DB the workflow can't have
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>
2026-04-26 11:44:26 +02:00
g-butandClaude Opus 4.7 cca31135c7 chore(ci): add GitHub Actions workflow running tsc + eslint + build
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>
2026-04-26 11:40:45 +02:00
g-butandClaude Opus 4.7 bceacc8222 chore(husky): add pre-commit hook running tsc + eslint
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>
2026-04-26 11:35:54 +02:00
g-butandClaude Opus 4.7 3b11b5ec92 refactor(memory): TYPE_COLOR keys derive from ENTITY_TYPE constant
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>
2026-04-26 11:30:43 +02:00
g-butandClaude Opus 4.7 cb76d73aa2 feat(api): wire zod validation across the remaining 19 POST/PATCH routes
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>
2026-04-26 11:26:41 +02:00
g-butandClaude Opus 4.7 2fd258339a feat(api): wire zod input validation, migrate /api/events POST as pattern
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>
2026-04-26 11:09:42 +02:00
g-butandClaude Opus 4.7 8d22c160e4 chore(smoke): add dynamic /api/people/<id> coverage via id discovery
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>
2026-04-26 10:43:11 +02:00
g-butandClaude Opus 4.7 4723fba12e refactor(memory): hoist relativeDate to lib/dates, finish EmptyState sweep
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>
2026-04-26 10:40:22 +02:00
g-butandClaude Opus 4.7 b1e93d1adc refactor(ui): extract EmptyState, sweep 6 dim "No X yet" placeholders
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>
2026-04-26 10:33:36 +02:00
g-butandClaude Opus 4.7 c86bfecb1f refactor(ui): extract PRIMARY_BUTTON_CLASS, sweep raw DELETE fetches
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>
2026-04-26 10:26:10 +02:00
g-butandClaude Opus 4.7 100dbddbf6 refactor(lib): extract postJson/patchJson/deleteJson, sweep 22 sites
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>
2026-04-26 10:15:32 +02:00
g-butandClaude Opus 4.7 4128a4bb3d refactor(prompts): route 2 modal-form selects through FIELD_INPUT_CLASS
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>
2026-04-26 09:52:12 +02:00
g-butandClaude Opus 4.7 1419508fe9 refactor(ui): add FIELD_INPUT_CLASS_TIGHT, sweep 26 inline-edit sites
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>
2026-04-26 09:47:02 +02:00
g-butandClaude Opus 4.7 52a0e7aef1 refactor(api): extract readIdParam, drop 20× UUID-validation boilerplate
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>
2026-04-26 09:30:27 +02:00
g-butandClaude Opus 4.7 dac304fd47 refactor(channels): centralize the "channel:" attr prefix + helpers
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>
2026-04-26 09:14:12 +02:00
g-butandClaude Opus 4.7 5dc2e52933 refactor(today): centralize the 14/30/14 due-soon windows as constants
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>
2026-04-25 18:48:46 +02:00
g-butandClaude Opus 4.7 b79217f94c refactor(projects): extract getProjectLinks, drop URL-prefix duplication
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>
2026-04-25 18:39:07 +02:00
g-butandClaude Opus 4.7 b2cbe5adb7 chore(scripts): smoke also hits the 6 DB-backed GET API endpoints
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>
2026-04-25 18:32:46 +02:00
g-butandClaude Opus 4.7 b9aa7e657c chore(scripts): add npm run smoke — route-level regression check
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>
2026-04-25 18:30:20 +02:00
g-butandClaude Opus 4.7 ad8dfef9fd refactor(habits): split HabitsList into HabitRow + AddHabitForm
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>
2026-04-25 18:26:13 +02:00
g-butandClaude Opus 4.7 6384f60847 docs(claude): bring CLAUDE.md back in sync with the shipped codebase
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>
2026-04-25 18:18:10 +02:00
g-butandClaude Opus 4.7 bea553f539 refactor(lib): extract toLocalDateStr, sweep 6 hand-rolled formatters
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>
2026-04-25 18:09:27 +02:00
g-butandClaude Opus 4.7 95fcf860f7 refactor(habits): centralize the 30-day window via HABIT_HISTORY_DAYS
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>
2026-04-25 18:03:07 +02:00
g-butandClaude Opus 4.7 2cb677002c refactor(lib): extract deadlineLabel, sweep 4 deadline-text sites
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>
2026-04-25 17:57:45 +02:00
g-butandClaude Opus 4.7 7488503570 refactor(ui): add FIELD_INPUT_CLASS_COMPACT, sweep 12 inline-form sites
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>
2026-04-25 17:48:48 +02:00
g-butandClaude Opus 4.7 92cb1ccb75 refactor(goals): migrate ProgressInput + DateInput to useInlineEdit
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>
2026-04-25 17:38:42 +02:00
g-butandClaude Opus 4.7 41fa885ce6 refactor(hooks): extract useInlineEdit, collapse 6 inline editors
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>
2026-04-25 17:31:37 +02:00
g-butandClaude Opus 4.7 941c5a8b80 refactor(ui): extract Field + FIELD_INPUT_CLASS, sweep New*Button forms
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>
2026-04-25 17:24:49 +02:00
g-butandClaude Opus 4.7 f78be4de0f refactor(hooks): extract useCreateMutation, drop the four-fold copy
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>
2026-04-25 17:19:14 +02:00
g-butandClaude Opus 4.7 21b61cff64 refactor(prompts): collapse Run/Schedule modal wiring into hook
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>
2026-04-25 17:11:24 +02:00
g-butandClaude Opus 4.7 e74b857466 fix(projects): show subtle refresh indicator on in-place reload
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>
2026-04-25 17:07:08 +02:00
g-butandClaude Opus 4.7 f14e162bad refactor(projects): split ProjectDetailHeader into focused components
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>
2026-04-25 17:02:52 +02:00
g-butandClaude Opus 4.7 3cf944bff6 refactor(prompts): split PromptLibraryClient into focused components
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>
2026-04-25 16:59:05 +02:00
g-butandClaude Opus 4.7 ab34ad8aaa refactor(events): split EventsGrid into single-responsibility files
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>
2026-04-25 16:55:47 +02:00
g-butandClaude Opus 4.7 6b7b34c60f refactor(ui): extract Modal/Drawer primitives, migrate 10 sites
Eliminates the duplicated 'fixed inset-0 z-50 + backdrop + Esc handler'
boilerplate that was repeated across 10 components. Modal and Drawer
now own:
- backdrop element + click-to-close
- window keydown Esc handler
- panel surface, border, sizing, shadow

Modal: centered with a 'bottom-mobile' position option (covers AskIvy's
bottom-anchored sheet on small screens). Accepts size sm/md/lg/xl/2xl,
padded, disableClose for in-flight async work.

Drawer: right-anchored. Surface variant ('drawer' | 'modal' |
'background') preserves the per-site shading that already existed
(ProjectDetail darker, JobDetail modal-shade, PersonDetail page bg).

Migrations:
- NewPersonButton, NewSubscriptionButton, NewGoalButton, NewProjectButton
- ScheduleModal, RunModal, AskIvyModal
- ProjectDetail, JobDetail, PersonDetail

Net: -58 lines, and a future modal palette tweak hits one file.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:51:16 +02:00
g-butandClaude Opus 4.7 92fdf04e64 refactor(theme): replace hardcoded modal/drawer hex with CSS tokens
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>
2026-04-25 16:34:30 +02:00
g-butandClaude Opus 4.7 8cd50e77bb fix(lint): clear all React-hooks errors and unused imports
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 &ldquo;/&rdquo;

Plus: removed 14 unused imports/vars across 10 files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-25 16:18:46 +02:00