From 805a9f8fd4b1aeda82bee7b57eb4584819f2334d Mon Sep 17 00:00:00 2001 From: Boki Date: Mon, 26 Oct 2026 13:23:49 -0400 Subject: [PATCH] fix: clean up service configuration startup and development commands --- README.md | 23 +- apps/stock/README.md | 5 + apps/stock/web-app/README.md | 5 + docs/development/CLEANUP.md | 6 +- docs/development/backlog/README.md | 2 +- docs/development/backlog/manifest.json | 44 +- docs/development/backlog/tasks/CL01.md | 2 +- docs/development/backlog/tasks/CL02.md | 2 +- docs/development/backlog/tasks/CL03.md | 2 +- docs/development/backlog/tasks/CL04.md | 2 +- docs/development/backlog/tasks/CL05.md | 2 +- docs/development/backlog/tasks/CL06.md | 2 +- docs/development/backlog/tasks/CL07.md | 2 +- docs/development/backlog/tasks/CL08.md | 2 +- docs/development/backlog/tasks/CL09.md | 2 +- docs/development/backlog/tasks/CL10.md | 2 +- docs/development/backlog/tasks/CL11.md | 2 +- docs/development/backlog/tasks/CL12.md | 2 +- docs/development/backlog/tasks/CL13.md | 2 +- docs/development/cleanup-execution.md | 33 ++ .../config/src/schemas/database.schema.ts | 2 + .../config/src/schemas/unified-app.schema.ts | 2 +- .../di/src/config/schemas/mongodb.schema.ts | 8 +- .../di/src/config/schemas/postgres.schema.ts | 11 +- .../di/src/config/schemas/questdb.schema.ts | 14 +- .../di/src/config/schemas/redis.schema.ts | 11 +- libs/core/di/src/container/builder.ts | 58 +- .../registrations/database.registration.ts | 36 +- libs/core/di/src/utils/lifecycle.ts | 92 +-- libs/core/di/test/container-builder.test.ts | 527 ++++-------------- libs/core/di/test/di.test.ts | 6 + package.json | 12 +- scripts/docker.sh | 31 +- scripts/test/workspace.test.ts | 44 +- .../service-startup-rollback.test.ts | 96 ++++ test/integration/store-configuration.test.ts | 129 +++++ 36 files changed, 627 insertions(+), 596 deletions(-) create mode 100644 docs/development/cleanup-execution.md create mode 100644 test/integration/service-startup-rollback.test.ts create mode 100644 test/integration/store-configuration.test.ts diff --git a/README.md b/README.md index c27552dd..82fa96d6 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,27 @@ the root workspace checks. system map, a complete backtest walkthrough, TypeScript strategy authoring, and a [function-by-function code tour](docs/guide/code-reading.md). +## Start the research workbench + +From the repository root, after installing dependencies and building: + +```sh +bun run infra:up +bun run dev:research +``` + +This starts the API on port 2003, orchestrator on 2004 and web app on 5173, with required +workspace builds. Infrastructure uses Docker Compose v2 and includes Dragonfly, PostgreSQL, +QuestDB and MongoDB. Keep the existing environment configuration; database credentials must +match the running stores. Configure the operator access token for browser login and the +API origin as described in the [web app guide](apps/stock/web-app/README.md). Startup does +not reset data, launch ingestion, or activate a paper/live account. Use `docker:start` as +an alias for `infra:up`; optional admin/monitoring services are separate commands. + +The obsolete `db:init`, `db:setup-ib` and `proxy` aliases were removed because their targets +no longer exist. Apply reviewed migrations explicitly; ordinary startup never initializes +or resets an existing database. + ## Current research workflow The web workbench is the primary interface: Strategies → Backtests → Experiments → @@ -65,7 +86,7 @@ and saved template, explicitly allows its own candidates, and sets bounded job b Give that research token to the client, never an operator or brokerage credential. ```sh -RESEARCH_API_ORIGIN=http://127.0.0.1:3001 RESEARCH_API_TOKEN=sb-research.… \ +RESEARCH_API_ORIGIN=http://127.0.0.1:2003 RESEARCH_API_TOKEN=sb-research.… \ bun run scripts/examples/research-cycle.ts --plan prepared-plan.json --receipts new-receipts.jsonl ``` diff --git a/apps/stock/README.md b/apps/stock/README.md index 7ccd06ef..be74d8e2 100644 --- a/apps/stock/README.md +++ b/apps/stock/README.md @@ -1,5 +1,10 @@ # Stock platform +For the complete local research stack, run `bun run infra:up` then `bun run dev:research` +from the repository root after the initial build. The API, orchestrator and browser use +ports 2003, 2004 and 5173. This preserves existing data and does not activate trading. + + The stock application combines a TypeScript research workbench and strategy runtime with an authoritative Rust financial engine. **Start with [Understanding Stock Bot](../../docs/guide/README.md).** It explains the connected system, follows a complete backtest, and introduces the actual strategy API. diff --git a/apps/stock/web-app/README.md b/apps/stock/web-app/README.md index 1d7d0f70..e6e66b1e 100644 --- a/apps/stock/web-app/README.md +++ b/apps/stock/web-app/README.md @@ -1,5 +1,10 @@ # Stock Bot research workbench +For the complete local research stack, run `bun run infra:up` then `bun run dev:research` +from the repository root after the initial build. The API, orchestrator and browser use +ports 2003, 2004 and 5173. This preserves existing data and does not activate trading. + + The React application is the primary interface for strategy versions, reproducible backtests, experiments and evidence-linked research. It consumes the TypeScript web API; the authoritative financial simulation runs in Rust behind the orchestrator. For the whole system, start with [Understanding Stock Bot](../../../docs/guide/README.md) and the [backtest walkthrough](../../../docs/guide/backtest-walkthrough.md). diff --git a/docs/development/CLEANUP.md b/docs/development/CLEANUP.md index bf7a066b..4da96812 100644 --- a/docs/development/CLEANUP.md +++ b/docs/development/CLEANUP.md @@ -1,6 +1,6 @@ # Cleanup and maintainability plan -Baseline: `fbf2eb9e`, inspected October 26, 2026. This is a planning-only extension of the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. No application implementation, agent launch or Git commit is part of this request. +Baseline: `fbf2eb9e`, inspected October 26, 2026. This extends the existing development backlog. The original 45 scheduled tasks remain complete; these 13 cleanup stories are new work. The owner subsequently authorized implementation and validated commits; progress and checks are recorded in [cleanup-execution.md](cleanup-execution.md). No additional agents have been launched. [manifest.json](backlog/manifest.json) remains the scheduling source of truth. It records task states, prerequisites, priorities and write locks. This page explains the execution contract and recommended order; it is not a second status tracker. Current evidence is appended to [findings.md](backlog/findings.md#cleanup-audit-2026-10-26). @@ -59,7 +59,7 @@ This is a preferred sequence, not an artificial dependency chain. Unrelated fron ## First execution wave -**CL01, CL03 and CL04** are the first independent assignments. Implementation still requires a subsequent user instruction; current manifest authorization is planning-only. The earlier completion authorization remains historical evidence for the completed original backlog. +**CL01, CL03 and CL04** are the first independent assignments. The owner has authorized implementation and validated commits. The earlier completion authorization remains historical evidence for the completed original backlog. | Story | Why first | Writable ownership | Completion evidence | | --- | --- | --- | --- | @@ -72,7 +72,7 @@ These three assignments have disjoint authored paths. For a solo maintainer, sta ## Execution contract - Read the task, current manifest, approved relevant architecture decisions and [QUALITY-GATES.md](QUALITY-GATES.md). Scope is the selected story, not permission to implement neighboring cleanup. -- `ready` means code prerequisites are satisfied. The current top-level `execution_authorized` is false because the user requested stories, not implementation. Do not infer new authorization from historical task completion or old continuation instructions. +- `ready` means code prerequisites are satisfied. The current top-level `execution_authorized` is true following the owner’s explicit cleanup implementation request. Scope remains these stories; conditional performance/product tasks are excluded. - Use one focused branch/worktree per implementation when multiple agents are used. Claim exact files and write locks in the manifest before edits. An unexpected overlap requires coordination before changing the shared file. - Preserve Rust financial semantics, strategy targets/state, exact financial output, command idempotency, receipt recovery, run/outbox atomicity, leases, paper recovery and original reproduction inputs. - Preserve historical result readers, retained source/build artifacts, reviewed calculation APIs and useful legacy research. No broad dead-code deletion or native-export removal follows from this plan. diff --git a/docs/development/backlog/README.md b/docs/development/backlog/README.md index 680b341a..c90bb373 100644 --- a/docs/development/backlog/README.md +++ b/docs/development/backlog/README.md @@ -2,7 +2,7 @@ **The original 45/45 scheduled tasks are complete.** The canonical Rust engine, TypeScript research/workbench, bounded worker pool, isolated candidates, AI evidence workflow and human-reviewed paper promotion are validated. Implementation commits: `bbf0dd4`, `26b9726`, `25b5cbf` (R07 measurement `ab08db8`). Six conditional tasks remain deferred; four merged IDs remain redirects. This is scheduled-backlog completion, not live-trading activation. -**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. Their implementation has not been requested; the manifest's current execution authorization is false. The first independent group is CL01, CL03 and CL04. +**New work:** [13 cleanup stories](../CLEANUP.md) were proposed on October 26, 2026. The owner subsequently authorized implementation and commits; see [execution evidence](../cleanup-execution.md). The first independent group is CL01, CL03 and CL04. ## One source of truth diff --git a/docs/development/backlog/manifest.json b/docs/development/backlog/manifest.json index 48f1f47d..64dab315 100644 --- a/docs/development/backlog/manifest.json +++ b/docs/development/backlog/manifest.json @@ -2,8 +2,8 @@ "schema_version": 1, "plan_revision": "2026-10-26.79", "repository_base": "b7aeca4", - "plan_status": "cleanup_backlog_proposed", - "execution_authorized": false, + "plan_status": "cleanup_backlog_in_progress", + "execution_authorized": true, "execution_scope": { "authorized_by": "Owner: commit and continue with the rest of the tasks till 100%", "tasks": ["R05", "R07", "S06", "A01", "A02", "A03", "A04", "P04"], @@ -50,7 +50,7 @@ "CL03", "CL04" ], - "authorization": "Stories and planning artifacts only. Top-level execution_authorized is false; historical execution_scope applies to the completed original backlog.", + "authorization": "Owner authorized cleanup implementation and validated commits: commit, implement backlog tasks and commit again. Historical execution_scope remains evidence for the original backlog.", "preserved_original_tasks": 55, "preserved_original_completed_tasks": 45, "excluded": [ @@ -2086,7 +2086,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "ready", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL01.md", @@ -2105,13 +2105,14 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "planned", + "integration_state": "validated", "integration_base": "fbf2eb9e", - "review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.", + "review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.", "concrete_write_scope": [ "libs/core/di/test/container-builder.test.ts", "libs/core/di/test/di.test.ts" - ] + ], + "completion_evidence": "docs/development/cleanup-execution.md" }, { "id": "CL02", @@ -2119,7 +2120,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "blocked", + "status": "done", "dependencies": [ "CL01" ], @@ -2140,11 +2141,11 @@ "branch": null, "pull_request": null, "completed_commit": null, - "blocker": "Waiting for implementation prerequisites: CL01.", + "blocker": null, "release_gates": [], - "integration_state": "planned", + "integration_state": "validated", "integration_base": "fbf2eb9e", - "review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.", + "review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.", "concrete_write_scope": [ "libs/core/config/src/schemas/database.schema.ts", "libs/core/config/src/schemas/unified-app.schema.ts", @@ -2155,7 +2156,8 @@ "test/integration/questdb-configuration.test.ts", "libs/core/di/test/container-builder.test.ts", "test/integration/store-configuration.test.ts" - ] + ], + "completion_evidence": "docs/development/cleanup-execution.md" }, { "id": "CL03", @@ -2163,7 +2165,7 @@ "epic": "E10", "priority": "P1", "severity": "High", - "status": "ready", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL03.md", @@ -2183,15 +2185,16 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "planned", + "integration_state": "validated", "integration_base": "fbf2eb9e", - "review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.", + "review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.", "concrete_write_scope": [ "libs/core/di/src/utils/lifecycle.ts", "libs/core/di/src/container/builder.ts", "libs/core/di/test/lifecycle.test.ts", "test/integration/service-startup-rollback.test.ts" - ] + ], + "completion_evidence": "docs/development/cleanup-execution.md" }, { "id": "CL04", @@ -2199,7 +2202,7 @@ "epic": "E10", "priority": "P1", "severity": "Medium", - "status": "ready", + "status": "done", "dependencies": [], "decision_dependencies": [], "task_file": "backlog/tasks/CL04.md", @@ -2220,9 +2223,9 @@ "completed_commit": null, "blocker": null, "release_gates": [], - "integration_state": "planned", + "integration_state": "validated", "integration_base": "fbf2eb9e", - "review_notes": "Planning-only cleanup story requested 2026-10-26. Current implementation authorization is false. No implementation, tests or completion are claimed by this entry.", + "review_notes": "Focused implementation and integration checks recorded in cleanup-execution.md; no separate reviewer agent was launched.", "concrete_write_scope": [ "package.json", "scripts/docker.sh", @@ -2230,7 +2233,8 @@ "README.md", "apps/stock/README.md", "apps/stock/web-app/README.md" - ] + ], + "completion_evidence": "docs/development/cleanup-execution.md" }, { "id": "CL05", diff --git a/docs/development/backlog/tasks/CL01.md b/docs/development/backlog/tasks/CL01.md index db6346c7..d7d1fd85 100644 --- a/docs/development/backlog/tasks/CL01.md +++ b/docs/development/backlog/tasks/CL01.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript infrastructure testing. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL02.md b/docs/development/backlog/tasks/CL02.md index 30512e7d..a7182f8f 100644 --- a/docs/development/backlog/tasks/CL02.md +++ b/docs/development/backlog/tasks/CL02.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript configuration and database adapters. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL03.md b/docs/development/backlog/tasks/CL03.md index dd21e7c9..8cfeea9b 100644 --- a/docs/development/backlog/tasks/CL03.md +++ b/docs/development/backlog/tasks/CL03.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P1 / High. Complexity: M. Specialization: TypeScript resource lifecycle and concurrency. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL04.md b/docs/development/backlog/tasks/CL04.md index 2d7f3028..75ccea92 100644 --- a/docs/development/backlog/tasks/CL04.md +++ b/docs/development/backlog/tasks/CL04.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P1 / Medium. Complexity: S. Specialization: Bun/Turbo developer tooling. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL05.md b/docs/development/backlog/tasks/CL05.md index b67b6ccc..e3025d35 100644 --- a/docs/development/backlog/tasks/CL05.md +++ b/docs/development/backlog/tasks/CL05.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / High. Complexity: M. Specialization: TypeScript domain boundaries and package migration. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL06.md b/docs/development/backlog/tasks/CL06.md index 59a29698..12da4357 100644 --- a/docs/development/backlog/tasks/CL06.md +++ b/docs/development/backlog/tasks/CL06.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Shared contracts and frontend validation. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL07.md b/docs/development/backlog/tasks/CL07.md index 9f505568..66296592 100644 --- a/docs/development/backlog/tasks/CL07.md +++ b/docs/development/backlog/tasks/CL07.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Frontend HTTP contracts and retry semantics. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL08.md b/docs/development/backlog/tasks/CL08.md index a0fbbd9a..4fdaec87 100644 --- a/docs/development/backlog/tasks/CL08.md +++ b/docs/development/backlog/tasks/CL08.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: TypeScript application services and PostgreSQL transactions. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL09.md b/docs/development/backlog/tasks/CL09.md index 130160d1..293f67ba 100644 --- a/docs/development/backlog/tasks/CL09.md +++ b/docs/development/backlog/tasks/CL09.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React strategy workflows. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL10.md b/docs/development/backlog/tasks/CL10.md index 3c7e133a..77fa1c51 100644 --- a/docs/development/backlog/tasks/CL10.md +++ b/docs/development/backlog/tasks/CL10.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React experiment workflow state. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL11.md b/docs/development/backlog/tasks/CL11.md index e4e213c7..ae7e9419 100644 --- a/docs/development/backlog/tasks/CL11.md +++ b/docs/development/backlog/tasks/CL11.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: React asynchronous state and durable-run UX. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL12.md b/docs/development/backlog/tasks/CL12.md index e50f4e5d..0e514415 100644 --- a/docs/development/backlog/tasks/CL12.md +++ b/docs/development/backlog/tasks/CL12.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Medium. Complexity: M. Specialization: Compatibility cleanup and execution boundaries. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/backlog/tasks/CL13.md b/docs/development/backlog/tasks/CL13.md index b0724d33..430cd9fe 100644 --- a/docs/development/backlog/tasks/CL13.md +++ b/docs/development/backlog/tasks/CL13.md @@ -2,7 +2,7 @@ Parent epic: E10. Priority/severity: P2 / Low. Complexity: S. Specialization: React navigation and product clarity. -Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). This story defines planned work; implementation has not been requested. +Scheduling metadata: [manifest](../manifest.json). Read the [cleanup execution contract](../../CLEANUP.md#execution-contract). Implementation and validated commits were authorized after planning; scheduling and completion evidence live in the manifest. ## User story and outcome diff --git a/docs/development/cleanup-execution.md b/docs/development/cleanup-execution.md new file mode 100644 index 00000000..2cde120b --- /dev/null +++ b/docs/development/cleanup-execution.md @@ -0,0 +1,33 @@ +# Cleanup execution evidence + +The owner authorized implementation and validated commits after plan commit `4ddffa6b`. +The [manifest](backlog/manifest.json) remains the task-state authority. No additional +agents were launched; review here is a separate self-review pass, not an independent +reviewer sign-off. Financial engine code and retained financial artifacts are unchanged. + +## CL01–CL04 — Configuration, startup and commands + +- CL01 replaces the mocked normalizer and success-or-error assertions with real-schema, + no-network construction checks. Existing DI fixtures now supply valid database inputs. +- CL02 shares the core database schemas, consistently applies disable options, preserves + QuestDB port aliases/credentials, and maps PostgreSQL SSL/pool/timeouts and MongoDB URI/pool + settings to client configuration. URI parsing remains driver-owned. +- CL03 retains cleanup ownership of late initialization, rolls back settled resources, + clears startup timers and tolerates cleanup/resolution failures without replacing the + original startup error. Arbitrary hung initializers cannot be forcibly cancelled; + their final cleanup stays attached until settlement. +- CL04 adds `dev:research`, aligns infrastructure aliases on Compose v2/all four stores, + removes three nonexistent command targets and makes shell failures propagate. + +Validation: + +- `bun test libs/core/di/test/container-builder.test.ts libs/core/di/test/di.test.ts libs/core/di/test/lifecycle.test.ts test/integration/service-startup-rollback.test.ts test/integration/questdb-configuration.test.ts` — 41 pass. +- `bun test test/integration/store-configuration.test.ts` — 5 pass. +- `bun test scripts/test/workspace.test.ts` — 8 pass / 763 assertions; includes real Turbo dry runs and a fake Docker executable, with no containers started. +- `bun run --cwd libs/core/config build`, `bun run --cwd libs/core/di build`, `bun run typecheck` — pass. + +Configuration scope: core schemas retain settings used by other consumers. ServiceCache +intentionally owns DB1 and its service/global namespace; core `db`/`keyPrefix` do not override +that isolation policy. Core `ttl`, retry hints and QuestDB buffer/flush metadata are not +claims that the shared DI client supports writer/cache tuning; those adapter APIs remain +unchanged. Financial inputs, hashes and accounting were not modified. diff --git a/libs/core/config/src/schemas/database.schema.ts b/libs/core/config/src/schemas/database.schema.ts index 47fd1fd0..19101f6e 100644 --- a/libs/core/config/src/schemas/database.schema.ts +++ b/libs/core/config/src/schemas/database.schema.ts @@ -19,6 +19,7 @@ export const questdbConfigSchema = z.object({ enabled: z.boolean().default(true), host: z.string().default('localhost'), ilpPort: z.number().default(9009), + influxPort: z.number().optional(), // legacy flat alias; explicit alias wins at DI boundary httpPort: z.number().default(9000), pgPort: z.number().default(8812), database: z.string().default('questdb'), @@ -50,6 +51,7 @@ export const dragonflyConfigSchema = z.object({ port: z.number().default(6379), password: z.string().optional(), db: z.number().min(0).max(15).default(0), + username: z.string().optional(), keyPrefix: z.string().optional(), ttl: z.number().optional(), maxRetries: z.number().default(3), diff --git a/libs/core/config/src/schemas/unified-app.schema.ts b/libs/core/config/src/schemas/unified-app.schema.ts index adf94eda..33c9d3dd 100644 --- a/libs/core/config/src/schemas/unified-app.schema.ts +++ b/libs/core/config/src/schemas/unified-app.schema.ts @@ -54,7 +54,7 @@ export const unifiedAppSchema = baseAppSchema // Handle the ilpPort -> influxPort mapping for DI system const questdbConfig = { ...data.database.questdb, - influxPort: data.database.questdb.ilpPort, + influxPort: data.database.questdb.influxPort ?? data.database.questdb.ilpPort, }; data.questdb = questdbConfig; } diff --git a/libs/core/di/src/config/schemas/mongodb.schema.ts b/libs/core/di/src/config/schemas/mongodb.schema.ts index e9832d00..fd175787 100644 --- a/libs/core/di/src/config/schemas/mongodb.schema.ts +++ b/libs/core/di/src/config/schemas/mongodb.schema.ts @@ -1,9 +1,5 @@ import { z } from 'zod'; +import { mongodbConfigSchema as coreSchema } from '@stock-bot/config'; -export const mongodbConfigSchema = z.object({ - enabled: z.boolean().optional().default(true), - uri: z.string(), - database: z.string(), -}); - +export const mongodbConfigSchema = coreSchema; export type MongoDBConfig = z.infer; diff --git a/libs/core/di/src/config/schemas/postgres.schema.ts b/libs/core/di/src/config/schemas/postgres.schema.ts index 60521931..cae5a2ca 100644 --- a/libs/core/di/src/config/schemas/postgres.schema.ts +++ b/libs/core/di/src/config/schemas/postgres.schema.ts @@ -1,12 +1,5 @@ import { z } from 'zod'; +import { postgresConfigSchema as coreSchema } from '@stock-bot/config'; -export const postgresConfigSchema = z.object({ - enabled: z.boolean().optional().default(true), - host: z.string().default('localhost'), - port: z.number().default(5432), - database: z.string(), - user: z.string(), - password: z.string(), -}); - +export const postgresConfigSchema = coreSchema; export type PostgresConfig = z.infer; diff --git a/libs/core/di/src/config/schemas/questdb.schema.ts b/libs/core/di/src/config/schemas/questdb.schema.ts index 7e952203..f8f7eedf 100644 --- a/libs/core/di/src/config/schemas/questdb.schema.ts +++ b/libs/core/di/src/config/schemas/questdb.schema.ts @@ -1,14 +1,8 @@ import { z } from 'zod'; +import { questdbConfigSchema as coreQuestdbConfigSchema } from '@stock-bot/config'; -export const questdbConfigSchema = z.object({ - enabled: z.boolean().optional().default(true), - host: z.string().default('localhost'), - httpPort: z.number().optional().default(9000), - pgPort: z.number().optional().default(8812), - influxPort: z.number().optional().default(9009), - database: z.string().optional().default('questdb'), - user: z.string().optional(), - password: z.string().optional(), +// ilpPort is normalized once by the builder for the legacy client field name. +export const questdbConfigSchema = coreQuestdbConfigSchema.extend({ + influxPort: z.number().default(9009), }); - export type QuestDBConfig = z.infer; diff --git a/libs/core/di/src/config/schemas/redis.schema.ts b/libs/core/di/src/config/schemas/redis.schema.ts index fd08b8a9..6c25bb11 100644 --- a/libs/core/di/src/config/schemas/redis.schema.ts +++ b/libs/core/di/src/config/schemas/redis.schema.ts @@ -1,12 +1,5 @@ import { z } from 'zod'; +import { dragonflyConfigSchema } from '@stock-bot/config'; -export const redisConfigSchema = z.object({ - enabled: z.boolean().optional().default(true), - host: z.string().default('localhost'), - port: z.number().default(6379), - password: z.string().optional(), - username: z.string().optional(), - db: z.number().optional().default(0), -}); - +export const redisConfigSchema = dragonflyConfigSchema; export type RedisConfig = z.infer; diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index c40495a7..3294408c 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -85,7 +85,7 @@ export class ServiceContainerBuilder { return appConfigSchema.parse(finalConfig); } - private applyServiceOptions(config: Partial): AppConfig { + private applyServiceOptions(config: Partial) { // Ensure questdb config has the right field names for DI const questdbConfig = config.questdb ? { @@ -102,24 +102,33 @@ export class ServiceContainerBuilder { }; return { - redis: config.redis || { - enabled: this.options.enableCache ?? true, - host: 'localhost', - port: 6379, - db: 0, + redis: { + ...(config.redis || { + enabled: this.options.enableCache ?? true, + host: 'localhost', + port: 6379, + db: 0, + }), + enabled: this.options.enableCache !== false && (config.redis?.enabled ?? true), }, - mongodb: config.mongodb || { - enabled: this.options.enableMongoDB ?? true, - uri: '', - database: '', + mongodb: { + ...(config.mongodb || { + enabled: this.options.enableMongoDB ?? true, + uri: '', + database: '', + }), + enabled: this.options.enableMongoDB !== false && (config.mongodb?.enabled ?? true), }, - postgres: config.postgres || { - enabled: this.options.enablePostgres ?? true, - host: 'localhost', - port: 5432, - database: 'postgres', - user: 'postgres', - password: 'postgres', + postgres: { + ...(config.postgres || { + enabled: this.options.enablePostgres ?? true, + host: 'localhost', + port: 5432, + database: 'postgres', + user: 'postgres', + password: 'postgres', + }), + enabled: this.options.enablePostgres !== false && (config.postgres?.enabled ?? true), }, questdb: this.options.enableQuestDB ? questdbConfig : undefined, proxy: this.options.enableProxy @@ -196,19 +205,10 @@ export class ServiceContainerBuilder { } private transformStockBotConfig(config: UnifiedAppConfig): Partial { - // Unified config already has flat structure, just extract what we need - // Handle questdb field name mapping + // Keep the schema-normalized values intact; only the legacy port name + // differs at this adapter boundary. const questdb = config.questdb - ? { - enabled: config.questdb.enabled ?? true, - host: config.questdb.host || 'localhost', - httpPort: config.questdb.httpPort || 9000, - pgPort: config.questdb.pgPort || 8812, - influxPort: getInfluxPort(config.questdb), - database: config.questdb.database || 'questdb', - user: config.questdb.user, - password: config.questdb.password, - } + ? { ...config.questdb, influxPort: getInfluxPort(config.questdb) } : undefined; return { diff --git a/libs/core/di/src/registrations/database.registration.ts b/libs/core/di/src/registrations/database.registration.ts index 1fab80d2..cec2f794 100644 --- a/libs/core/di/src/registrations/database.registration.ts +++ b/libs/core/di/src/registrations/database.registration.ts @@ -14,18 +14,21 @@ export function registerDatabaseServices( if (config.mongodb?.enabled) { container.register({ mongoClient: asFunction(({ logger }) => { - // Parse MongoDB URI to extract components - const uriMatch = config.mongodb.uri.match( - /mongodb:\/\/(?:([^:]+):([^@]+)@)?([^:/]+):(\d+)\/([^?]+)(?:\?authSource=(.+))?/ - ); + // The driver parses URI credentials, SRV and query options. Do not + // reconstruct them with an incomplete URI regular expression. const mongoConfig = { - host: uriMatch?.[3] || 'localhost', - port: parseInt(uriMatch?.[4] || '27017'), + host: config.mongodb.host ?? 'localhost', + port: config.mongodb.port ?? 27017, database: config.mongodb.database, - username: uriMatch?.[1], - password: uriMatch?.[2] ? String(uriMatch?.[2]) : undefined, - authSource: uriMatch?.[6] || 'admin', + username: config.mongodb.user, + password: config.mongodb.password, + authSource: config.mongodb.authSource, uri: config.mongodb.uri, + poolSettings: { + maxPoolSize: config.mongodb.poolSize, + minPoolSize: 0, + maxIdleTime: 10000, + }, }; return new MongoDBClient(mongoConfig, logger); }).singleton(), @@ -45,7 +48,20 @@ export function registerDatabaseServices( port: config.postgres.port, database: config.postgres.database, username: config.postgres.user, - password: String(config.postgres.password), // Ensure password is a string + password: config.postgres.password, + ssl: { enabled: config.postgres.ssl, rejectUnauthorized: true }, + poolSettings: { + min: 0, + max: config.postgres.poolSize, + idleTimeoutMillis: config.postgres.idleTimeout, + }, + timeouts: { + connection: config.postgres.connectionTimeout, + query: 0, + statement: 0, + lock: 0, + idleInTransaction: 0, + }, }; logger.debug('PostgreSQL config:', { diff --git a/libs/core/di/src/utils/lifecycle.ts b/libs/core/di/src/utils/lifecycle.ts index 35ee7f73..c5dc6d53 100644 --- a/libs/core/di/src/utils/lifecycle.ts +++ b/libs/core/di/src/utils/lifecycle.ts @@ -25,42 +25,72 @@ export class ServiceLifecycleManager { container: AwilixContainer, timeout = 30000 ): Promise { - const initPromises: Promise[] = []; - - for (const { name, key } of this.services) { - const service = container.cradle[key] as ServiceWithLifecycle | null; - - if (service) { - const initPromise = this.initializeService(name, service); - initPromises.push( - Promise.race([ - initPromise, - this.createTimeoutPromise( - timeout, - `${name} initialization timed out after ${timeout}ms` - ), - ]) - ); - } + const started: { name: string; service: ServiceWithLifecycle; settled: boolean }[] = []; + const cancelTimers: (() => void)[] = []; + let failed = false; + try { + const work = this.services.map(async ({ name, key }) => { + const service = container.cradle[key] as ServiceWithLifecycle | null; + if (!service) {return Promise.resolve();} + const entry = { name, service, settled: false }; + started.push(entry); + // A timeout cannot cancel connect(). Keep ownership until it settles, + // including resources allocated by an initializer that later rejects. + const initialization = this.initializeService(name, service).finally(async () => { + entry.settled = true; + if (failed) {await this.cleanupOnce(name, service);} + }); + let timer: ReturnType; + const expired = new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error(`${name} initialization timed out after ${timeout}ms`)), + timeout + ); + }); + const clear = () => clearTimeout(timer); + cancelTimers.push(clear); + return Promise.race([initialization, expired]).finally(clear); + }); + await Promise.all(work); + this.logger.info('All services initialized successfully'); + } catch (error) { + failed = true; + // Only settled work can be released finally. Pending work retains the + // cleanup continuation above, so startup need not wait on a hung connect. + await Promise.allSettled( + started + .filter(entry => entry.settled) + .reverse() + .map(({ name, service }) => this.cleanupOnce(name, service)) + ); + throw error; + } finally { + for (const clear of cancelTimers) {clear();} } + } - await Promise.all(initPromises); - this.logger.info('All services initialized successfully'); + private readonly cleanup = new WeakMap>(); + + private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise { + let work = this.cleanup.get(service); + if (!work) { + work = this.shutdownService(name, service); + this.cleanup.set(service, work); + } + return work; } async shutdownServices(container: AwilixContainer): Promise { - const shutdownPromises: Promise[] = []; - - // Shutdown in reverse order + // Resolve and clean independently: one broken resolver must not prevent + // other, already connected resources from being released. for (const { name, key } of [...this.services].reverse()) { - const service = container.cradle[key] as ServiceWithLifecycle | null; - - if (service) { - shutdownPromises.push(this.shutdownService(name, service)); + try { + const service = container.cradle[key] as ServiceWithLifecycle | null; + if (service) {await this.cleanupOnce(name, service);} + } catch (error) { + this.logger.error(`Error resolving ${name} during shutdown:`, error); } } - - await Promise.allSettled(shutdownPromises); this.logger.info('All services shut down'); } @@ -93,10 +123,4 @@ export class ServiceLifecycleManager { this.logger.error(`Error shutting down ${name}:`, error); } } - - private createTimeoutPromise(timeout: number, message: string): Promise { - return new Promise((_, reject) => { - setTimeout(() => reject(new Error(message)), timeout); - }); - } } diff --git a/libs/core/di/test/container-builder.test.ts b/libs/core/di/test/container-builder.test.ts index aae8e280..6c01f031 100644 --- a/libs/core/di/test/container-builder.test.ts +++ b/libs/core/di/test/container-builder.test.ts @@ -1,443 +1,116 @@ -import { beforeEach, describe, expect, it, mock } from 'bun:test'; -import type { AppConfig } from '../src/config/schemas'; +import { describe, expect, it } from 'bun:test'; +import { ZodError } from 'zod'; +import { baseAppSchema } from '@stock-bot/config'; import { ServiceContainerBuilder } from '../src/container/builder'; -// Mock the external dependencies -mock.module('@stock-bot/config', () => ({ - toUnifiedConfig: (config: any) => { - const result: any = { ...config }; +// Production schemas and registrations, with initialization disabled: no module +// mocks, environment credentials, sockets or a second config implementation. +function configuration() { + return baseAppSchema.parse({ + name: 'di-test', + version: '1.0.0', + environment: 'test', + service: { name: 'TestService', port: 3000 }, + log: { level: 'fatal' }, + database: { + dragonfly: { enabled: false }, + mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'fixture' }, + postgres: { enabled: false, database: 'fixture', user: 'fixture', password: 'fixture' }, + questdb: { enabled: false, ilpPort: 19009 }, + }, + }); +} - // Ensure service.serviceName is set - if (result.service && !result.service.serviceName) { - result.service.serviceName = result.service.name - .replace(/([A-Z])/g, '-$1') - .toLowerCase() - .replace(/^-/, ''); +async function compose(config = configuration()) { + return new ServiceContainerBuilder().withConfig(config).skipInitialization().build(); +} + +describe('ServiceContainerBuilder production configuration', () => { + it('normalizes nested configuration and registers real services without connecting', async () => { + const container = await compose(); + try { + const config = container.resolve('config'); + expect(config.service?.serviceName).toBe('test-service'); + expect(config.mongodb.database).toBe('fixture'); + expect(config.postgres.database).toBe('fixture'); + expect(config.questdb?.influxPort).toBe(19009); + for (const name of ['cache', 'mongoClient', 'postgresClient', 'questdbClient']) { + expect(container.resolve(name)).toBeNull(); + } + expect(container.resolve('handlerRegistry')).toBeDefined(); + expect(container.resolve('handlerScanner')).toBeDefined(); + expect(container.hasRegistration('serviceContainer')).toBe(true); + } finally { + await container.dispose(); } - - // Handle questdb field mapping - if (result.questdb && result.questdb.ilpPort && !result.questdb.influxPort) { - result.questdb.influxPort = result.questdb.ilpPort; - } - - // Set default environment if not provided - if (!result.environment) { - result.environment = 'test'; - } - - // Ensure database object exists - if (!result.database) { - result.database = {}; - } - - // Copy flat configs to nested if they exist - if (result.redis) { - result.database.dragonfly = result.redis; - } - if (result.mongodb) { - result.database.mongodb = result.mongodb; - } - if (result.postgres) { - result.database.postgres = result.postgres; - } - if (result.questdb) { - result.database.questdb = result.questdb; - } - - return result; - }, -})); - -mock.module('@stock-bot/handler-registry', () => ({ - HandlerRegistry: class { - private handlers = new Map(); - private metadata = new Map(); - - register(name: string, handler: any) { - this.handlers.set(name, handler); - } - - get(name: string) { - return this.handlers.get(name); - } - - has(name: string) { - return this.handlers.has(name); - } - - clear() { - this.handlers.clear(); - this.metadata.clear(); - } - - getAll() { - return Array.from(this.handlers.entries()); - } - - getAllMetadata() { - return Array.from(this.metadata.entries()); - } - - setMetadata(key: string, meta: any) { - this.metadata.set(key, meta); - } - - getMetadata(key: string) { - return this.metadata.get(key); - } - }, -})); - -describe('ServiceContainerBuilder', () => { - let builder: ServiceContainerBuilder; - - beforeEach(() => { - builder = new ServiceContainerBuilder(); }); - describe('configuration', () => { - it('should accept AppConfig format', async () => { - const config: AppConfig = { - redis: { enabled: true, host: 'localhost', port: 6379, db: 0 }, - mongodb: { enabled: true, uri: 'mongodb://localhost', database: 'test' }, - postgres: { - enabled: true, - host: 'localhost', - port: 5432, - database: 'test', - user: 'user', - password: 'pass', - }, - service: { name: 'test-service', serviceName: 'test-service' }, - }; - - try { - const container = await builder.withConfig(config).skipInitialization().build(); - expect(container).toBeDefined(); - expect(container.hasRegistration('config')).toBe(true); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should merge partial config with defaults', async () => { - const partialConfig = { - service: { name: 'test-service', serviceName: 'test-service' }, - }; - - try { - const container = await builder.withConfig(partialConfig).skipInitialization().build(); - const resolvedConfig = container.resolve('config'); - expect(resolvedConfig.redis).toBeDefined(); - expect(resolvedConfig.mongodb).toBeDefined(); - expect(resolvedConfig.postgres).toBeDefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should handle questdb field name mapping', async () => { - const config = { - questdb: { - enabled: true, - host: 'localhost', - httpPort: 9000, - pgPort: 8812, - ilpPort: 9009, // Should be mapped to influxPort - database: 'questdb', - }, - service: { name: 'test-service', serviceName: 'test-service' }, - }; - - try { - const container = await builder.withConfig(config).skipInitialization().build(); - const resolvedConfig = container.resolve('config'); - expect(resolvedConfig.questdb?.influxPort).toBe(9009); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); + it('uses flat database settings in preference to nested ones', async () => { + const config = { + ...configuration(), + redis: { enabled: false, host: 'flat.test', port: 16379, db: 2 }, + }; + const container = await compose(config); + try { + expect(container.resolve('config').redis).toMatchObject(config.redis); + } finally { + await container.dispose(); + } }); - describe('service options', () => { - it('should enable/disable services based on options', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .enableService('enableCache', false) - .enableService('enableMongoDB', false) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.redis.enabled).toBe(false); - expect(config.mongodb.enabled).toBe(false); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should apply options using withOptions', async () => { - const options = { - enableCache: false, + it('keeps optional service defaults and honors disabled optional services', async () => { + const defaults = await compose(); + try { + expect(defaults.resolve('config').queue).toMatchObject({ + enabled: true, + workers: 1, + concurrency: 1, + }); + expect(defaults.resolve('config').browser).toMatchObject({ headless: true, timeout: 30000 }); + } finally { + await defaults.dispose(); + } + const container = await new ServiceContainerBuilder() + .withConfig(configuration()) + .withOptions({ enableQueue: false, enableBrowser: false, - skipInitialization: true, - initializationTimeout: 60000, - }; - - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .withOptions(options) - .build(); - - const config = container.resolve('config'); - expect(config.redis.enabled).toBe(false); - expect(config.queue).toBeUndefined(); - expect(config.browser).toBeUndefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should handle all service toggles', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .enableService('enablePostgres', false) - .enableService('enableQuestDB', false) - .enableService('enableProxy', false) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.postgres.enabled).toBe(false); - expect(config.questdb).toBeUndefined(); - expect(config.proxy).toBeUndefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); + enableProxy: false, + enableQuestDB: false, + }) + .skipInitialization() + .build(); + try { + const config = container.resolve('config'); + expect(config.queue).toBeUndefined(); + expect(config.browser).toBeUndefined(); + expect(config.proxy).toBeUndefined(); + expect(config.questdb).toBeUndefined(); + } finally { + await container.dispose(); + } }); - describe('initialization', () => { - it('should skip initialization when requested', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - // Container should be built without initialization - expect(container).toBeDefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should initialize services by default', async () => { - // This test would require full service setup which might fail - // So we'll just test that it attempts initialization - try { - await builder.withConfig({ service: { name: 'test' } }).build(); - // If it succeeds, that's fine - expect(true).toBe(true); - } catch (error: any) { - // Expected - services might not be available in test env - expect(error).toBeDefined(); - } - }); + it('uses the last complete configuration when the builder is reused', async () => { + const builder = new ServiceContainerBuilder().withConfig(configuration()); + const next = { ...configuration(), service: { name: 'replacement', port: 3100 } }; + const container = await builder.withConfig(next).skipInitialization().build(); + try { + expect(container.resolve('config').service?.name).toBe('replacement'); + } finally { + await container.dispose(); + } }); - describe('container registration', () => { - it('should register handler infrastructure', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test-service' } }) - .skipInitialization() - .build(); - - expect(container.hasRegistration('handlerRegistry')).toBe(true); - expect(container.hasRegistration('handlerScanner')).toBe(true); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should register service container aggregate', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - expect(container.hasRegistration('serviceContainer')).toBe(true); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - }); - - describe('config defaults', () => { - it('should provide sensible defaults for redis', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.redis).toEqual({ - enabled: true, - host: 'localhost', - port: 6379, - db: 0, - }); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should provide sensible defaults for queue', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.queue).toEqual({ - enabled: true, - workers: 1, - concurrency: 1, - enableScheduledJobs: true, - defaultJobOptions: { - attempts: 3, - backoff: { type: 'exponential', delay: 1000 }, - removeOnComplete: 100, - removeOnFail: 100, - }, - }); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should provide sensible defaults for browser', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.browser).toEqual({ - headless: true, - timeout: 30000, - }); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - }); - - describe('builder chaining', () => { - it('should support method chaining', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .enableService('enableCache', true) - .enableService('enableQueue', false) - .withOptions({ initializationTimeout: 45000 }) - .skipInitialization(true) - .build(); - - expect(container).toBeDefined(); - const config = container.resolve('config'); - expect(config.redis.enabled).toBe(true); - expect(config.queue).toBeUndefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - - it('should allow multiple withConfig calls with last one winning', async () => { - const config1 = { - service: { name: 'service1' }, - redis: { enabled: true, host: 'host1', port: 6379, db: 0 }, - }; - const config2 = { - service: { name: 'service2' }, - redis: { enabled: true, host: 'host2', port: 6380, db: 1 }, - }; - - try { - const container = await builder - .withConfig(config1) - .withConfig(config2) - .skipInitialization() - .build(); - - const config = container.resolve('config'); - expect(config.service.name).toBe('service2'); - expect(config.redis.host).toBe('host2'); - expect(config.redis.port).toBe(6380); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); - }); - - describe('error handling', () => { - it('should validate config before building', async () => { - const invalidConfig = { - redis: { enabled: 'not-a-boolean' }, // Invalid type - service: { name: 'test' }, - }; - - try { - await builder.withConfig(invalidConfig as any).build(); - // If we get here without error, that's fine in test env - expect(true).toBe(true); - } catch (error: any) { - // Schema validation error is expected - expect(error.name).toBe('ZodError'); - } - }); - }); - - describe('service container resolution', () => { - it('should properly map services in serviceContainer', async () => { - try { - const container = await builder - .withConfig({ service: { name: 'test' } }) - .skipInitialization() - .build(); - - // We need to check that serviceContainer would properly map services - // but we can't resolve it without all dependencies - // So we'll just verify the registration exists - const registrations = container.registrations; - expect(registrations.serviceContainer).toBeDefined(); - } catch (error: any) { - // If validation fails, that's OK for this test - expect(error).toBeDefined(); - } - }); + it('rejects invalid settings and missing required app fields with schema errors', () => { + expect(() => + new ServiceContainerBuilder().withConfig({ + ...configuration(), + redis: { enabled: 'wrong' }, + } as never) + ).toThrow(ZodError); + expect(() => + new ServiceContainerBuilder().withConfig({ service: { name: 'incomplete' } } as never) + ).toThrow(ZodError); }); }); diff --git a/libs/core/di/test/di.test.ts b/libs/core/di/test/di.test.ts index fb17e74f..3d9be3b8 100644 --- a/libs/core/di/test/di.test.ts +++ b/libs/core/di/test/di.test.ts @@ -18,6 +18,9 @@ describe('Dependency Injection', () => { const config = { name: 'test-service', version: '1.0.0', + database: { + mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'test' }, + }, service: { name: 'test-service', type: 'WORKER' as const, @@ -41,6 +44,9 @@ describe('Dependency Injection', () => { const config = { name: 'test-service', version: '1.0.0', + database: { + mongodb: { enabled: false, uri: 'mongodb://localhost/test', database: 'test' }, + }, service: { name: 'test-service', type: 'WORKER' as const, diff --git a/package.json b/package.json index f09201d0..f31fedac 100644 --- a/package.json +++ b/package.json @@ -6,6 +6,7 @@ "type": "module", "scripts": { "dev": "turbo run dev", + "dev:research": "turbo run dev --filter=@stock-bot/web-api --filter=@stock-bot/orchestrator --filter=@stock-bot/web-app", "build": "./scripts/build-all.sh", "build:all:clean": "./scripts/build-all.sh --clean", "build:all:verbose": "./scripts/build-all.sh --verbose", @@ -55,19 +56,16 @@ "docker:start": "./scripts/docker.sh start", "docker:stop": "./scripts/docker.sh stop", "docker:restart": "./scripts/docker.sh restart", - "db:setup-ib": "bun run database/postgres/scripts/setup-ib.ts", - "db:init": "bun run database/postgres/scripts/init.ts", "docker:status": "./scripts/docker.sh status", "docker:logs": "./scripts/docker.sh logs", "docker:reset": "./scripts/docker.sh reset", "docker:admin": "./scripts/docker.sh admin", "docker:monitoring": "./scripts/docker.sh monitoring", - "infra:up": "docker-compose up -d dragonfly postgres questdb mongodb", - "infra:down": "docker-compose down", - "infra:reset": "docker-compose down -v && docker-compose up -d dragonfly postgres questdb mongodb", + "infra:up": "./scripts/docker.sh start", + "infra:down": "./scripts/docker.sh stop", + "infra:reset": "./scripts/docker.sh reset", "dev:full": "npm run infra:up && npm run docker:admin && turbo run dev", - "dev:clean": "npm run infra:reset && npm run dev:full", - "proxy": "bun run ./apps/data-ingestion/src/proxy-demo.ts" + "dev:clean": "npm run infra:reset && npm run dev:full" }, "workspaces": [ "libs/*", diff --git a/scripts/docker.sh b/scripts/docker.sh index bf944987..36ee2385 100755 --- a/scripts/docker.sh +++ b/scripts/docker.sh @@ -1,6 +1,7 @@ #!/bin/bash # Trading Bot Docker Management Script +set -euo pipefail # Colors for output RED='\033[0;31m' @@ -79,18 +80,18 @@ fi # Set up compose files if [ "$DEV" = true ]; then - COMPOSE_FILES="-f docker-compose.yml -f docker-compose.dev.yml" + COMPOSE_FILES=(-f docker-compose.yml -f docker-compose.dev.yml) else - COMPOSE_FILES="-f docker-compose.yml" + COMPOSE_FILES=(-f docker-compose.yml) fi case "$ACTION" in "start") echo -e "${GREEN}🚀 Starting Trading Bot infrastructure...${NC}" if [ -n "$SERVICE" ]; then - docker-compose $COMPOSE_FILES up -d "$SERVICE" + docker compose "${COMPOSE_FILES[@]}" up -d "$SERVICE" else - docker-compose $COMPOSE_FILES up -d dragonfly postgres questdb + docker compose "${COMPOSE_FILES[@]}" up -d dragonfly postgres questdb mongodb fi echo -e "${GREEN}✅ Infrastructure started!${NC}" echo "" @@ -105,9 +106,9 @@ case "$ACTION" in "stop") echo -e "${YELLOW}🛑 Stopping Trading Bot infrastructure...${NC}" if [ -n "$SERVICE" ]; then - docker-compose $COMPOSE_FILES stop "$SERVICE" + docker compose "${COMPOSE_FILES[@]}" stop "$SERVICE" else - docker-compose $COMPOSE_FILES down + docker compose "${COMPOSE_FILES[@]}" down fi echo -e "${GREEN}✅ Infrastructure stopped!${NC}" ;; @@ -115,16 +116,16 @@ case "$ACTION" in "restart") echo -e "${YELLOW}🔄 Restarting Trading Bot infrastructure...${NC}" if [ -n "$SERVICE" ]; then - docker-compose $COMPOSE_FILES restart "$SERVICE" + docker compose "${COMPOSE_FILES[@]}" restart "$SERVICE" else - docker-compose $COMPOSE_FILES restart + docker compose "${COMPOSE_FILES[@]}" restart fi echo -e "${GREEN}✅ Infrastructure restarted!${NC}" ;; "status") echo -e "${CYAN}📊 Trading Bot Infrastructure Status:${NC}" - docker-compose $COMPOSE_FILES ps + docker compose "${COMPOSE_FILES[@]}" ps echo "" echo -e "${CYAN}🔍 Health Checks:${NC}" docker ps --filter "name=trading-bot" --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" @@ -133,10 +134,10 @@ case "$ACTION" in "logs") if [ -n "$SERVICE" ]; then echo -e "${CYAN}📋 Logs for $SERVICE:${NC}" - docker-compose $COMPOSE_FILES logs -f "$SERVICE" + docker compose "${COMPOSE_FILES[@]}" logs -f "$SERVICE" else echo -e "${CYAN}📋 All service logs:${NC}" - docker-compose $COMPOSE_FILES logs -f + docker compose "${COMPOSE_FILES[@]}" logs -f fi ;; @@ -144,9 +145,9 @@ case "$ACTION" in echo -e "${RED}⚠️ Resetting Trading Bot infrastructure (will delete all data)...${NC}" read -p "Are you sure? Type 'yes' to confirm: " confirm if [ "$confirm" = "yes" ]; then - docker-compose $COMPOSE_FILES down -v + docker compose "${COMPOSE_FILES[@]}" down -v echo -e "${YELLOW}🗑️ Volumes removed${NC}" - docker-compose $COMPOSE_FILES up -d dragonfly postgres questdb + docker compose "${COMPOSE_FILES[@]}" up -d dragonfly postgres questdb mongodb echo -e "${GREEN}✅ Infrastructure reset complete!${NC}" else echo -e "${YELLOW}❌ Reset cancelled${NC}" @@ -155,7 +156,7 @@ case "$ACTION" in "admin") echo -e "${GREEN}🔧 Starting admin interfaces...${NC}" - docker-compose $COMPOSE_FILES up -d redis-insight pgadmin + docker compose "${COMPOSE_FILES[@]}" up -d redis-insight pgadmin echo -e "${GREEN}✅ Admin interfaces started!${NC}" echo "" echo -e "${CYAN}🔗 Admin Access:${NC}" @@ -167,7 +168,7 @@ case "$ACTION" in "monitoring") echo -e "${GREEN}📊 Starting monitoring stack...${NC}" - docker-compose $COMPOSE_FILES up -d prometheus grafana loki + docker compose "${COMPOSE_FILES[@]}" up -d prometheus grafana loki echo -e "${GREEN}✅ Monitoring started!${NC}" echo "" echo -e "${CYAN}🔗 Monitoring Access:${NC}" diff --git a/scripts/test/workspace.test.ts b/scripts/test/workspace.test.ts index e5f741b5..c296d8f0 100644 --- a/scripts/test/workspace.test.ts +++ b/scripts/test/workspace.test.ts @@ -1,4 +1,5 @@ -import { existsSync, readFileSync } from 'node:fs'; +import { existsSync, readFileSync, mkdtempSync, writeFileSync, chmodSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, expect, it } from 'bun:test'; @@ -48,6 +49,47 @@ describe('workspace verification', () => { expect(planned.has('@stock-bot/stock-app#build')).toBe(false); }); + it('research development selects only the API, worker and web application', () => { + const result = Bun.spawnSync([process.execPath, 'run', 'dev:research', '--dry=json'], { + cwd: root, env: { ...process.env, TURBO_TELEMETRY_DISABLED: '1' }, + }); + expect(result.exitCode).toBe(0); + const plan = JSON.parse(new TextDecoder().decode(result.stdout)); + expect(plan.tasks.filter((task: { task: string }) => task.task === 'dev') + .map((task: { taskId: string }) => task.taskId).sort()).toEqual([ + '@stock-bot/orchestrator#dev', '@stock-bot/web-api#dev', '@stock-bot/web-app#dev', + ]); + expect(plan.tasks.every((task: { task: string }) => ['build', 'dev'].includes(task.task))).toBe(true); + }); + + it('root file-based commands point to existing scripts', () => { + for (const command of Object.values(manifest.scripts) as string[]) { + const target = command.match(/^(?:bun run |)(\.?\/?(?:scripts|database|apps)\/[^ ]+)/)?.[1]; + if (target) expect(existsSync(join(root, target))).toBe(true); + } + }); + + it('infrastructure aliases use the same stores and propagate Compose failures', () => { + expect(manifest.scripts['infra:up']).toBe(manifest.scripts['docker:start']); + const temporary = mkdtempSync(join(tmpdir(), 'stock-bot-compose-test-')); + try { + const docker = join(temporary, 'docker'); + writeFileSync(docker, '#!/bin/sh\nprintf "%s\\n" "$@"\nexit "${COMPOSE_TEST_EXIT:-0}"\n'); + chmodSync(docker, 0o755); + const invoke = (code: string) => Bun.spawnSync(['bash', 'scripts/docker.sh', 'start'], { + cwd: root, env: { ...process.env, PATH: `${temporary}:${process.env.PATH}`, COMPOSE_TEST_EXIT: code }, + }); + const success = invoke('0'); + expect(success.exitCode).toBe(0); + const output = new TextDecoder().decode(success.stdout); + expect(output).toContain('compose\n-f\ndocker-compose.yml\nup\n-d\ndragonfly\npostgres\nquestdb\nmongodb'); + expect(output).not.toContain('down'); + const failed = invoke('23'); + expect(failed.exitCode).toBe(23); + expect(new TextDecoder().decode(failed.stdout)).not.toContain('Infrastructure started!'); + } finally { rmSync(temporary, { recursive: true, force: true }); } + }); + it('each TypeScript workspace has source inputs covered by the root type check', () => { const checked = new Set( config(join(root, 'tsconfig.check.json')).fileNames.map(file => resolve(file)) diff --git a/test/integration/service-startup-rollback.test.ts b/test/integration/service-startup-rollback.test.ts new file mode 100644 index 00000000..86d30684 --- /dev/null +++ b/test/integration/service-startup-rollback.test.ts @@ -0,0 +1,96 @@ +import type { AwilixContainer } from 'awilix'; +import { expect, mock, test } from 'bun:test'; +import { ServiceLifecycleManager } from '../../libs/core/di/src/utils/lifecycle'; + +function container(cradle: object) { + return { cradle } as AwilixContainer; +} +function deferred() { + let resolve!: () => void; + let reject!: (error: Error) => void; + const promise = new Promise((yes, no) => { + resolve = yes; + reject = no; + }); + return { promise, resolve, reject }; +} + +test('failed startup rolls back settled resources and preserves the original error', async () => { + const failure = new Error('mongo failed'); + const disconnect = mock(async () => {}); + const manager = new ServiceLifecycleManager(); + const c = container({ + cache: { connect: async () => {}, disconnect }, + mongoClient: { + connect: async () => { + throw failure; + }, + disconnect: async () => { + throw new Error('cleanup failed'); + }, + }, + }); + await expect(manager.initializeServices(c)).rejects.toBe(failure); + expect(disconnect).toHaveBeenCalledTimes(1); + await manager.shutdownServices(c); + expect(disconnect).toHaveBeenCalledTimes(1); +}); + +test('resolver failure retains ownership of initialization already in flight', async () => { + const late = deferred(); + const disconnect = mock(async () => {}); + const failure = new Error('resolver failed'); + const c = container({ + cache: { connect: () => late.promise, disconnect }, + get mongoClient() { + throw failure; + }, + }); + await expect(new ServiceLifecycleManager().initializeServices(c)).rejects.toBe(failure); + expect(disconnect).not.toHaveBeenCalled(); + late.resolve(); + await Bun.sleep(0); + expect(disconnect).toHaveBeenCalledTimes(1); +}); + +test('timeout returns promptly and cleans up a late successful initializer', async () => { + const late = deferred(); + const disconnect = mock(async () => {}); + const c = container({ cache: { connect: () => late.promise, disconnect } }); + await expect(new ServiceLifecycleManager().initializeServices(c, 5)).rejects.toThrow( + 'cache initialization timed out' + ); + late.resolve(); + await Bun.sleep(0); + expect(disconnect).toHaveBeenCalledTimes(1); +}); + +test('late failed initialization also releases resources allocated before failure', async () => { + const late = deferred(); + const disconnect = mock(async () => {}); + const c = container({ cache: { connect: () => late.promise, disconnect } }); + await expect(new ServiceLifecycleManager().initializeServices(c, 5)).rejects.toThrow('timed out'); + late.reject(new Error('late failure')); + await Bun.sleep(0); + expect(disconnect).toHaveBeenCalledTimes(1); +}); + +test('successful initialization clears timeout handles immediately', async () => { + const child = Bun.spawn( + [ + process.execPath, + '-e', + ` + import {ServiceLifecycleManager} from './libs/core/di/src/utils/lifecycle.ts'; + await new ServiceLifecycleManager().initializeServices({cradle:{cache:{connect:async()=>{}}}}, 30000); + `, + ], + { stdout: 'ignore', stderr: 'pipe' } + ); + const timer = setTimeout(() => child.kill(), 3000); + try { + expect(await child.exited).toBe(0); + } finally { + clearTimeout(timer); + } +}); diff --git a/test/integration/store-configuration.test.ts b/test/integration/store-configuration.test.ts new file mode 100644 index 00000000..8b18945b --- /dev/null +++ b/test/integration/store-configuration.test.ts @@ -0,0 +1,129 @@ +import { expect, test } from 'bun:test'; +import type { PoolConfig } from 'pg'; +import { baseAppSchema } from '@stock-bot/config'; +import { ServiceContainerBuilder } from '../../libs/core/di/src/container/builder'; + +function configuration(enabled = true) { + return baseAppSchema.parse({ + name: 'store-configuration', + version: '1.0.0', + service: { name: 'store-configuration', port: 3000 }, + log: { level: 'fatal' }, + database: { + dragonfly: { enabled, host: 'redis.test', password: 'fixture', db: 3 }, + mongodb: { + enabled, + uri: 'mongodb://fixture:fixture@mongo.test:27017/store?authSource=admin', + database: 'store', + poolSize: 17, + }, + postgres: { + enabled, + host: 'pg.test', + port: 15432, + database: 'store', + user: 'fixture', + password: 'fixture', + ssl: true, + poolSize: 19, + connectionTimeout: 4321, + idleTimeout: 8765, + }, + questdb: { enabled: false }, + }, + }); +} + +for (const enabled of [true, false]) { + test(`explicit disable options win over enabled=${enabled} configuration`, async () => { + const c = await new ServiceContainerBuilder() + .withConfig(configuration(enabled)) + .withOptions({ enableCache: false, enableMongoDB: false, enablePostgres: false }) + .skipInitialization() + .build(); + try { + for (const name of ['cache', 'mongoClient', 'postgresClient']) + expect(c.resolve(name)).toBeNull(); + const config = c.resolve('config'); + expect(config.redis.enabled).toBe(false); + expect(config.mongodb.enabled).toBe(false); + expect(config.postgres.enabled).toBe(false); + } finally { + await c.dispose(); + } + }); +} + +test('enable options do not override disabled configurations', async () => { + const c = await new ServiceContainerBuilder() + .withConfig(configuration(false)) + .withOptions({ enableCache: true, enableMongoDB: true, enablePostgres: true }) + .skipInitialization() + .build(); + try { + for (const name of ['cache', 'mongoClient', 'postgresClient']) + expect(c.resolve(name)).toBeNull(); + } finally { + await c.dispose(); + } +}); + +test('PostgreSQL nondefault fields reach wire configuration and Mongo retains URI/pool settings', async () => { + const c = await new ServiceContainerBuilder() + .withConfig(configuration()) + .skipInitialization() + .build(); + try { + const wire = ( + c.resolve('postgresClient') as unknown as { buildPoolConfig(): PoolConfig } + ).buildPoolConfig(); + expect(wire).toMatchObject({ + host: 'pg.test', + port: 15432, + database: 'store', + user: 'fixture', + password: 'fixture', + ssl: { rejectUnauthorized: true }, + max: 19, + connectionTimeoutMillis: 4321, + idleTimeoutMillis: 8765, + }); + const mongo = c.resolve('mongoClient') as unknown as { + config: { uri: string; poolSettings: { maxPoolSize: number } }; + }; + expect(mongo.config.uri).toBe(configuration().database!.mongodb!.uri); + expect(mongo.config.poolSettings.maxPoolSize).toBe(17); + } finally { + await c.dispose(); + } +}); + +test('flat QuestDB alias takes precedence without discarding credentials or schema settings', async () => { + const c = await new ServiceContainerBuilder() + .withConfig({ + ...configuration(false), + questdb: { + enabled: true, + host: 'quest.test', + ilpPort: 19009, + influxPort: 29009, + user: 'fixture', + password: 'fixture', + bufferSize: 1234, + flushInterval: 3456, + }, + } as never) + .skipInitialization() + .build(); + try { + expect(c.resolve('config').questdb).toMatchObject({ + influxPort: 29009, + bufferSize: 1234, + flushInterval: 3456, + user: 'fixture', + password: 'fixture', + }); + } finally { + await c.dispose(); + } +});