Doc status: supporting. This document preserves migration history and implementation context. It is not a source of truth; use
./AGENTS.mdand the canonical docs instead.
Status: Draft (complete, actionable plan for externalizing DI across src/**/application/**)
This document contains a step-by-step migration plan, batch list with files, templates, commands, commit/PR guidance, verification checklist, and troubleshooting notes. Save this file and use it as your source of truth when you reset the conversation and implement the changes.
- Replace implicit/service-locator style dependencies in
src/**/application/**with explicit Dependency Injection (DI). - Pattern: each use-case/service module becomes a factory:
createXxxUseCases(deps)and exposes a backward-compatible shimexport const xxxUseCases = createXxxUseCases({...}). - Wire default factories/instances in
src/di/container.tsx(the central container). - Migrate consumers incrementally. Keep shims until all consumers are migrated.
- Run full checks after each batch:
npm run copilot:check.
- Ensure
src/di/container.tsxandsrc/sections/common/context/Providers.tsxexist and are ready to accept wiring (these were created/adjusted earlier). - Have a clean working tree before starting each batch.
- Tests and linters must be green before starting a batch.
Commands (run before/after batches):
# From repo root (macroflows)
npm run copilot:check # runs lint, tsc, tests via the repo's script
# alternative quick commands:
pnpm run lint
pnpm run test
- Refactor in batches by domain/module. Each batch is a small, reviewable PR.
- For each file:
- Convert the exported object of use-cases into a factory
createXxxUseCases(deps). - Add
export const xxxUseCases = createXxxUseCases({ /* default deps */ })as a shim to avoid immediate breaking changes. - Move imports of infra (repositories, fetchers, clients) into factory
deps. When factories rely on other modules that have not yet been migrated, prefer passing an adapter or keep local import but flag it for follow-up. - Add JSDoc for exported types/functions (repository rules).
- Convert the exported object of use-cases into a factory
- Do NOT create
index.tsbarrel files (repository rule). - Prefer explicit parameter types; avoid
anyand largeascasts. - Container shape should be stable and frozen; prefer
Readonly<Container>.
Note: The list below was scanned from the repository. Use it as your authoritative list to edit. If new files exist locally, adjust the plan accordingly.
src/di/container.tsx(container factory, Provider)src/sections/common/context/Providers.tsx(Provider usage / lifecycle init)
src/modules/auth/application/usecases/authUseCases.tssrc/modules/auth/application/services/authService.tssrc/modules/auth/application/authDI.tssrc/modules/auth/application/store/authStore.tssrc/modules/user/application/usecases/userUseCases.tssrc/modules/user/application/services/userService.tssrc/modules/user/application/store/userStore.ts
src/modules/diet/recipe/application/usecases/recipeCrud.tssrc/modules/diet/recipe/application/services/cacheManagement.tssrc/modules/diet/item/application/recipeItemUseCases.ts(already converted; review)src/modules/diet/food/application/usecases/foodCrud.tssrc/modules/diet/meal/application/meal.tssrc/modules/diet/macro-profile/application/usecases/macroProfileUseCases.tssrc/modules/diet/macro-profile/application/service/macroProfileCrudService.ts
src/modules/diet/day-diet/application/usecases/createBlankDay.tssrc/modules/diet/day-diet/application/usecases/dayEditOrchestrator.tssrc/modules/diet/day-diet/application/usecases/dayUseCases.tssrc/modules/diet/template/application/createGroupFromTemplate.tssrc/modules/diet/template/application/templateToItem.tssrc/modules/template-search/application/templateSearchLogic.tssrc/modules/template-search/application/usecases/templateSearchState.ts
src/modules/weight/application/weight/usecases/weightUseCases.tssrc/modules/weight/application/weight/weightCrud.tssrc/modules/weight/application/chart/weightChartUseCases.tssrc/modules/measure/application/usecases/measureCrud.tssrc/modules/measure/application/usecases/measureState.ts
src/modules/toast/application/toastManager.tssrc/modules/clipboard/application/usecases/clipboardUseCases.tssrc/modules/recent-food/application/usecases/recentFoodCrud.tssrc/modules/import-export/application/exportUtils.tssrc/modules/import-export/application/importValidation.tssrc/modules/import-export/application/idRegeneration.ts
src/modules/profile/application/profile.tssrc/modules/search/application/usecases/cachedSearchCrud.tssrc/modules/observability/application/telemetry.ts- and other remaining
src/modules/*/application/*files.
- Remove backward-compat shims as consumers migrate.
- Remove dead imports, run full lint & test again.
Progress (Batch 7):
Completed (previous work):
-
weightUseCases— centralized in DI container, shim removed- Refactored
createWeightUseCasesto accept requiredauthDepsparameter - Removed circular
useCasesimport from weightUseCases.ts - Updated all consumers (8 files) to use
useCases.weightUseCases() - Updated
container.tsxto provideauthDepswhen creating default weight use-cases
- Refactored
-
weightChartUseCases— centralized in DI container, shim removed- Refactored
createWeightChartUseCasesto accept granularWeightChartDepsinstead oftypeof useCases - Updated consumers (WeightChartTooltip, WeightEvolution) to use
useCases.weightChartUseCases()
- Refactored
Completed (current work - 2025-12-06):
-
macroProfileCrudService— shim removed (internal only, used by macroProfileUseCases)- Made
createMacroProfileUseCasesuse the factory directly with optional deps - Removed shim export from
macroProfileCrudService.ts
- Made
-
dayUseCases(duplicate in dayEditOrchestrator) — removed shadowing export- Removed duplicate shim from
dayEditOrchestrator.tsthat was shadowing main export - Updated test to create instance using factory
- Updated
DayMeals.tsxto create module-level instance - Fixed TypeScript 'any' type errors in catch blocks
- Removed duplicate shim from
-
macroOverflowUseCases— shim removed (1 consumer + 2 legacy exports)- Removed shim and legacy named exports (
isOverflow,getAvailableMacros) - Updated consumers to create module-level instances with factory
- Updated
ItemEditBody.tsx,ItemViewMacros.tsx,TemplateSearchModal.tsx
- Removed shim and legacy named exports (
-
foodCrud— shim removed (1 consumer + named exports)- Removed shim and legacy named exports (
fetchFoods,fetchFoodsByName,fetchFoodByEan) - Updated
EANSearch.tsxto create module-level instance - Updated
templateSearchState.tsto acceptfoodCrudas optional dependency
- Removed shim and legacy named exports (
Blocked (circular dependency):
-
clipboardUseCases— cannot centralize due to import chain causing circular dependency:- Import chain:
useCases.ts→clipboardUseCases→PasteConfirmModal→ItemListView→ItemView→ItemViewMacros→macroOverflow→dayUseCases→useCases.ts - This requires refactoring
macroOverflowto not importdayUseCasesat module level, which is out of scope for this batch. - Keeping shim pattern for now.
- Import chain:
Remaining shims to evaluate (may have similar circular dependency issues):
macroProfileUseCases(3 consumers)dayUseCases(14 consumers) - high risk, needs careful planningcreateBlankDay(function shim)recipeCrud(4 consumers)recipeItemUseCases(4 consumers)macroTargetUseCases(4 consumers)mealUseCases(0 direct imports, may be using through other modules)authUseCases,userUseCases(already in central container)
Commits (Batch 7):
de7b3ccd— refactor(di): batch-7 - centralize weightUseCases in DI container861518ea— refactor(di): batch-7 - migrate weightUseCases consumers to use container696725b4— refactor(di): batch-7 - remove weightUseCases backward-compatible shimab2e709c— refactor(di): batch-7 - make weightUseCases.authDeps required, remove circular import5f66ea6e— docs(di): update migration plan with Batch 7 progress0021f244— refactor(di): batch-7 - centralize weightChartUseCases in DI containerad458e2— refactor(di): Remove macroProfileCrudService and dayUseCases shims (2025-12-06)7f26850— refactor(di): Remove macroOverflowUseCases shim (2025-12-06)69a8491— refactor(di): Remove foodCrud shims (2025-12-06)
A. Example: converting a legacy fooUseCases object
Before:
export const fooUseCases = {
async fetchAndDo(id: number) {
const r = await fetchSomething(id)
// other logic that imports infra directly
},
syncAction(p) {
// ...
}
}
After:
/**
* Factory that returns use-cases for Foo
* @param deps.fetchSomething - injected fetcher
*/
export function createFooUseCases(deps: { fetchSomething: (id:number)=>Promise<Foo|null> }) {
const { fetchSomething } = deps
return {
async fetchAndDo(id: number) {
const r = await fetchSomething(id)
// same logic, but using injected fetcher
},
syncAction(p: string) {
// ...
}
}
}
// Backward-compatible default export (shim)
import { fetchSomething } from '~/modules/foo/infrastructure/fooApi'
export const fooUseCases = createFooUseCases({ fetchSomething })
B. Example: factory typing for reuse
export type FooUseCases = ReturnType<typeof createFooUseCases>
C. Container wiring (example snippet)
// inside createContainer / merged object
fooUseCases: overrides.fooUseCases ?? createFooUseCases({
fetchSomething: () => createFooRepository().fetchById
}),
- Preferred: components call
useContainer()to get the use-cases:
import { useContainer } from '~/di/container'
function MyComponent() {
const container = useContainer()
const foo = container.fooUseCases
// use foo.fetchAndDo(...)
}
- Temporary: keep
import { fooUseCases } from '~/modules/foo/application/fooUseCases'working via shim. Migrate consumers in subsequent small PRs.
Recommended workflow per batch:
git checkout -b refactor/di/batch-<N>
# apply changes for the batch
npm run copilot:check # run checks (lint + tsc + tests)
# if green:
git add .
git commit -m "refactor(di): batch <N> - <module-names>
Converted X files to factory-based DI and registered defaults in container.
Kept backward-compatible shims where needed."
git push origin refactor/di/batch-<N>
# open PR and wait for CI
- If check fails, re-run up to 2 times; if still failing, collect logs and fix locally, then repeat.
- Use the repository script (recommended):
npm run copilot:check
- If tests fail:
- Inspect TS/ESLint output carefully — most common issues:
- Missing
| nullin return type of fetchers used in createResource. - Solid
reactivitylint errors when you expose signals across container; prefer factories that create signals or expose accessor functions. - Avoid
anyand excessiveascasts.
- Missing
- Inspect TS/ESLint output carefully — most common issues:
Example commit header/body:
refactor(di): batch 2 - diet/recipe & diet/item
- Converted recipeCrud.ts and recipeItemUseCases.ts to factory-based DI:
- createRecipeCrud(deps)
- createRecipeItemUseCases(deps)
- Added backward-compatible shims so imports don't break.
- Wired defaults in src/di/container.tsx
- Ran npm run copilot:check and fixed lint/type issues.
PR description checklist:
- Files changed (list)
- Reason & migration pattern
- Tests ran (local output snippet)
- Notes for reviewers (things to watch, follow-ups)
-
Type errors about
Promise<T | null>vsPromise<T>:- Update the factory
depssignature to acceptPromise<T | null>if repo/fetcher returnsnull. - Update callers accordingly.
- Update the factory
-
Solid reactivity lint (
solid/reactivity):- Do not expose live signals from the container directly. Prefer:
- factories that create signals inside components, or
- expose accessor functions, or
- use
createMemoas needed but keep the container's value stable.
- Do not expose live signals from the container directly. Prefer:
-
ESLint complaining about
anycasts:- Replace
anywith explicit small interfaces that declare only the properties you need (e.g., footnote-shaped interfaceLegacyUseCases).
- Replace
-
Tests failing after migration:
- Identify which consumers imported the legacy object; ensure shim exists.
- If tests import directly and expect the old shape, either:
- update tests to create factory instances with mocked deps, or
- keep the shim until tests are updated.
- If a batch breaks CI or causes regressions that cannot be fixed quickly:
- Revert the branch:
git checkout main && git pull && git branch -D refactor/di/batch-<N> && git push origin --delete refactor/di/batch-<N>(or usegit reverton the commit after merge). - Collect logs from
npm run copilot:checkand open an issue with diffs + errors. - Discuss fixes in a follow-up branch and split the batch into smaller chunks if needed.
- Revert the branch:
When you reset the chat and want me to continue, paste a short context block at the start:
- Branch name / stage:
refactor/di/batch-<N>(orstartif new) - Which batch to start with (0..7)
- Files you already changed (optional list or commit SHA)
- Container status: if you added wiring in
src/di/container.tsx, mention it - Request example: "Continue and apply batch 1 (auth & user) and run checks."
With that minimum context I'll resume applying batches or generating concrete diffs.
Use these exact paths while editing. (If you need the complete raw list in a single file, I can produce that on demand.)
src/di/container.tsxsrc/sections/common/context/Providers.tsxsrc/modules/auth/application/authDI.tssrc/modules/auth/application/services/authService.tssrc/modules/auth/application/store/authStore.tssrc/modules/auth/application/usecases/authUseCases.tssrc/modules/clipboard/application/store/clipboardStore.tssrc/modules/clipboard/application/store/tests/clipboardStore.test.tssrc/modules/clipboard/application/usecases/clipboardUseCases.tssrc/modules/diet/day-diet/application/services/dayChange.tssrc/modules/diet/day-diet/application/store/dayCacheStore.tssrc/modules/diet/day-diet/application/store/dayChangeStore.tssrc/modules/diet/day-diet/application/store/dayStateStore.tssrc/modules/diet/day-diet/application/usecases/createBlankDay.tssrc/modules/diet/day-diet/application/usecases/dayEditOrchestrator.tssrc/modules/diet/day-diet/application/usecases/dayUseCases.tssrc/modules/diet/day-diet/application/usecases/useCopyDayOperations.tssrc/modules/diet/day-diet/tests/application/createBlankDay.test.tssrc/modules/diet/day-diet/tests/application/dayEditOrchestrator.test.tssrc/modules/diet/food/application/usecases/foodCrud.tssrc/modules/diet/food/infrastructure/api/application/apiFood.tssrc/modules/diet/item/application/recipeItemUseCases.tssrc/modules/diet/item/application/tests/recipeItemUseCases.test.tssrc/modules/diet/macro-nutrients/application/macroOverflow.tssrc/modules/diet/macro-profile/application/service/macroProfileCrudService.tssrc/modules/diet/macro-profile/application/store/macroProfileCacheStore.tssrc/modules/diet/macro-profile/application/store/macroProfileStateStore.tssrc/modules/diet/macro-profile/application/usecases/macroProfileState.tssrc/modules/diet/macro-profile/application/usecases/macroProfileUseCases.tssrc/modules/diet/macro-target/application/macroTargetUseCases.tssrc/modules/diet/meal/application/meal.tssrc/modules/diet/recipe/application/services/cacheManagement.tssrc/modules/diet/recipe/application/usecases/recipeCrud.tssrc/modules/diet/template/application/createGroupFromTemplate.tssrc/modules/diet/template/application/templateToItem.tssrc/modules/import-export/application/exportUtils.tssrc/modules/import-export/application/idRegeneration.tssrc/modules/import-export/application/importValidation.tssrc/modules/measure/application/measureUtils.tssrc/modules/measure/application/tests/measureUtils.test.tssrc/modules/measure/application/usecases/measureCrud.tssrc/modules/measure/application/usecases/measureState.tssrc/modules/observability/application/telemetry.tssrc/modules/profile/application/profile.tssrc/modules/recent-food/application/tests/extractRecentFoodReference.test.tssrc/modules/recent-food/application/usecases/extractRecentFoodReference.tssrc/modules/recent-food/application/usecases/recentFoodCrud.tssrc/modules/search/application/usecases/cachedSearchCrud.tssrc/modules/template-search/application/templateSearchLogic.tssrc/modules/template-search/application/tests/templateSearchLogic.test.tssrc/modules/template-search/application/usecases/templateSearchState.tssrc/modules/toast/application/toastManager.tssrc/modules/user/application/services/userService.tssrc/modules/user/application/store/userStore.tssrc/modules/user/application/usecases/userUseCases.tssrc/modules/weight/application/chart/weightChartUseCases.tssrc/modules/weight/application/chart/tests/isWeightChartType.test.tssrc/modules/weight/application/chart/weightChartSettings.tssrc/modules/weight/application/weight/store/weightCacheStore.tssrc/modules/weight/application/weight/usecases/weightUseCases.tssrc/modules/weight/application/weight/weightCrud.tssrc/modules/weight/application/weight/weightState.ts
Abaixo segue um checklist detalhado do progresso realizado até o momento. Mantive shims backward-compatible onde necessário e rodei os checks (lint/ts/tests) após cada conjunto de mudanças.
-
Batch 0 — Preparation DI
-
src/di/container.tsx— criado/ajustado e preparado para receber wiring de use-cases (wired defaults para auth/user). -
src/sections/common/context/Providers.tsx— atualizado para criar o container de bootstrap e inicializar lifecycles (usauseCaseslegacy como overrides).
-
-
Batch 1 — Auth & User
-
src/modules/user/application/usecases/userUseCases.ts— convertido paracreateUserUseCases({ repository }), adicionadouserUseCasesshim.- Commit relacionado:
0d90b17e("refactor(di): batch 1 - user & container wiring")
- Commit relacionado:
-
src/di/container.tsx— wired defaults parauserUseCases(Supabase repo) eauthUseCases.- Commit relacionado:
0d90b17e
- Commit relacionado:
-
src/modules/auth/application/usecases/authUseCases.ts— exportcreateAuthUseCasese addedauthUseCasesshim delegando aouserUseCasesshim.- Commit relacionado:
3159e614("refactor(di): auth usecases shim")
- Commit relacionado:
- Verificação:
npm run copilot:checkpassou (lint / tsc / tests).
-
-
Batch 2 — Diet core (recipes, items, food, meal, macro-profile)
-
src/modules/diet/recipe/application/usecases/recipeCrud.ts— convertido paracreateRecipeCrud({ repository })+ defaultrecipeCrud+ shims (fetch*,insertRecipe, etc).- Commit:
4e300d92("refactor(di): batch 2 - recipe crud factory + shims")
- Commit:
-
src/modules/diet/recipe/application/services/cacheManagement.ts— já era factory-style; revisado e mantido. -
src/modules/diet/item/application/recipeItemUseCases.ts— já compatível com DI (usafetchRecipeByIdshim). -
src/modules/diet/food/application/usecases/foodCrud.ts— convertido paracreateFoodCrud({ repository })+ default shimfoodCrud.- Commit:
74c193e6("refactor(di): batch 2 - food crud factory + shims")
- Commit:
-
src/modules/diet/meal/application/meal.ts— criadocreateMealUseCases(deps)com shimmealUseCases, tipado para usarDayUseCases.- Commits:
1d024d79,22d36b6e("refactor(di): batch 2 - meal usecases factory + shim" / "meal uses DayUseCases type")
- Commits:
-
src/modules/diet/day-diet/application/usecases/dayUseCases.ts— convertido paracreateDayUseCases()(encloses signals in createRoot) e exportadodayUseCasesshim; exportDayUseCasestype.- Commits:
78e9ad7e,fad6fb6e("refactor(di): batch 2 - dayUseCases factory + shim" / "refactor(di): batch 2 - dedupe DayUseCases export")
- Commits:
-
src/modules/diet/macro-profile/application/service/macroProfileCrudService.ts— convertido paracreateMacroProfileCrudService+ defaultmacroProfileCrudServiceshim.- Commit:
77a080eb
- Commit:
-
src/modules/diet/macro-profile/application/usecases/macroProfileUseCases.ts— convertido paracreateMacroProfileUseCases({ crudService, cache })+ default shimmacroProfileUseCases.- Commits:
77a080eb,b882ae3b
- Commits:
- Verificação:
npm run copilot:checkpassou após cada alteração e no conjunto final (lint / tsc / tests).
-
-
Batch 3 — Day-diet, template, template-search (concluído)
-
src/modules/diet/day-diet/application/usecases/createBlankDay.ts— convertido para factory (createCreateBlankDay) com backward-compatible shimcreateBlankDay. Note: kept shim to avoid breaking consumers. Commit:0d22e1f8. -
src/modules/diet/day-diet/application/usecases/dayEditOrchestrator.ts— converted tocreateDayEditOrchestrator(deps)and shimmed asdayUseCases. Adjusted types and null-checks to satisfy lint. Commit:0d22e1f8. -
src/modules/diet/template/application/createGroupFromTemplate.ts— reviewed (pure/domain function); no DI required. Commit:0d22e1f8. -
src/modules/diet/template/application/templateToItem.ts— reviewed (pure/domain function); no DI required. Commit:0d22e1f8. -
src/modules/template-search/application/templateSearchLogic.ts— reviewed (pure, logic-only). Commit:0d22e1f8. -
src/modules/template-search/application/usecases/templateSearchState.ts— converted tocreateTemplateSearchState(deps)factory with a backward-compatible shim exposing previous exports. Wrapped increateRootto isolate signals and added a small lint-safe usage pattern. Commit:0d22e1f8.
-
-
Batch 4 — Weight / Measure / Charts
-
src/modules/weight/application/weight/usecases/weightUseCases.ts— converted tocreateWeightUseCases+ shim -
src/modules/weight/application/chart/weightChartUseCases.ts— converted tocreateWeightChartUseCases+ shim -
src/modules/measure/application/usecases/measureCrud.ts— converted tocreateMeasureCrud+ shim -
src/modules/measure/application/usecases/measureState.ts— converted tocreateMeasureState+ shim -
src/modules/weight/application/weight/weightCrud.ts— reviewed and kept as DI-friendly service factory - (other weight/measure/chart files) — pending review
-
-
Batch 5 — Toast, Clipboard, Recent-food, Import/Export
-
src/modules/toast/application/toastManager.ts— factory-style reviewed -
src/modules/clipboard/application/usecases/clipboardUseCases.ts— factory + shim (reviewed) -
src/modules/recent-food/application/usecases/recentFoodCrud.ts— factory + shim (reviewed) -
src/modules/import-export/application/exportUtils.ts— pure helpers (no DI required) -
src/modules/import-export/application/importValidation.ts— pure helpers (no DI required) -
src/modules/import-export/application/idRegeneration.ts— pure helpers (no DI required)
-
-
Batch 6 — Profile, Search, Observability, Misc
-
src/modules/profile/application/profile.ts -
src/modules/search/application/usecases/cachedSearchCrud.ts -
src/modules/observability/application/telemetry.ts -
src/modules/diet/macro-target/application/macroTargetUseCases.ts -
src/modules/diet/macro-nutrients/application/macroOverflow.ts(shim + legacy named exports added) - (other remaining
src/modules/*/application/*files) — reviewed and converted where appropriate; legacy named exports kept as shims.
-
Assistant session notes (context & remaining un-annotated progress)
- Current assistant context window usage at time of note: ~113k / 128k tokens (approx). I recorded this to help resume work if the session is reset.
- Progress that was applied in this session but hadn't yet been explicitly annotated in the plan before this update:
src/modules/diet/macro-target/application/macroTargetUseCases.ts→ converted tocreateMacroTargetUseCases(...)+ shimsrc/modules/diet/macro-nutrients/application/macroOverflow.ts→ converted tocreateMacroOverflow(...)+ shim; legacy named exportsisOverflowandgetAvailableMacrosadded to preserve consumerssrc/modules/weight/application/chart/weightChartUseCases.ts→ converted tocreateWeightChartUseCases(...)+ shimsrc/modules/measure/application/usecases/measureCrud.ts→ converted tocreateMeasureCrud(...)+ shimsrc/modules/measure/application/usecases/measureState.ts→ converted tocreateMeasureState(...)+ shim
These are now recorded above in the checklist.
Plans for next steps / Options (detailed)
Option A — Full Cleanup (Batch 7) — remove all backward-compatible shims
- Goal: remove all default/top-level shim exports (e.g.,
export const fooUseCases = createFooUseCases()), enforce DI everywhere by using the container or explicit factories. - Risk: high — will break any consumer that still imports the legacy named exports. Must be performed only after verifying all consumers have been migrated.
- Steps:
- Discovery phase:
- Run a global search for imports of each shim (e.g.,
import { fooUseCases } from '.../foo') and produce a list of all consumers. - For each shim, build a consumer map showing file and import locations.
- Run a global search for imports of each shim (e.g.,
- Migration/replace phase:
- For each consumer, decide replacement strategy:
- If the file is application-level UI or composed via Provider/DI container, replace import to use
useCasesfrom~/di/useCases(preferred). - If the file is a utility/test, inject the factory via parameters or import the factory and instantiate locally in test setups.
- If the file is application-level UI or composed via Provider/DI container, replace import to use
- Replace the imports programmatically (small targeted edits).
- For each consumer, decide replacement strategy:
- Removal phase:
- Remove the shim export from its source file.
- Run
npm run copilot:check. - Fix any remaining compile/test failures.
- Verification:
- Run full lint/ts/tests.
- Manual spot-check UI flows if possible.
- Commit strategy:
- Make frequent commits per-group (recommended), with a final "cleanup(batch-7): remove shims" commit that summarizes changes.
- Rollback:
- If regressions are found, revert the commit and triage failing consumers.
- Discovery phase:
- Timeline estimate: depends on number of consumers; for this repo size likely 1–2 hours of work with iterative fixes.
Option C — One-by-one shim removal (conservative)
- Goal: remove shims incrementally to minimize risk and reduce the blast radius.
- Steps:
- Pick one shim to remove (e.g.,
weightChartUseCases) — choose low-risk, well-covered modules first (lots of tests). - Find and update all consumers of that shim to use the DI factory/container or an injected dependency:
- Update tests to create factory instances rather than relying on top-level shims.
- Remove the shim export from the source file.
- Run
npm run copilot:check. Fix any issues (1–2 iteration rule). - Commit the change with message:
refactor(di): batch-7 - remove shim <module>. - Repeat for the next shim.
- Pick one shim to remove (e.g.,
- Advantages:
- Low risk, easy rollback per-file.
- Easier to track migration progress.
- Disadvantages:
- Longer overall duration.
- Commit strategy:
- One commit per shim removal (recommended). Optionally squash later.
Common practices & safety nets for both options
- Always run
npm run copilot:checkafter each file change. - Prefer updating tests first: update test imports to use factories before removing shims to avoid noisy failures.
- Keep commits small and descriptive. Use Conventional Commits:
refactor(di): remove shim for <module>orrefactor(di): migrate <consumer> to DI
- If a shim removal causes widespread breakage, revert quickly and open a focused follow-up to address remaining consumers.
Manual approval before Batch 7
-
I will NOT start Batch 7 (removing shims) without your explicit confirmation of which option (A or C) and the commit behavior you prefer (single final commit vs per-file commits). Please confirm the option and commit style.
-
Batch 7 — Cleanup final
- Remover shims backward-compat quando todos os consumidores forem migrados.
- Remover imports mortos, rodar lint+tests e limpar tipos.
Commits relevantes (resumo)
0d90b17e— refactor(di): batch 1 - user & container wiring3159e614— refactor(di): auth usecases shim323e037c— docs(di): add DI migration plan4e300d92— refactor(di): batch 2 - recipe crud factory + shims74c193e6— refactor(di): batch 2 - food crud factory + shims1d024d79— refactor(di): batch 2 - meal usecases factory + shim22d36b6e— refactor(di): batch 2 - meal uses DayUseCases type3bbc71c2— refactor(di): batch 2 - day and meal typing + meal factory77a080eb— refactor(di): batch 2 - macro-profile service & usecases factories + shimsb882ae3b— refactor(di): batch 2 - macro-profile factories + shims78e9ad7e— refactor(di): batch 2 - dayUseCases factory + shimfad6fb6e— refactor(di): batch 2 - dedupe DayUseCases export
Observações / notas rápidas
- Estratégia aplicada: converter módulos para factories e manter shims até migrar consumidores. Isso mantém o código rodando e testes verdes durante a migração gradual.
- Após a sua ação de "comprimir a conversa" e retomar, prossigo com Batch 3 (vou manter a estratégia padrão de manter shims para minimizar impacto — altere se quiser injetar dependências imediatamente).
- Se preferir, posso também gerar um arquivo
.github/di-migration-checklist.mdcom o mesmo checklist para tracking no repo.
Assistant migration snapshot (recorded progress)
-
Short summary
- Pattern applied: convert application modules to DI-friendly factories
createXxx(...)and keep backward-compatible shimsexport const xxx = createXxx(...)while migrating consumers incrementally. - Commits are small and frequent;
npm run copilot:check(lint + tsc + tests) was run after each change set.
- Pattern applied: convert application modules to DI-friendly factories
-
Batches completed (so far)
- Batch 0 — Preparation DI: done (container & providers ready).
- Batch 1 — Auth & User: done (user/auth use-cases converted & wired).
- Batch 2 — Diet core: done (recipes/food/meal/macro-profile converted).
- Batch 3 — Day-diet, template, template-search: done (factories + shims; pure template functions left unchanged).
- Batch 4 — Weight: partial —
weightUseCasesconverted tocreateWeightUseCases+ shim. - Batch 5 — Toast / Recent-food / Clipboard: partial —
toastManager,recentFoodCrud,clipboardUseCasesconverted to factories + shims.
-
Files modified (high-level)
- Day-diet:
src/modules/diet/day-diet/application/usecases/createBlankDay.ts—createCreateBlankDay+ shim.src/modules/diet/day-diet/application/usecases/dayEditOrchestrator.ts—createDayEditOrchestrator+ shim.src/modules/diet/day-diet/application/usecases/useCopyDayOperations.ts—createCopyDayOperations+ shim.
- Template / Template-search:
src/modules/diet/template/application/templateToItem.ts— pure/domain (reviewed).src/modules/diet/template/application/createGroupFromTemplate.ts— pure/domain (reviewed).src/modules/template-search/application/templateSearchLogic.ts— pure logic (reviewed).src/modules/template-search/application/usecases/templateSearchState.ts—createTemplateSearchState+ shim.
- Weight:
src/modules/weight/application/weight/usecases/weightUseCases.ts—createWeightUseCases+ shim.
- Toast:
src/modules/toast/application/toastManager.ts—createToastManagerfactory; top-level wrappers call the factory at call-time to keep tests/spies working.
- Recent-food:
src/modules/recent-food/application/usecases/recentFoodCrud.ts—createRecentFoodCrud+ shim.
- Clipboard:
src/modules/clipboard/application/usecases/clipboardUseCases.ts—createClipboardUseCases+ shim.
- Day-diet:
-
Important commits (recent)
0d22e1f8— batch-3 day-diet & template-search changes2cdecde1— docs update (marked Batch 3 completed)207f7220— batch-4 weight usecases factory + shimb7247c22— batch-5 toast manager factory + shim5f81d81c— batch-5 recent-food CRUD factory + shimfbba9d19— batch-5 clipboard usecases factory + shim
-
Verification status
- After each set of edits I ran
npm run copilot:check. Final recorded state: all checks passed (lint/ts/tests) at the last commit; 562 tests green.
- After each set of edits I ran
-
Design notes & rationale
- Keep shims for backward compatibility and stepwise consumer migration.
- Create signals/resources inside
createRootwhen needed to respect Solid lifecycle and reactivity lint. - Avoid introducing barrel files (index.ts) or changing import conventions; keep absolute
~/imports. - Prefer explicit types and avoid unsafe
anyor unchecked conditionals.
How to resume (exact lines you can paste to resume)
- Minimal resume command:
- "Resume: continue Batch 6"
- Specific-file resume:
- "Resume: migrate src/modules/observability/application/telemetry.ts"
- "Resume: migrate src/modules/profile/application/profile.ts"
- "Resume: migrate src/modules/search/application/usecases/cachedSearchCrud.ts"
- Default behavior on resume:
- I will continue converting files in the chosen batch to the factory+shim pattern, run
npm run copilot:checkafter each logical change, commit frequently with messages like:refactor(di): batch-6 - <module-name> factory + shim
- I will update this
DI-migration-plan.mdchecklist as I complete files.
- I will continue converting files in the chosen batch to the factory+shim pattern, run
Notes before you reset the conversation
- The file
DI-migration-plan.mdis already updated to reflect Batch 3 completion. - If you want a separate artifact for CI tracking, tell me to generate
.github/di-migration-checklist.mdand I will produce it. - When you come back, paste one of the resume lines above and I will continue exactly where I left off.