Skip to content

refactor(storage): split cleanup.ts into cohesive leaf modules - #4491

Merged
lidge-jun merged 2 commits into
devfrom
codex/260913-split-storage-cleanup
Sep 13, 2026
Merged

lidge-jun merged 2 commits into
devfrom
codex/260913-split-storage-cleanup

Conversation

@lidge-jun

@lidge-jun lidge-jun commented Sep 13, 2026 •

Copy link
Copy Markdown
Owner

Summary

src/storage/cleanup.ts was 3141 lines carrying quarantine preview, execution, satellite-database snapshot/restore, trash staging, and restore-pending bookkeeping in one file. This splits it into ten cohesive leaves under src/storage/cleanup/ and leaves the original path as a 63-line facade that re-exports all 35 previously exported names, spelled identically, so no consumer and no test is edited.

The leaves are types, paths, db, satellite, pending, reconcile, staging, preview, execute, and restore, layered acyclically (types/paths → db → satellite → reconcile, with the rest on top). The only module-level mutable binding in the original, the _restorePendingSeq filename sequencer, lives in exactly one module (pending.ts) next to its only writer.

This is a pure move: zero behavior change, no renamed symbol, no changed signature. It also opens devlog/_plan/260913_godfile_round1/, which records how the round's three targets were chosen — the ranking is by live open-PR contention rather than size, because responses/core.ts and config.ts each have 19 open PRs against them and splitting either today would rebase all of them.

First of a three-PR stack: this → src/service.ts → src/adapters/kiro.ts.

Verification

  • Local product suite, typecheck, and build were NOT RUN by operator instruction. Hosted CI on the stack tip is the proof; the tip's tree contains all three splits.
  • Export parity checked mechanically: 35 names exported by the original, 35 re-exported by the facade, none missing and none added, with export type vs export preserved.
  • All 143 baseline top-level declarations resolve to exactly one leaf; comment-normalized body comparison shows zero differing bodies.
  • No duplicate declaration across the leaf set, no leaf imports the facade, no src/lab/ import, no relative specifier left unresolvable.
  • Adversarial static review caught one real defect that this PR fixes: randomUUID was used in paths.ts and restore.ts without being imported, which would have thrown ReferenceError on every quarantine execute and mid-commit on every restore.

Checklist

  • Scope stays focused and avoids unrelated cleanup.
  • Docs or release notes were updated when needed.
  • Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.

Summary by CodeRabbit

  • New Features
    • Added archived-session cleanup previews with oldest-first selection, percentage or exact candidate targeting, digest validation, and exclusions for pinned or restore-pending sessions.
    • Added quarantine cleanup with trash staging, recovery manifests, and restore support.
    • Added permanent cleanup that removes archived files after successful database reconciliation.
    • Added resilient restore handling with resumable recovery for interrupted operations and protection against partial failures.

Pure-move split of src/storage/cleanup.ts (3141 lines) into src/storage/cleanup/ leaves: types, paths, db, satellite, pending, reconcile, staging, preview, execute, restore. The original file remains a facade re-exporting every public name. No behavior change; no consumer edits.
@lidge-jun
lidge-jun requested a review from Ingwannu as a code owner September 13, 2026 07:56
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T08:00:32.087977Z 8a07097 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@github-actions github-actions Bot added the intake: hygiene-blocked Deterministic PR hygiene checks failed label Sep 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Deterministic hygiene checks failed.

  • missing_regression_test — Behavior changed under src/ or gui/src/ without a test change. Add focused coverage or obtain test-exception-approved.

@github-actions github-actions Bot added the chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). label Sep 13, 2026
@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 01397bb6-0bd7-4d66-b583-ef18d60018c6

📥 Commits

Reviewing files that changed from the base of the PR and between a3ca64f and 8a07097.

📒 Files selected for processing (12)
  • devlog/_plan/260913_godfile_round1/000_plan.md
  • src/storage/cleanup.ts
  • src/storage/cleanup/db.ts
  • src/storage/cleanup/execute.ts
  • src/storage/cleanup/paths.ts
  • src/storage/cleanup/pending.ts
  • src/storage/cleanup/preview.ts
  • src/storage/cleanup/reconcile.ts
  • src/storage/cleanup/restore.ts
  • src/storage/cleanup/satellite.ts
  • src/storage/cleanup/staging.ts
  • src/storage/cleanup/types.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


📝 Walkthrough

Walkthrough

The PR adds an archived-session cleanup subsystem. It previews and validates candidates, stages files, reconciles SQLite rows with backups, supports quarantine or permanent deletion, and restores staged files through resumable trash entries.

Changes

Archived cleanup and restore

Layer / File(s) Summary
Round scope and cleanup contracts
devlog/_plan/260913_godfile_round1/000_plan.md, src/storage/cleanup/types.ts
The plan defines the cleanup split and pure-move contract. Cleanup and restore result types are added.
Filesystem, pending-state, and database primitives
src/storage/cleanup/paths.ts, src/storage/cleanup/staging.ts, src/storage/cleanup/pending.ts, src/storage/cleanup/db.ts
The modules add safe path validation, atomic file writes, exclusive trash directories, staging and rollback, restore-pending markers, versioned database discovery, writable transactions, and SQLite row helpers.
Preview and database reconciliation
src/storage/cleanup/preview.ts, src/storage/cleanup/satellite.ts, src/storage/cleanup/reconcile.ts
The preview flow selects oldest candidates and excludes pending restores or pinned threads. Reconciliation locks satellite databases, snapshots related rows, deletes dependent data, commits state changes, and restores backups after failures.
Cleanup execution
src/storage/cleanup/execute.ts
executeArchivedCleanup validates the preview digest, writes staging manifests, stages files, reconciles database rows, and handles quarantine or permanent purge results.
Trash listing and restore
src/storage/cleanup/restore.ts
restoreTrashEntry validates manifests and trash paths, resumes interrupted restores with pending markers, moves files back without replacement, restores database rows, commits satellite sections, and finalizes completed stages.

Priority: ➖ Normal

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

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant CleanupClient
  participant executeArchivedCleanup
  participant Preview
  participant Reconcile
  participant TrashRestore
  CleanupClient->>executeArchivedCleanup: request cleanup with preview digest
  executeArchivedCleanup->>Preview: select and validate candidates
  executeArchivedCleanup->>Reconcile: stage files and reconcile database rows
  Reconcile-->>executeArchivedCleanup: cleanup result
  executeArchivedCleanup-->>CleanupClient: quarantine or permanent result
  CleanupClient->>TrashRestore: restore trash entry
  TrashRestore->>Reconcile: restore thread and satellite rows
  TrashRestore-->>CleanupClient: restore result
Loading

Merge Risk: ⚪ Minimal · up to 8a070

No concrete behavior regression or production exposure is established, so the refactor is ready for normal CI validation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 48.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 99 functions across 10 files. (1 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: splitting src/storage/cleanup.ts into cohesive leaf modules while retaining the storage refactor scope.
Full details: Docstring Coverage

Explanation

Docstring coverage is 48.48% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 99 functions across 10 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/260913-split-storage-cleanup

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.

@github-actions

github-actions Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

✅ READY

  • all PR quality gates passed.

Hygiene

✅ Deterministic PR hygiene checks passed.

@github-actions
github-actions Bot marked this pull request as draft September 13, 2026 07:57
@lidge-jun

Copy link
Copy Markdown
Owner Author

test-exception-approved applied — rationale

This PR is a pure-move refactor with zero behavior change: the original file stays as a facade re-exporting every name it exported before, so no consumer and no test is edited. The hygiene gate counts any non-comment change under src/ as a behavior change, which is correct as a default and does not fit a relocation.

Adding a new focused test here would be the wrong artifact. The oracle for a pure move is the existing suite for the moved subsystem, unchanged, which is exactly what proves the relocation preserved behavior. Those suites run on the stack tip (#4493).

Fidelity was verified statically instead, and the checks found real defects rather than rubber-stamping: every baseline top-level declaration resolves to exactly one leaf with a comment-normalized identical body, the facade's export set matches the baseline exactly, every module-level mutable binding and test hook has a single declaration site, and every relative import specifier resolves. Local product suite, typecheck, and build were NOT RUN by operator instruction.

@lidge-jun lidge-jun added the test-exception-approved Maintainer approved a non-automated regression-test exception label Sep 13, 2026
@github-actions github-actions Bot removed the intake: hygiene-blocked Deterministic PR hygiene checks failed label Sep 13, 2026
@lidge-jun

Copy link
Copy Markdown
Owner Author

리뷰 · 우선순위 64 / 80

설명
이 PR은 god-file round 1의 첫 장입니다. 지금 dev의 src/storage/cleanup.ts는 약 3141줄짜리 한 파일에 격리(quarantine) 미리보기, 실행, 위성 DB 스냅샷/복구, 휴지통 스테이징, restore-pending 장부가 전부 들어 있습니다. 이 변경은 그 내용을 src/storage/cleanup/ 아래 열 개 leaf(types, paths, db, satellite, pending, reconcile, staging, preview, execute, restore)로 옮기고, 원래 경로 src/storage/cleanup.ts는 공개 이름을 그대로 다시보내 주는 facade(약 63줄)로 남깁니다.

중요한 점은 "동작 변경 없는 순수 이동"이라는 계약입니다. 예전에 내보내던 이름 35개를 철자까지 같게 다시보내고, 소비자나 테스트를 고치지 않습니다. 모듈 수준에서 바꾸던 유일한 값인 _restorePendingSeq는 pending.ts 한곳에만 두어서, 싱글톤이 둘로 갈라지는 실수를 막습니다. leaf 사이 import도 한 방향(types/paths → db → satellite → reconcile, 나머지는 그 위)이라 순환이 없습니다.

왜 지금 cleanup부터냐면, 계획 문서(devlog/_plan/260913_godfile_round1/000_plan.md)가 말하는 대로입니다. responses/core.ts나 config.ts는 열려 있는 PR이 각각 19개라서 지금 쪼개면 다른 사람 작업이 줄줄이 rebase됩니다. 반면 cleanup/service/kiro는 open-PR 경합이 0이라 지금 쪼개도 남을 가지를 건드리지 않습니다. 위험도도 cleanup이 가장 낮아서 스택의 바닥으로 두었습니다. 스택은 이 PR → #4492(service) → #4493(kiro) 순서이고, 부모 커밋은 [skip ci]라서 실제 CI는 tip(#4493)에서 한 번 돌리는 설계입니다.

정적 검토에서 잡힌 실수도 고쳤습니다. paths.ts와 restore.ts에서 randomUUID를 쓰면서 import를 빠뜨리면 quarantine execute와 restore 중간에서 ReferenceError가 납니다. PR 브랜치에는 node:crypto에서 가져오도록 이미 들어가 있습니다.

우선순위 64는 "지금 당장 사용자 버그를 고치는 건 아니지만", 유지보수와 이후 분할 프로그램의 안전한 첫 발이라서입니다. package는 여전히 2.53.0이고, types/config 분할과는 직접 충돌하지 않습니다. 다만 hygiene이 missing_regression_test로 막혀 있고(intake: hygiene-blocked), 로컬 스위트도 안 돌린 상태라 tip CI 결과가 머지 게이트입니다.

src/storage/cleanup.ts facade - 35개 공개 이름을 leaf에서 다시보냄. 소비자 경로 유지.

src/storage/cleanup/pending.ts - _restorePendingSeq 단일 선언. 포크되면 restore-pending 파일명이 꼬일 수 있음.

src/storage/cleanup/paths.ts / restore.ts - randomUUID import 누락이 있으면 런타임 크래시. 브랜치에는 포함됨.

심볼 hygiene missing_regression_test - 순수 이동이라 새 테스트를 안 넣은 것이 의도. 기존 스위트가 오라클이라는 주장과 게이트 규칙이 충돌 중.

심볼 스택 #4492 / #4493 - 바닥만 먼저 머지하고 tip CI를 볼지, tip이 초록일 때까지 셋을 묶을지.

메인테이너의 판단이 필요한 지점

너의 추천
#4493 tip CI가 초록이면 #4491부터 아래에서 위로 머지하세요. hygiene은 순수 이동이면 export-parity 스모크 한 개로 게이트를 푸는 편이 안전합니다. types/config 분할과는 무관하니 close-don't-rebase 대상이 아닙니다.

이 댓글은 grok-bot이 작성했습니다

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8a0709790d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/storage/cleanup.ts
Comment on lines +15 to +16
* Implementation lives in the `./cleanup/` leaf modules; this file is the
* stable public surface and re-exports every original name.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Update the owning runtime structure document

This split changes the architecture of the owned src/storage/ area, which structure/manifest.json:92 assigns to structure/runtime.md, but the commit does not update that document. Record the new cleanup facade/leaf-module boundary in runtime.md in the same change so the source-ownership documentation remains synchronized.

AGENTS.md reference: AGENTS.md:L37-L41

Useful? React with 👍 / 👎.

@github-actions
github-actions Bot marked this pull request as ready for review September 13, 2026 08:00
@lidge-jun
lidge-jun merged commit 8a07097 into dev Sep 13, 2026
10 of 13 checks passed
@lidge-jun
lidge-jun deleted the codex/260913-split-storage-cleanup branch September 13, 2026 09:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore Maintenance, CI, tests, refactors, or build changes (not a user-facing bug or feature). test-exception-approved Maintainer approved a non-automated regression-test exception

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant