Skip to content

Expose migration state in operator health#378

Merged
thebtf merged 3 commits into
mainfrom
work/migrations-health-control-plane
Jun 23, 2026
Merged

Expose migration state in operator health#378
thebtf merged 3 commits into
mainfrom
work/migrations-health-control-plane

Conversation

@thebtf

@thebtf thebtf commented Jun 23, 2026

Copy link
Copy Markdown
Owner

Summary

  • add read-only GET /api/migrations backed by the gormigrate bookkeeping table
  • wire Operator Console Health to show live migration state and endpoint evidence
  • update i18n, mock API, seam contract, and PARITY so migrations are no longer marked mustbuild

Verification

  • go test ./internal/worker -run TestHandleGetMigrations -count=1
  • go test ./internal/db/gorm ./internal/worker -count=1
  • npm run test:seam
  • npm run parity
  • npm run build
  • npm run test:browser
  • go test ./...

Notes

  • npm build/browser verification required a local node_modules install in this worktree. Cleanup was attempted, but the destructive-command guard blocks removing D:\Dev\engram-wt paths because the active workspace root is D:\Dev\engram. node_modules is ignored and not part of this PR.

Summary by CodeRabbit

Примечания к выпуску

  • New Features

    • Добавлена новая карточка «migrations» на странице Health: отображаются движок, таблица, текущая версия и количество применённых миграций.
    • При недоступности данных или неподдерживаемых полях выводится понятное состояние/сообщение.
  • Improvements

    • Расширена диагностика сервера: статус миграций теперь учитывается в общей оценке здоровья.
    • Обновлены переводы для EN/RU/ZH с новыми строками по миграциям.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@thebtf, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 3 minutes and 17 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses rolling per-developer review limits. Reviews become available again as older review attempts age out of the rolling limit window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 9dee0b4d-ae42-4b8c-b954-161cd3541ff9

📥 Commits

Reviewing files that changed from the base of the PR and between 64e8c36 and 07d64e7.

📒 Files selected for processing (3)
  • apps/operator-console/scripts/seam-contract.test.mjs
  • internal/db/gorm/migration_state.go
  • internal/db/gorm/migration_state_test.go

Walkthrough

Добавлен новый эндпоинт GET /api/migrations на бэкенде, реализованный методом GetMigrationState в gorm-слое. Оператор-консоль получает состояние миграций через хук useOperatorHealthSettings и отображает его в виде карточки на странице Health. Запись "migrations (mustbuild)" удалена из PARITY.json.

Changes

Migration State: Backend to Health UI

Layer / File(s) Summary
MigrationState тип и GetMigrationState метод
internal/db/gorm/migration_state.go
Новый тип MigrationState и метод Store.GetMigrationState, читающий таблицу migrations, вычисляющий CurrentVersion и AppliedCount с фиксированными флагами DirtySupported=false, AppliedAtSupported=false.
HTTP-маршрут и обработчик /api/migrations
internal/worker/service.go, internal/worker/handlers_system.go, internal/worker/handlers_system_test.go
Регистрирует GET /api/migrations в таблице маршрутов; handleGetMigrations блокирует через initMu, возвращает 503 при отсутствии store и 500 при ошибке. Юнит-тест проверяет 503, интеграционный тест — поля ответа 200.
ApiMigrationState и загрузка состояния в хуке
apps/operator-console/composables/useOperatorHealthSettings.ts
Добавлен интерфейс ApiMigrationState, evidence для /api/migrations, migrations useState, migrationsState computed, migrationMetrics computed, включение в агрегирование ошибок и в refresh.
Карточка миграций на странице Health с i18n
apps/operator-console/pages/health.vue, apps/operator-console/i18n/locales/en.json, apps/operator-console/i18n/locales/ru.json, apps/operator-console/i18n/locales/zh.json
Разворачивает migrationsState и migrationMetrics в скрипте; добавляет карточку с метриками, ветку по dirty_supported и HonestyBadge. Добавлены ключи перевода migration.* во всех трёх локалях.
Mock API, seam-тест и удаление PARITY-гэпа
apps/operator-console/scripts/mock-operator-api.mjs, apps/operator-console/scripts/seam-contract.test.mjs, apps/operator-console/PARITY.json
Добавлены фикстура и маршрут /api/migrations в mock-сервер. Seam-контракт проверяет экспорт типа, live-классификацию и i18n на странице. Строка "migrations (mustbuild)" удалена из PARITY.json.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • thebtf/engram#370: Изменяет apps/operator-console/PARITY.json в секции health, касаясь статуса задела для миграций; в этой PR запись удаляется после реализации.

Poem

🐇 Скок-поскок по базе данных,
Миграции теперь не mustbuild!
/api/migrations открыт — ура нам,
Версия, движок — всё в UI видать.
Кролик доволен: гэп закрыт в PARITY,
HonestyBadge светит честно и ярко! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок PR точно отражает основное изменение: добавление эндпоинта и интеграции для отображения состояния миграций в системе health мониторинга оператора консоли.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch work/migrations-health-control-plane

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

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements live database migration status tracking in the operator console's health page, replacing the previous mock gap. It introduces the /api/migrations endpoint on the backend to retrieve the current migration state from the database, and updates the frontend to display these metrics. Feedback on the changes highlights a logical issue in health.vue where the UI incorrectly falls back to a 'not loaded' message when the migration state is live but dirty_supported is not false.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread apps/operator-console/pages/health.vue Outdated
@thebtf

thebtf commented Jun 23, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai review incremental

@thebtf

thebtf commented Jun 23, 2026

Copy link
Copy Markdown
Owner Author

@codex review

@coderabbitai

coderabbitai Bot commented Jun 23, 2026

Copy link
Copy Markdown

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Get PR details
gh pr view 378 --repo thebtf/engram --json title,body,baseRefName,headRefName,files

echo "=== PR DIFF ==="
gh pr diff 378 --repo thebtf/engram

Length of output: 23445



@thebtf Here's the incremental review:


internal/db/gorm/migration_state.go

current_version sort assumption (line 39)

Order("id ASC").
Scan(&ids).Error; err != nil {

Order("id ASC") sorts lexicographically. current_version is then taken as ids[len(ids)-1]. This is correct only because all migration IDs currently use zero-padded numeric prefixes (001_, 150_, 151_). If a future migration is added without that prefix convention, the "latest" ID could be wrong silently. Worth a short comment:

// IDs are expected to be zero-padded numeric prefixes (e.g. "151_…") so that
// lexicographic ASC order equals insertion order.
Order("id ASC").

applied_ids always included, unbounded (line 52)

AppliedIDs: ids,

applied_ids is the full list of every applied migration and is returned on every health poll. For a codebase that accumulates hundreds of migrations, this is extra payload on a frequently-polled endpoint. Consider omitting or capping it (e.g. only include the last N, or gate it behind a ?verbose=1 query parameter) — or at minimum document that callers should treat this as potentially large.


apps/operator-console/pages/health.vue

Error state shows "not loaded" copy instead of error (lines 126–131)

<p class="message">
  {{ migrationsState.kind === 'live' && migrationsState.data.dirty_supported === false
      ? t('health.migration.dirtyUnsupported')
      : t('health.state.notLoaded') }}    <!-- shown for 'error' too -->
</p>
<HonestyBadge
  :evidence="migrationsState.kind === 'live'
    ? migrationsState.data.engine
    : t('health.state.notLoaded')"        <!-- shown for 'error' too -->
/>

When migrationsState.kind === 'error', both the <p> and the HonestyBadge evidence fall through to t('health.state.notLoaded'). The data was attempted but failed — "not loaded" is misleading. Other cards in the health page distinguish pending/error; this one should too. A minimal fix:

<p class="message">
  {{ migrationsState.kind === 'live' && migrationsState.data.dirty_supported === false
      ? t('health.migration.dirtyUnsupported')
      : migrationsState.kind === 'error'
        ? t('health.state.error', { message: migrationsState.error.message })
        : t('health.state.notLoaded') }}
</p>

And for the badge evidence:

:evidence="migrationsState.kind === 'live'
  ? migrationsState.data.engine
  : migrationsState.kind === 'error'
    ? migrationsState.error.message
    : t('health.state.notLoaded')"

internal/worker/handlers_system_test.go

TestHandleGetMigrations_ReturnsAppliedState accesses s.store directly — this is fine for a test-local Service struct with no concurrent access, and the skip guard on DATABASE_DSN is correct. No issue.


Everything else

  • Route registration, RLock guard around s.store, i18n keys (en/ru/zh all consistent), mock API, seam contract assertions, PARITY update — all look correct and consistent with the existing patterns.
  • The dirty_supported: false / applied_at_supported: false hardcoded values are well-documented and the UI dirtyUnsupported message is a nice transparency touch.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@apps/operator-console/scripts/seam-contract.test.mjs`:
- Line 368: The regex pattern in the assert.match call for mockOperatorApiSource
uses a greedy quantifier in the pattern matching the migration case block. The
`[\s\S]*` is matching too much content and can span across adjacent case blocks,
potentially missing regressions in the specific `/api/migrations` endpoint
handler. Change the greedy quantifier `[\s\S]*` to non-greedy `[\s\S]*?` in the
regex pattern to ensure it matches the minimum necessary content and properly
validates only the migrations case block without extending into neighboring case
statements.

In `@internal/db/gorm/migration_state.go`:
- Around line 35-46: The issue is that the query in the migration state function
sorts migration IDs lexicographically using Order("id ASC") and takes the last
one, but this does not reflect the actual order in which migrations were applied
since gormigrate registers migrations in a different order than their ID values
suggest. To fix this, replace the Order("id ASC") clause with ordering by a
timestamp or sequence field that tracks the actual application order of
migrations (such as created_at or a similar field in the migrations table that
gormigrate maintains). This ensures that the current variable correctly captures
the last applied migration rather than the lexicographically last ID. If the
migrations table schema is unclear, check the gormigrate documentation or the
actual migrations table structure to determine which field properly tracks
application order.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: aaa023aa-4f69-452b-adfa-5883c4b133ee

📥 Commits

Reviewing files that changed from the base of the PR and between 333605c and b0698fe.

📒 Files selected for processing (12)
  • apps/operator-console/PARITY.json
  • apps/operator-console/composables/useOperatorHealthSettings.ts
  • apps/operator-console/i18n/locales/en.json
  • apps/operator-console/i18n/locales/ru.json
  • apps/operator-console/i18n/locales/zh.json
  • apps/operator-console/pages/health.vue
  • apps/operator-console/scripts/mock-operator-api.mjs
  • apps/operator-console/scripts/seam-contract.test.mjs
  • internal/db/gorm/migration_state.go
  • internal/worker/handlers_system.go
  • internal/worker/handlers_system_test.go
  • internal/worker/service.go

Comment thread apps/operator-console/scripts/seam-contract.test.mjs Outdated
Comment thread internal/db/gorm/migration_state.go
@thebtf thebtf merged commit c89fba6 into main Jun 23, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant