Skip to content

domain: reflective derivations — foundation for the Daily Anchor / feedback loop#13

Open
TargiX wants to merge 1 commit into
mainfrom
feat/daily-anchor-selectors
Open

domain: reflective derivations — foundation for the Daily Anchor / feedback loop#13
TargiX wants to merge 1 commit into
mainfrom
feat/daily-anchor-selectors

Conversation

@TargiX
Copy link
Copy Markdown
Owner

@TargiX TargiX commented Jun 8, 2026

Зачем

Anchor собирает богатый дневной сигнал (2D-настроение energy×valence, сон, привычки, intention, journal), но возвращает почти ничего: во всём lib/ единственные деривации — «ритуал сделан?» + стрик. Этот дисбаланс «отдаёшь и не получаешь» и создаёт ощущение обрубка.

Это фундамент для замыкания петли — без UI, чисто провабельный слой. Спокойные отражения, а не оценки.

Что добавлено (lib/domain/reflection.ts)

Деривация Что говорит человеку
moodShift как настроение качнулось за день (утро → вечер)
averageValence общий уровень настроения за окно
moodDirection rising / steady / falling — тренд, а не снимок
activeDays «ты был здесь 5 из 7 дней» (consistency)
averageSleepHours средний сон за окно
consecutiveLowSleepNights «3-я короткая ночь подряд» (в стиле стрика)
habitCounts сколько раз выполнена каждая привычка

Все функции чистые, в стиле существующего selectors.ts, считают по уже собираемым полям — никаких изменений модели данных и поведения приложения.

Проверки

  • 18 новых юнит-тестов (reflection.test.ts), весь сьют 71 зелёный
  • tsc --noEmit чисто
  • UI не тронут — следующий шаг — Home-карточка «Daily Anchor», которая это покажет (спокойный тон, не дашборд с цифрами)

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added mood trend analysis with direction classification (rising/steady/falling)
    • Mood shift tracking between morning and evening entries
    • Sleep hour averaging and consecutive low-sleep night counting
    • Habit completion tracking and engagement metrics across configurable time windows

Anchor captures a rich daily signal — 2D mood (energy×valence), sleep, habits,
intention, journal — but derives almost nothing back: selectors.ts only knows
"ritual done?" and a streak count. That give-without-get is why the product
feels truncated.

This adds lib/domain/reflection.ts: pure, unit-tested derivations that turn the
captured data into gentle, factual signals a calm UI can surface — reflections,
not grades:

  - moodOf / moodShift        within-day mood movement (morning → evening)
  - averageValence            mood level over a window
  - moodDirection             rising / steady / falling (trend, not snapshot)
  - activeDays                consistency: shown up N of last M days
  - averageSleepHours         sleep level over a window
  - consecutiveLowSleepNights "third short night in a row", streak-style
  - habitCounts               per-habit completions over a window

No UI yet — this is the provable foundation for the Home "Daily Anchor" card.
18 new tests, full suite 71 green, tsc clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 8, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
anchor Ready Ready Preview, Comment, Open in v0 Jun 8, 2026 9:25am
next-js-tether-targix Ready Ready Preview, Comment Jun 8, 2026 9:25am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Jun 8, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ee2e9204-4464-450f-9111-9f04c6d9b422

📥 Commits

Reviewing files that changed from the base of the PR and between f9c095f and ba9e3ee.

📒 Files selected for processing (2)
  • lib/domain/reflection.test.ts
  • lib/domain/reflection.ts

📝 Walkthrough

Walkthrough

This PR introduces a new reflection domain module that exports ten pure functions for analyzing mood trends, sleep patterns, engagement metrics, and habit completion across a sliding window of day entries. All functions operate on immutable day-entry maps and include comprehensive Vitest coverage.

Changes

Reflection and Mood Analysis Domain

Layer / File(s) Summary
Core mood extraction and day windowing
lib/domain/reflection.ts, lib/domain/reflection.test.ts
moodOf selects a representative mood per day (evening preferred), and entriesInWindow extracts and orders entries within a chronological window. Test helpers set up reusable DayEntry and mood fixtures.
Mood delta computation and valence averaging
lib/domain/reflection.ts, lib/domain/reflection.test.ts
moodShift computes energy/valence deltas between morning and evening moods, and averageValence averages valence per day within the window. Tests verify null handling when mood data is incomplete.
Mood direction classification
lib/domain/reflection.ts, lib/domain/reflection.test.ts
moodDirection splits the window into older and recent halves, averages valence for each, and classifies the trend as rising, falling, or steady with epsilon tolerance. Tests cover boundary conditions and threshold behavior.
Activity and engagement counting
lib/domain/reflection.ts, lib/domain/reflection.test.ts
activeDays counts days with completed ritual signals (evening mood + journal, or morning mood + intention) and returns count and total days audited.
Sleep metrics and consecutive low-sleep tracking
lib/domain/reflection.ts, lib/domain/reflection.test.ts
averageSleepHours averages logged sleep nights; consecutiveLowSleepNights backtracks from the latest logged night and counts consecutive nights below a threshold, handling gaps and unlogged days. Tests verify streak counting and threshold edge cases.
Habit completion aggregation
lib/domain/reflection.ts, lib/domain/reflection.test.ts
habitCounts tallies completed habit IDs across the window and returns a map of habit id to completion count.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 A window opens on each day,
Moods dance in their own way,
Sleep and habits counted true,
Ten pure functions, tested through and through!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically summarizes the main change: introducing pure reflection derivation functions that form the foundation for the Daily Anchor feedback loop feature.
Docstring Coverage ✅ Passed Docstring coverage is 83.33% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/daily-anchor-selectors

Comment @coderabbitai help to get the list of available commands and usage tips.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant