Skip to content

fix(runtime): isolate state by infobase - #39

Open
korolevpavel wants to merge 10 commits into
alkoleft:masterfrom
korolevpavel:fix/per-ib-runtime-state
Open

fix(runtime): isolate state by infobase#39
korolevpavel wants to merge 10 commits into
alkoleft:masterfrom
korolevpavel:fix/per-ib-runtime-state

Conversation

@korolevpavel

@korolevpavel korolevpavel commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

Что сделано

  • состояние runtime изолировано по fingerprint информационной базы в ib-state/v1;
  • tracked source tree больше не используется для публикации ConfigDumpInfo.xml: Designer и EDT работают через приватные транзакционные копии;
  • sync receipts фиксируют точный набор обработанных файлов и канонический recovery token;
  • dump выполняется через приватные shadows с трёхсторонним merge, журналом и восстановлением после сбоя;
  • добавлены архитектурные guardrails, CLI-регрессии, live-fixture, ADR и обновление SKILL/SKILL.md.

Проверки

  • cargo fmt --all -- --check;
  • cargo check --all-targets --offline;
  • targeted suites: architecture 4/4, cli_build 19/19, cli_dump 10/10, cli_test 20/20, use_case_boundaries 1/1;
  • независимые tester/reviewer/Rust expert проверки — без findings;
  • реальная 1С 8.3.27: A → A(skip) → B → A(skip), чистый source без CDFI, FULL applied, INCREMENTAL/PARTIAL conflict без изменения source и ib-state;
  • полный suite: 794 passed; 43 воспроизводимых environment/baseline failures (sandbox/macOS path/TCP bind), не связанных с изменением.

Closes #30

Summary by CodeRabbit

  • Новые возможности

    • Добавлены подробные квитанции результатов для операций build и dump: статус, обработанные, пропущенные и конфликтующие файлы.
    • Состояние операций теперь изолируется для каждой информационной базы и контекста.
    • Все режимы dump используют безопасную теневую копию и восстановление после сбоев.
  • Исправления

    • Конфликты и одновременные изменения больше не публикуют частичные результаты.
    • Улучшено безопасное выполнение операций с файлами в Windows.
  • Документация

    • Обновлены инструкции по build/dump, конфликтам, восстановлению и runtime-каталогам.

- define secret-free versioned runtime identity and bootstrap semantics

- specify private CDFI, shadow merge, journal recovery, and exact receipts

- add the test-driven implementation plan for issue 30
- derive secret-free versioned identities for infobases and source contexts

- route change detection through per-infobase storage with explicit bootstrap semantics

- propagate identity failures through typed use-case boundaries without panics
- validate normalized targets and raw SHA-256 transitions
- preserve pre-platform observations across full and partial flows
- exclude runtime artifacts from managed source inventories
- stage managed sources and private CDFI outside source trees
- commit CDFI and hash observations through recoverable journals
- prevent concurrent state replacement with exact no-clobber claims
- commit EDT observations only after downstream convergence
- preserve per-infobase lifecycle across backends and restarts
- resolve relative tool-extension sources against project base
- merge baseline source and dump states without overwriting conflicts
- recover manifest publication and coherent runtime generations
- report exact per-file dump receipts across all modes
- describe private build and dump state lifecycle
- document exact receipts and recovery tokens
- update operator guidance and superseded ADR clauses
- cover incremental and partial no-clobber conflicts
- validate private CDFI lifecycle in trusted live smoke
- harden fixture setup across CI and macOS bash
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@korolevpavel, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 12 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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 reviews.

How do review limits work?

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

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 43684f46-eedb-4c5c-bb15-7a8369053bc2

📥 Commits

Reviewing files that changed from the base of the PR and between e105049 and 577661b.

📒 Files selected for processing (25)
  • SKILL/SKILL.md
  • SKILL/references/file-and-artifact-workflows.md
  • SKILL/references/troubleshooting.md
  • docs/CAPABILITIES.md
  • docs/CONFIGURATION.md
  • scripts/test/live-cli-fixture.sh
  • spec/acceptance/real-environment-validation.md
  • spec/architecture/arc42/09-architecture-decisions.md
  • spec/decisions/0002-izolirovat-runtime-state-po-source-set-pod-workpath.md
  • spec/decisions/0012-on-demand-change-detection-i-faylovaya-partial-load-strategiya.md
  • src/change_detection/hash_storage.rs
  • src/change_detection/partial_load.rs
  • src/change_detection/source_sets.rs
  • src/domain/dump.rs
  • src/domain/mod.rs
  • src/mcp/service.rs
  • src/platform/connection.rs
  • src/platform/designer.rs
  • src/use_cases/dump_config.rs
  • src/use_cases/dump_config/coordinator.rs
  • src/use_cases/dump_config/helpers.rs
  • src/use_cases/runtime_state.rs
  • src/use_cases/source_transaction.rs
  • tests/cli_dump.rs
  • tests/cli_test.rs

Walkthrough

Введено изолированное per-IB runtime state под workPath/ib-state/v1, private build/dump shadows, exact sync receipts, B/S/D merge, recoverable journal publication и Windows-safe filesystem operations. Build, dump, EDT, IBCMD, MCP и acceptance-тесты обновлены под новые контракты.

Changes

Runtime state and contracts

Layer / File(s) Summary
Runtime identity and receipts
src/domain/*, src/change_detection/*
Добавлены fingerprint-based runtime identities, scoped storage, typed SyncReceipt и exact file deltas.
Private build pipeline
src/use_cases/build_project/*, src/use_cases/runtime_state.rs, src/use_cases/source_transaction.rs
Designer/EDT build используют private source transactions, private CDFI, deferred commits и recovery journals.
Private dump publication
src/use_cases/dump_shadow.rs, src/use_cases/dump_execution.rs, src/use_cases/shadow_merge.rs, src/use_cases/source_publication.rs
Dump выполняется в private shadow, планирует B/S/D merge и публикует managed files через recoverable transactions.
Adapters and validation
src/use_cases/dump_config/*, src/use_cases/tool_extension.rs, src/platform/*, tests/*, scripts/test/*
Обновлены orchestration, platform arguments, JSON receipts, conflict handling и acceptance-проверки.
Architecture and documentation
ARCHITECTURE.md, docs/*, spec/*, SKILL/*
Документированы ib-state/v1, private shadows, recovery, receipt semantics и no-clobber dump flow.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested reviewers: alkoleft

Poem

Я, кролик, state в норке храню,
Тени дампа по тропке веду.
Receipt’ы шуршат: “всё учтено!”,
Конфликтам сказать: “не тронуто!”.
CDFI в source не прыгнет никак —
Пусть безопасен будет каждый шаг!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% 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 Заголовок кратко и точно отражает основное изменение: изоляцию runtime state по ИБ.
Linked Issues check ✅ Passed Изменения покрывают #30: изоляцию state по ИБ, приватный CDFI, точные receipts, private shadow dump и защиту от записи в source tree.
Out of Scope Changes check ✅ Passed Не видно посторонних изменений: документация, тесты и платформенные правки поддерживают заявленную изоляцию runtime state и публикацию CDFI.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@korolevpavel

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 4

🧹 Nitpick comments (5)
src/use_cases/runtime_state.rs (1)

292-316: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Вынести вычисление пути маркера full-rebuild-required в общий помощник.

Одинаковая логика вычисления пути маркера (родитель transactions_dir()state_dir.join(FULL_REBUILD_MARKER) с fallback на transactions_dir().join(...)) продублирована трижды: здесь в designer_full_rebuild_required (Line 295-299) и require_designer_full_rebuild (Line 307-311), а также в clear_full_rebuild_marker (Line 686-690). Извлечение единого помощника full_rebuild_marker_path(context) исключит риск расхождения при будущих изменениях расположения маркера.

🤖 Prompt for 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.

In `@src/use_cases/runtime_state.rs` around lines 292 - 316, Extract the
duplicated marker-path calculation into a shared full_rebuild_marker_path
helper. Update designer_full_rebuild_required, require_designer_full_rebuild,
and clear_full_rebuild_marker to use it, preserving the existing
parent-directory fallback behavior.
src/change_detection/source_sets.rs (1)

50-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Опционально: вынести сборку SourceSetContext в общий помощник.

Три ветки (Designer, Edt-generated и edt_contexts) почти идентичны: RuntimeSourceDescriptor::new(...)state_layout.source_state(...)SourceSetContext::new(...).with_excluded_roots(...). Разница только в source_root и logical_role. Помощник вида build_context(ss, path, role, work_path) уберёт дублирование и снизит риск рассинхронизации при будущих правках полей дескриптора.

Also applies to: 103-116

🤖 Prompt for 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.

In `@src/change_detection/source_sets.rs` around lines 50 - 84, Optionally extract
the duplicated SourceSetContext construction shared by the Designer,
Edt-generated, and edt_contexts branches into a helper such as build_context.
Have it accept the source set, source root, logical role, and work path, while
centralizing RuntimeSourceDescriptor::new, source_state, SourceSetContext::new,
and excluded-root setup; preserve each branch’s existing path and role values.
src/use_cases/source_transaction.rs (1)

145-172: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Дублирование логики сравнения snapshot с verify_snapshot.

verify_source_snapshot (Line 145–172) повторяет ту же схему, что и метод verify_snapshot (Line 108–133): скан → построение HashMap<rel_path, hash> → сравнение → SnapshotMismatch. Различаются лишь корень скана и текст ошибки. Стоит вынести сравнение в общий помощник, чтобы обе ветки не разошлись при будущих правках.

🤖 Prompt for 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.

In `@src/use_cases/source_transaction.rs` around lines 145 - 172, Вынеси общую
логику сканирования, построения карт rel_path/hash и сравнения snapshot из
verify_snapshot и verify_source_snapshot в единый вспомогательный метод.
Обеспечь передачу корня скана и сохранение различающихся текстов
SnapshotMismatch, затем замени дублирующиеся участки в обоих методах вызовом
этого помощника.
src/platform/connection.rs (1)

136-136: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Перенесите use в начало файла.

Импорт split_v8_arg_string размещён в самом конце файла после модуля mod tests. Это допустимо синтаксически, но ухудшает читаемость — объявление лучше держать вместе с остальными импортами вверху файла.

🤖 Prompt for 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.

In `@src/platform/connection.rs` at line 136, Переместите импорт
split_v8_arg_string из нижней части файла, после mod tests, в начало
src/platform/connection.rs, разместив его рядом с остальными объявлениями use;
не изменяйте остальную логику.
src/platform/designer.rs (1)

182-182: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Обновите doc-комментарии под новый набор аргументов.

Методы теперь всегда добавляют -updateConfigDumpInfo, но doc-комментарии не отражают это. Актуализируйте описания сигнатур команд, чтобы они соответствовали реально формируемым аргументам.

  • Line 182 (dump_config_to_files): /DumpConfigToFiles <dir> -updateConfigDumpInfo [-Extension <name>]
  • Line 199 (dump_config_to_files_incremental): добавить -updateConfigDumpInfo
  • Line 259 (dump_config_to_files_partial): добавить -updateConfigDumpInfo
🤖 Prompt for 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.

In `@src/platform/designer.rs` at line 182, Обновите doc-комментарии методов
dump_config_to_files, dump_config_to_files_incremental и
dump_config_to_files_partial, добавив обязательный аргумент
-updateConfigDumpInfo в описания формируемых команд; для dump_config_to_files
сохраните порядок `/DumpConfigToFiles <dir> -updateConfigDumpInfo [-Extension
<name>]`, чтобы документация соответствовала фактическим аргументам.
🤖 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 `@docs/CAPABILITIES.md`:
- Line 36: Исправьте Markdown-таблицу в docs/CAPABILITIES.md: экранируйте
символы "|" внутри значений ячеек, начиная с DESIGNER|IBCMD в строке dump.
Найдите соседние строки с IBCMD и также замените внутренние разделители на "\|",
сохранив структуру таблицы из трёх ячеек.

In `@spec/architecture/arc42/09-architecture-decisions.md`:
- Around line 26-27: Добавьте в обзорную таблицу раздела архитектурных решений
отдельные строки для ADR-0021 и ADR-0022, используя их существующие названия,
ссылки, статусы, даты и описания из spec/decisions; сохраните текущий порядок
ADR между ADR-0020 и ADR-0023.

In `@src/change_detection/hash_storage.rs`:
- Around line 538-545: Обновите current_dump_transaction_id, заменив проверку
self.path.exists() на try_exists() с явной обработкой ошибки через
map_filesystem_lookup_error, как в load_state. Возвращайте Ok(None) только когда
путь достоверно отсутствует; ошибки проверки файловой системы или открытия базы
данных должны передаваться как StorageError.

In `@src/use_cases/source_transaction.rs`:
- Around line 63-89: Обновите DesignerSourceTransaction::create, чтобы staging
работал с симлинком в настроенном source_root: после вычисления
canonical_source_root используйте его как физический корень для WalkDir и
передачи исходного корня в copy_regular_no_follow. Сохраните относительные пути,
фильтрацию SourceInventoryPolicy и поведение для обычных корней без изменений.

---

Nitpick comments:
In `@src/change_detection/source_sets.rs`:
- Around line 50-84: Optionally extract the duplicated SourceSetContext
construction shared by the Designer, Edt-generated, and edt_contexts branches
into a helper such as build_context. Have it accept the source set, source root,
logical role, and work path, while centralizing RuntimeSourceDescriptor::new,
source_state, SourceSetContext::new, and excluded-root setup; preserve each
branch’s existing path and role values.

In `@src/platform/connection.rs`:
- Line 136: Переместите импорт split_v8_arg_string из нижней части файла, после
mod tests, в начало src/platform/connection.rs, разместив его рядом с остальными
объявлениями use; не изменяйте остальную логику.

In `@src/platform/designer.rs`:
- Line 182: Обновите doc-комментарии методов dump_config_to_files,
dump_config_to_files_incremental и dump_config_to_files_partial, добавив
обязательный аргумент -updateConfigDumpInfo в описания формируемых команд; для
dump_config_to_files сохраните порядок `/DumpConfigToFiles <dir>
-updateConfigDumpInfo [-Extension <name>]`, чтобы документация соответствовала
фактическим аргументам.

In `@src/use_cases/runtime_state.rs`:
- Around line 292-316: Extract the duplicated marker-path calculation into a
shared full_rebuild_marker_path helper. Update designer_full_rebuild_required,
require_designer_full_rebuild, and clear_full_rebuild_marker to use it,
preserving the existing parent-directory fallback behavior.

In `@src/use_cases/source_transaction.rs`:
- Around line 145-172: Вынеси общую логику сканирования, построения карт
rel_path/hash и сравнения snapshot из verify_snapshot и verify_source_snapshot в
единый вспомогательный метод. Обеспечь передачу корня скана и сохранение
различающихся текстов SnapshotMismatch, затем замени дублирующиеся участки в
обоих методах вызовом этого помощника.
🪄 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: 70d94cbe-760e-4f66-9710-bd19cf695129

📥 Commits

Reviewing files that changed from the base of the PR and between be558db and e105049.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (67)
  • ARCHITECTURE.md
  • Cargo.toml
  • SKILL/SKILL.md
  • SKILL/references/file-and-artifact-workflows.md
  • SKILL/references/troubleshooting.md
  • docs/CAPABILITIES.md
  • docs/CONFIGURATION.md
  • docs/DEEP_DIVE.md
  • docs/plans/2026-07-21-issue-30-per-ib-runtime-state.md
  • scripts/test/README.md
  • scripts/test/ci-designer-config.sh
  • scripts/test/live-cli-fixture.sh
  • spec/acceptance/real-environment-validation.md
  • spec/architecture/arc42/02-constraints.md
  • spec/architecture/arc42/04-solution-strategy.md
  • spec/architecture/arc42/05-building-block-view.md
  • spec/architecture/arc42/06-runtime-view.md
  • spec/architecture/arc42/08-cross-cutting-concepts.md
  • spec/architecture/arc42/09-architecture-decisions.md
  • spec/architecture/arc42/11-risks-and-technical-debt.md
  • spec/architecture/invariants.md
  • spec/decisions/0002-izolirovat-runtime-state-po-source-set-pod-workpath.md
  • spec/decisions/0012-on-demand-change-detection-i-faylovaya-partial-load-strategiya.md
  • spec/decisions/0015-atomarnaya-publikatsiya-dump-artifacts-cherez-staging-backup.md
  • spec/decisions/0023-izolirovat-runtime-state-po-infobase-i-ispolzovat-private-shadow.md
  • spec/decisions/README.md
  • src/change_detection/analyzer.rs
  • src/change_detection/hash_storage.rs
  • src/change_detection/partial_load.rs
  • src/change_detection/scanner.rs
  • src/change_detection/source_sets.rs
  • src/domain/build.rs
  • src/domain/dump.rs
  • src/domain/mod.rs
  • src/domain/runtime_state.rs
  • src/domain/source_set.rs
  • src/domain/sync_receipt.rs
  • src/mcp/edt_syntax.rs
  • src/mcp/service.rs
  • src/platform/connection.rs
  • src/platform/designer.rs
  • src/support/connection_args.rs
  • src/support/error.rs
  • src/support/mod.rs
  • src/support/path.rs
  • src/support/windows_fs.rs
  • src/use_cases/artifacts.rs
  • src/use_cases/build_project.rs
  • src/use_cases/build_project/coordinator.rs
  • src/use_cases/build_project/helpers.rs
  • src/use_cases/check_syntax.rs
  • src/use_cases/dump_config.rs
  • src/use_cases/dump_config/coordinator.rs
  • src/use_cases/dump_config/helpers.rs
  • src/use_cases/dump_execution.rs
  • src/use_cases/dump_shadow.rs
  • src/use_cases/mod.rs
  • src/use_cases/result.rs
  • src/use_cases/runtime_state.rs
  • src/use_cases/shadow_merge.rs
  • src/use_cases/source_inventory.rs
  • src/use_cases/source_publication.rs
  • src/use_cases/source_transaction.rs
  • src/use_cases/tool_extension.rs
  • tests/cli_build.rs
  • tests/cli_dump.rs
  • tests/cli_test.rs

Comment thread docs/CAPABILITIES.md Outdated
Comment thread spec/architecture/arc42/09-architecture-decisions.md
Comment thread src/change_detection/hash_storage.rs
Comment thread src/use_cases/source_transaction.rs
- propagate hard storage lookup failures during recovery
- support symlinked source roots without leaking excluded files
- align documentation and remove review-reported duplication
@korolevpavel

Copy link
Copy Markdown
Contributor Author

Исправления по CodeRabbit опубликованы в b90dde1.

Помимо четырёх inline findings:

  • вынесено единое вычисление пути full-rebuild marker;
  • централизована сборка SourceSetContext без изменения role/path/identity контрактов;
  • объединено сравнение staged/source snapshots с сохранением разных диагностик;
  • импорт connection parser перенесён к остальным use;
  • doc comments Designer приведены к фактическому набору аргументов.

Отдельный Rust expert review обнаружил связанный fail-closed риск: hard/concurrent storage errors маскировались через is_ok_and во время journal recovery. Теперь только Recoverable трактуется как mismatch; Hard и ConcurrentStateModified прерывают recovery до rollback. Регрессионный тест подтверждает сохранение journal и staged artifacts.

Проверки: cargo fmt, cargo check --all-targets, architecture 4/4, targeted unit 76/76, CLI 49/49, новые regressions 3/3. Независимые tester/reviewer/Rust expert проходы — CLEAN.

Предупреждение CodeRabbit о blanket docstring coverage принято как waiver: проект не требует документировать все private helpers, а массовые комментарии не улучшают публичный контракт. Новые и изменённые публичные/инвариантные контракты документированы адресно.

- preserve per-infobase private state and source transactions
- integrate partial selectors, IBCMD data isolation, and upstream launch changes
- reconcile dump tests and docs with shadow bootstrap semantics
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.

bug(runtime): изолировать hash/CDFI state по ИБ и не изменять ConfigDumpInfo в source tree

1 participant