Compare commits

...

17 Commits

Author SHA1 Message Date
kjh2064 11e8a3c7f8 docs: final file-count status for this session's cleanup thread
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 23s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 11s
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Failing after 10s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 13s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 13s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 2m28s
4,523 -> 1,687 (77% of the 2,200 budget). Records the
test_kis_data_collection_v1.py import fix and the golden-stub removal
reasoning, and explicitly notes that further file-count reduction
isn't warranted right now - the gate has real headroom and continuing
to hunt for deletions has more downside (accidentally cutting
something live) than upside at this point.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 15:02:18 +09:00
kjh2064 65e3769eb2 chore: remove 174 non-executing golden test stubs (M3 parity now done)
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 14s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 24s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Failing after 10s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 11s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 11s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 2m26s
spec/60_quant_engine_wbs.yaml's own QE-M0-06 note explicitly deferred
this: "골든 테스트 174개는 실행되지 않는 placeholder... 삭제는 M3
패리티 대체 후" (the 174 golden tests are non-executing placeholders;
delete once M3 parity replaces them). Confirmed all 5 M3 tasks
(point-in-time reader, factor parity calculator, SS001 composite
score, PipelineOrchestrator honesty, score FE) are status=DONE.

Verified before deleting, not just inferred:
- No .gitea/workflows/*.yml references tests/golden/generated/ - CI
  only runs specific named files under tests/unit/.
- tools/validate_golden_coverage_100.py's coverage ratio is computed
  from spec/formula_golden_cases_v2-v4.yaml entries, not by counting
  these stub files (its own code comment says so).
- Sampled a stub: trivial always-true assertions, one even internally
  broken (`assert outputs` on an empty list) - proof it never actually
  ran.

Re-ran the coverage validator, QE-M0-06's WBS verdict, and full pytest
collection after deletion - all still pass/clean. tests/golden/
itself (README.md, formula_registry_v2_cases.yaml) is untouched, only
the generated/ subdirectory is gone.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 15:01:20 +09:00
kjh2064 4dd6098619 fix: broken import in test_kis_data_collection_v1.py (same root cause as F8)
Same class of bug as the earlier tools/run_kis_data_collection_v1.py
fix this session: the module moved to src/quant_engine/deprecated/
but this test still imported the old path. Found by actually running
pytest --collect-only on tests/unit/ (110 tests collect cleanly now,
was failing at 1 error before).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 14:34:01 +09:00
kjh2064 70e49f0556 docs: update handoff notes with orphan cleanup and xlsx findings
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 13s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 22s
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Failing after 11s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 11s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 10s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 1m51s
Records the two-pass orphan script cleanup (74 files total across two
commits) and the methodology gap that mattered (check output-path
references, not just script-name references). Also records that
GatherTradingData.json (the project's own designated canonical seed,
per docs/GATHERTRADINGDATA_XLSX_DECISION) is available from the
production server even without the untracked .xlsx, but the release
DAG's convert_xlsx node has no skip-if-output-exists logic, and the
remaining 10 blocked WBS verdicts need a running QuantEngine.Web +
Playwright evidence run against real DB price history, not just the
seed JSON - not attempted this session.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 14:29:49 +09:00
kjh2064 73572b6211 chore: remove 40 more orphaned one-off scripts from tools/
Second pass over the 47 lower-confidence orphan candidates held back
from the earlier 34-file cleanup. This time checked two signals, not
one: (1) is the script's own filename referenced anywhere, and (2)
does the script's own Temp/*.json output get read by any other file
(a script can be "orphaned" by name but still load-bearing if
something else consumes what it produces).

7 of the 47 failed check (2) - their outputs (outcome_ledger_v1.json,
pre_distribution_early_warning_v3.json, shadow_ledger_v1.json,
calibration_registry_v1.json, final_execution_decision_v4.json,
live_outcome_ledger_v1.json, final_decision_packet_v2.json) are read
by other tools even though the producing script's name never appears
elsewhere - kept those 7 in place.

The remaining 40 (WBS-ticket-tagged one-offs: wbs81/92/93/95/96_*,
build_p0-p6_*; and misc build_*/validate_* diagnostics with no
external reference by name or by output) were deleted. Re-ran the
full-repo reference search (zero hits) and quick-mode release DAG +
WBS validator afterward - failure set is unchanged (same 10
tasks already known blocked on missing live trading data / a running
web app + Playwright, unrelated to this deletion).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 14:29:08 +09:00
kjh2064 2439d5e24d docs: record the Temp/ evidence-cache incident in the handoff notes
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 13s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 23s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 12s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 11s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 9s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 1m50s
Entropy cleanup earlier today deleted all of Temp/, which turned out
to include WBS verification evidence (Temp/evidence/*/verdict.json),
not just build cache. Documents what broke, what got recovered, and
what remains genuinely blocked on missing trading data - so this
doesn't get rediscovered from scratch next time.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 14:12:42 +09:00
kjh2064 977167a0db chore: remove 34 orphaned one-off scripts from tools/
Systematic scan (not manual per-file review): for every *.py under
tools/ and src/quant_engine/, searched the entire tracked repo for
its filename stem outside itself (code, docs, spec, CI workflows,
tests). 81 of 619 files had zero references anywhere. Deleting all
81 in one pass was judged too risky - some could be intentional
manual-run utilities that just don't get named by other files - so
this commit only removes the two highest-confidence tiers, 34 files:

- Superseded DB init/fix/load scripts, most with an explicit "_v2"/
  "_correct"/"_properly" sibling that replaced them (e.g.
  load_from_xlsx.py -> load_from_xlsx_correct.py,
  initialize_database.py -> initialize_database_v2.py). Verified via
  `git log` that both members of each pair were last touched the same
  day (2026-06-23) and never again - abandoned mid-iteration, not
  live tooling.
- Ad-hoc test/debug scripts sitting in tools/ instead of tests/
  (test_api_components.py, test_build_ui_state*.py, diagnose_api_error.py,
  verify_*.py, validate_json_conversion.py) - one-off interactive
  debugging session artifacts.

Re-ran the full-repo reference search after deletion (zero hits) and
the quick-mode release DAG + WBS validator (both still pass) to confirm
nothing references these files. The other 47 orphan candidates (WBS-
ticket-tagged one-offs and misc build_*/validate_* scripts) are left
in place pending further review - some may be intentional manual
utilities the automated reference scan can't distinguish from dead code.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 14:12:09 +09:00
kjh2064 fa0da0b159 docs: add session handoff notes for the 2026-07-30 strategic audit
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 12s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 26s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 13s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 11s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 10s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 1m56s
Adds docs/SESSION_HANDOFF_2026-07-30.md with what a future session
needs that isn't derivable from git log: open threads (release DAG
unverified end-to-end, engine_history/quantengine schema collision
left as-is, OpenDART/KRX not yet wired into any workflow) and traps
hit this session worth not repeating (archive-before-grepping
tools/spec/tests, DbUp ordinal sort, runtime/ is tracked history not
scratch space, two Pythons on this machine, entropy audit counting
local build noise). Pointed to it from CLAUDE.md's Known Issues list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 13:43:32 +09:00
kjh2064 823a9a64e2 fix: repository entropy audit was measuring build noise, not repo bloat
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 13s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 23s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 13s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 10s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 10s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 1m56s
audit_repository_entropy_v2.py (the "과유불급" file-count gate in the
release DAG) was failing: 4,523 files against a 2,200 budget. Traced
it down before touching anything - the audit's _EXCLUDE_DIRS list
predates several directories this repo's own .gitignore already
excludes (Temp/, dist/, outputs/, publish_artifact/, **/bin/,
**/obj/, test-results/), so every local dotnet build/test run
inflates the count with disposable, zero-git-impact build artifacts.
Verified via `git ls-files` that none of the ~2,400 files in those
paths were tracked, versus runtime/, archive_db/, backups/, and
artifacts/ (246 files, all tracked, all genuine audit-trail/history
data) which must NOT be touched.

Cleaned the untracked build/scratch artifacts from disk and added the
missing directories to _EXCLUDE_DIRS so the metric can't be
re-inflated by normal local development again. Gate now passes at
1,934 files with real headroom, without deleting a single tracked
file. Verified full .NET build still succeeds after removing all
bin/obj folders (clean rebuild, 0 errors/warnings).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 13:38:42 +09:00
kjh2064 0a2f0eb4a1 fix: un-archive two docs that CI/release-gate validators depend on
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 15s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 25s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 12s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 11s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 12s
Workflow Lint & Validation / Lint All Workflow Files (push) Failing after 13s
Workflow Lint & Validation / Validate Secrets Contract (push) Successful in 6s
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 2m5s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Workflow Lint & Validation / Notify Lint Results (push) Failing after 1s
Qualitative Sell Strategy Pipeline / Validate Qualitative Sell Strategy (push) Failing after 7s
Qualitative Sell Strategy Pipeline / Notify Strategy Validation Status (push) Failing after 1s
docs/ROADMAP_WBS.md and docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md were
archived in an earlier commit today as "superseded planning docs," but
that judgment only checked CLAUDE.md/README/other docs for references
- not the actual validator scripts, spec YAMLs, and unit tests that
drive the release gate. Both paths turn out to be load-bearing:

- docs/ROADMAP_WBS.md is read directly by
  tools/validate_quant_engine_wbs_v1.py,
  tools/validate_platform_transition_wbs_v1.py,
  tests/unit/test_validate_quant_engine_wbs_v1.py, and referenced by
  spec/60_quant_engine_wbs.yaml and others.
- docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md is read by
  tools/validate_enterprise_crud_specification_v1.py, which runs as
  the "Enterprise Contract Parity Test" step in
  .gitea/workflows/ci-frontend.yml.

Moved both back to their original path, replaced the stale "ARCHIVED"
banner with a note explaining why they can't be archived without first
updating the validators, and fixed the 4 doc cross-references that had
been repointed at docs/archive/. Verified all three affected validators
now exit 0 by actually running them locally.

The other 9 docs archived earlier today (5 CI/CD docs + CICD_ROADMAP.md,
EXECUTION_PLAN_PHASE0_CLOSEOUT_AND_PHASE1_KICKOFF.md,
MODERNIZATION_ROADMAP_VISUAL.md,
MODERNIZATION_STRATEGY_ROADMAP_2026-2027.md) were checked against the
same grep sweep (*.py/*.yaml/*.yml/*.js/*.ts/*.cs/*.json, whole repo)
and have zero references outside markdown - those archivals stand.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 12:36:20 +09:00
kjh2064 8dabffc08a chore: commit pre-existing untracked work + finish archived-doc notes
Commits work that predated this session and was sitting untracked:
qualitative sell strategy module (src/quant_engine), the t20 outcome
ledger cron workflow, the QuantEngine masterpiece roadmap doc, a WBS
execution yaml, and shared Razor Pages partials (page header, delete
confirm modal) with their view models. Verified these build clean
(0 errors, 0 warnings) before committing.

Also includes the "ARCHIVED" header notes on 6 docs archived in the
previous commit - the git-mv landed there, but the note text itself
was missed from that commit's staged file list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 12:21:32 +09:00
kjh2064 88e3d58664 docs: archive superseded roadmap/WBS docs, fix broken install command, retire stale files
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 18s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 26s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 12s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 12s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 9s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 1m56s
Archives 6 more superseded planning docs to docs/archive/ (ROADMAP_WBS.md,
MODERNIZATION_ROADMAP_VISUAL.md, MODERNIZATION_STRATEGY_ROADMAP_2026-2027.md,
ROADMAP_ENTERPRISE_TEMPLATES_WBS.md, EXECUTION_PLAN_PHASE0_CLOSEOUT_AND_PHASE1_KICKOFF.md,
CICD_ROADMAP.md), each replaced by a current source of truth (CLAUDE.md,
docs/MIGRATION_STATUS.md, or the OMS·WMS·ERP spec/playbook), and repoints
4 files that linked to the pre-archive path.

Fixes README's top-of-file install instructions and package.json's
"ops:dev" script, both of which pointed at core_satellite_collector.js -
a file that has never existed anywhere in this repo's git history. The
real, working entry point (tools/run_kis_data_collection_v1.py /
npm run ops:data-collect) was already correctly documented further
down the same README.

Also finishes retiring pre-existing stale state that predates this
session: removes the superseded deploy-prod.yml.backup, completes the
already-in-progress removal of the old src/client/ Vue+AG-Grid
prototype (superseded by src/frontend/), and untracks
test-results/.last-run.json (Playwright's own run-metadata file,
regenerated every test run - shouldn't be version controlled).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:50:25 +09:00
kjh2064 477bd693c1 fix: unify OpenDART env var name with Gitea Secrets; add missed migration header notes
tools/ingest_fundamental_raw.py read DART_API_KEY, but the Gitea Secret
is registered as OPENDART_OPENAPI_KEY, and no workflow bridges the two
(none currently invoke this script). Renamed the code side to match
the secret name directly rather than adding a mapping layer, so
whenever this gets wired into a workflow it just works. Updated the
matching README setup instructions.

Also includes the V9/V10 migration header explanations (why they were
renamed from V003/V004) that were written earlier but missed from the
previous commit's file list.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:39:48 +09:00
kjh2064 279d1760ef fix: migration ordering bug that could block fresh-DB deploys
V004_normalize_snapshots_schema.sql had an unguarded FK to a table V2
creates. Under DbUp's default ordinal filename sort, the zero-padded
"V003_"/"V004_" migrations sorted before "V1__", so on a brand-new
database V004 would hard-fail on that FK and abort every migration
after it - V1 through V8 would never run. Confirmed via production
that neither V003 nor V004 had ever actually applied.

Fix: renamed them to V9__/V10__ and added MigrationScriptNameComparer,
which sorts DbUp scripts by numeric V{n} value instead of raw string
order, so double-digit versions can never again sort ahead of earlier
single-digit ones. Added regression tests for both the fixed case and
the original bug shape.

Also updates docs/db/quantengine.dbml (renamed migrations, and closes
out the engine_history/quantengine table-name-collision question -
both schemas are live, backing different code paths, not duplicates)
and CLAUDE.md (migration ordering fix, KIS/OpenDART/KRX credential
env-var-name reference, including a CI secret/env-var name mismatch
found for OpenDART that still needs a decision).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:36:00 +09:00
kjh2064 70824c2afb fix: security, data-integrity, and doc-drift findings from repo audit
Consolidates duplicate KIS API client implementations (governance tests
were exercising an unused class instead of the one actually running in
production), closes a SQL injection path in the DB admin page, fixes a
migration that used MySQL-only syntax and had never actually applied
(confirmed against production), resyncs docs/db/quantengine.dbml with
all migrations, and removes a duplicate OMS·WMS·ERP frontend tree in
favor of src/frontend/. Also corrects several unverifiable/inflated
claims in the OMS planning docs and realigns CI/CD and architecture
documentation with what's actually in the repo.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-30 11:20:02 +09:00
kjh2064 99943d9871 Merge pull request 'Add OMS WMS ERP platform' (#16) from agent/oms-wms-erp into main
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (push) Failing after 24s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (push) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (push) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (push) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (push) Has been skipped
Validators (Pushes and Pull Requests) / UI & Storage Validation (push) Failing after 12s
Validators (Pushes and Pull Requests) / Database & Schema Validation (push) Successful in 12s
Validators (Pushes and Pull Requests) / Security & Secrets (push) Successful in 12s
Validators (Pushes and Pull Requests) / CI Workflow Lint (push) Failing after 11s
Validators (Pushes and Pull Requests) / Notify PR Results (push) Has been skipped
Frontend CI Pipeline / ci-frontend-8-steps (push) Failing after 2m29s
Add OMS WMS ERP platform
2026-07-27 00:46:36 +09:00
kjh2064 b34b0dd7d6 Add OMS WMS ERP platform
Validators (Pushes and Pull Requests) / UI & Storage Validation (pull_request) Failing after 12s
Validators (Pushes and Pull Requests) / Database & Schema Validation (pull_request) Successful in 13s
Validators (Pushes and Pull Requests) / Core Validators & Database Setup (pull_request) Failing after 28s
Validators (Pushes and Pull Requests) / WBS & Audit Validations (pull_request) Has been skipped
Validators (Pushes and Pull Requests) / .NET Contracts (pull_request) Has been skipped
Validators (Pushes and Pull Requests) / Calibration & Performance (pull_request) Has been skipped
Validators (Pushes and Pull Requests) / Operational Report & Decision Packet (pull_request) Has been skipped
Validators (Pushes and Pull Requests) / CI Workflow Lint (pull_request) Failing after 10s
Validators (Pushes and Pull Requests) / Security & Secrets (pull_request) Successful in 12s
Validators (Pushes and Pull Requests) / Notify PR Results (pull_request) Successful in 2s
Frontend CI Pipeline / ci-frontend-8-steps (pull_request) Failing after 2m50s
2026-07-27 00:45:39 +09:00
299 changed files with 3357 additions and 15230 deletions
-644
View File
@@ -1,644 +0,0 @@
name: Deploy to Production
on:
push:
branches: [ main ]
workflow_dispatch:
# Phase 4: Manual-only deployment (improved & hardened)
# Automatic deployment moved to merge-to-main.yml (Stage 5)
# Use this workflow for manual deployments when needed
#
# Error handling: Comprehensive logging + automatic rollback
# Security: SSH key validation, deployment verification
# Observability: Detailed stage reporting + Telegram notifications
concurrency:
group: deploy-prod-main
cancel-in-progress: false
env:
DEPLOY_HOST: quant.taxbaik.com
DEPLOY_USER: kjh2064
SERVICE_NAME: quantengine
DOTNET_VERSION: '10.0.x'
QUANTENGINE_DB_NAME: quantenginedb
QUANTENGINE_DB_USER: quantengine_app
TELEGRAM_BOT_TOKEN_DEFAULT: "8734507814:AAFyacLMai8GB4K-hQ_Nd3t3D01A-H1ZdV0"
TELEGRAM_CHAT_ID_DEFAULT: "-5460205872"
DEPLOY_TIMEOUT: "600"
HEALTH_CHECK_RETRIES: "5"
HEALTH_CHECK_DELAY: "3"
jobs:
build-and-deploy:
name: Build & Deploy to Production
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Setup .NET
uses: actions/setup-dotnet@v3
with:
dotnet-version: ${{ env.DOTNET_VERSION }}
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.10'
- name: Install Python Dependencies
run: pip install pyyaml openpyxl requests
- name: "[GATE] Run Core Validations"
run: |
echo " Running critical CI validations..."
python3 tools/validate_no_direct_api_trading_v1.py || exit 1
python3 tools/validate_specs.py || exit 1
echo " All critical validations passed"
- name: Ensure Temp Directory and Mock Packet
run: |
mkdir -p Temp
if [ ! -f Temp/final_decision_packet_active.json ]; then
echo '{"active_decision": "PASS", "details": "CI dummy packet"}' > Temp/final_decision_packet_active.json
fi
- name: Restore Dependencies
run: dotnet restore src/dotnet/QuantEngine.Web/QuantEngine.Web.csproj
- name: Build Release
run: |
dotnet build src/dotnet/QuantEngine.Web/QuantEngine.Web.csproj \
-c Release \
--no-restore
- name: Run Unit Tests
run: |
dotnet test src/dotnet/QuantEngine.Core.Tests/QuantEngine.Core.Tests.csproj \
-c Release \
--no-build
- name: Publish Release Package
run: |
dotnet publish src/dotnet/QuantEngine.Web/QuantEngine.Web.csproj \
-c Release \
--no-build \
-o ./publish
- name: Generate Build Info
run: |
COMMIT_HASH=$(git rev-parse --short HEAD)
BUILD_TIME=$(date -d "+9 hours" +'%Y-%m-%d %H:%M:%S KST')
mkdir -p ./publish/wwwroot
printf '{\n "version": "1.0.%s-%s",\n "built": "%s"\n}\n' "${{ github.run_number }}" "$COMMIT_HASH" "$BUILD_TIME" > ./publish/wwwroot/version.json
echo " Generated version info: 1.0.${{ github.run_number }}-$COMMIT_HASH @ $BUILD_TIME"
- name: Prepare & Validate QuantEngine DB Env
run: |
echo " Preparing database environment..."
DB_PASSWORD="${{ secrets.QUANTENGINE_DB_PASSWORD }}"
if [ -z "$DB_PASSWORD" ]; then
echo " QUANTENGINE_DB_PASSWORD secret not configured in Gitea"
echo " Please set secret in Repository Settings > Secrets"
exit 1
fi
if [ -z "${{ env.QUANTENGINE_DB_NAME }}" ] || [ -z "${{ env.QUANTENGINE_DB_USER }}" ]; then
echo " DB configuration environment variables not set"
exit 1
fi
#
mkdir -p ./deploy
printf 'ConnectionStrings__DefaultConnection=Host=127.0.0.1;Database=%s;Username=%s;Password=%s;Search Path=quantengine;\n' \
"${{ env.QUANTENGINE_DB_NAME }}" \
"${{ env.QUANTENGINE_DB_USER }}" \
"$DB_PASSWORD" > ./deploy/quantengine.env
chmod 600 ./deploy/quantengine.env
# appsettings.Production.json
mkdir -p ./publish
cat <<EOF > ./publish/appsettings.Production.json
{
"ConnectionStrings": {
"DefaultConnection": "Host=127.0.0.1;Database=${{ env.QUANTENGINE_DB_NAME }};Username=${{ env.QUANTENGINE_DB_USER }};Password=${DB_PASSWORD};Search Path=quantengine;"
}
}
EOF
chmod 600 ./publish/appsettings.Production.json
if [ ! -f ./deploy/quantengine.env ] || [ ! -f ./publish/appsettings.Production.json ]; then
echo " Failed to create database config files"
exit 1
fi
echo " Database configuration prepared"
- name: Copy Deployment Scripts
run: |
echo " Copying deployment scripts..."
cp deploy_gb.sh ./publish/deploy_gb.sh
mkdir -p ./publish/scripts
cp scripts/validate_migrations.sh ./publish/scripts/validate_migrations.sh
chmod +x ./publish/deploy_gb.sh ./publish/scripts/validate_migrations.sh
echo " Deployment scripts copied"
- name: Package Artifact
run: |
echo " Creating deployment package..."
if ! tar -czf quantengine.tar.gz -C ./publish .; then
echo " Failed to create package"
exit 1
fi
PACKAGE_SIZE=$(du -sh quantengine.tar.gz | cut -f1)
PACKAGE_BYTES=$(stat -c%s quantengine.tar.gz 2>/dev/null || echo "0")
if [ -z "$PACKAGE_BYTES" ] || [ "$PACKAGE_BYTES" -lt 1000000 ]; then
echo " Warning: Package seems too small ($PACKAGE_SIZE)"
fi
if [ ! -f quantengine.tar.gz ]; then
echo " Package file not created"
exit 1
fi
echo " Package created: $PACKAGE_SIZE"
tar -tzf quantengine.tar.gz | head -n 5 || true
- name: Pre-Deployment Migration Validation
run: |
echo "=== Pre-Deployment Database Check ==="
# ()
TEMP_DEPLOY="/tmp/quantengine_validate"
mkdir -p "$TEMP_DEPLOY"
tar -xzf quantengine.tar.gz -C "$TEMP_DEPLOY"
#
chmod +x "$TEMP_DEPLOY/scripts/validate_migrations.sh"
"$TEMP_DEPLOY/scripts/validate_migrations.sh" "$TEMP_DEPLOY"
#
rm -rf "$TEMP_DEPLOY"
- name: Pre-Deployment Verification
run: |
echo "=== PRE-DEPLOYMENT CHECKS ==="
# 1. SSH
if [ ! -f ~/.ssh/id_rsa ]; then
echo "ERROR: SSH key not found"
exit 1
fi
echo "OK: SSH key present"
# 2.
if [ ! -f quantengine.tar.gz ]; then
echo "ERROR: Build artifact (quantengine.tar.gz) not found"
exit 1
fi
ARTIFACT_SIZE=$(stat -c%s quantengine.tar.gz)
if [ "$ARTIFACT_SIZE" -lt 1000000 ]; then
echo "WARNING: Artifact seems small (${ARTIFACT_SIZE} bytes), but proceeding"
fi
echo "OK: Build artifact present (${ARTIFACT_SIZE} bytes)"
# 3.
for file in deploy/quantengine.env deploy_gb.sh; do
if [ ! -f "$file" ]; then
echo "ERROR: Required file missing: $file"
exit 1
fi
done
echo "OK: All required deployment files present"
# 4.
if [ -z "${{ secrets.QUANTENGINE_DB_PASSWORD }}" ]; then
echo "ERROR: DB password secret not configured"
exit 1
fi
echo "OK: DB credentials configured"
echo "=== ALL PRE-DEPLOYMENT CHECKS PASSED ==="
- name: Local Deploy (Green-Blue)
id: deploy
run: |
set -e
#
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
COMMIT=$(git rev-parse --short HEAD)
RUN_NUM="${{ github.run_number }}"
DEPLOY_BASE="/home/kjh2064/deployments"
ACTIVE_LINK="/home/kjh2064/quantengine_active"
TARGET_DIR="${DEPLOY_BASE}/quantengine_${TIMESTAMP}_${COMMIT}_${RUN_NUM}"
DEPLOYMENT_LOG="./deployment_${TIMESTAMP}.log"
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
send_telegram() {
local text="$1"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text=${text}" \
-d "parse_mode=HTML" >/dev/null || true
}
trap 'on_error' ERR
on_error() {
echo "DEPLOYMENT FAILED" | tee -a "$DEPLOYMENT_LOG"
send_telegram "DEPLOYMENT FAILED: $COMMIT at $(date)"
exit 1
}
{
echo "=== DEPLOYMENT START: $TIMESTAMP ==="
echo "Commit: $COMMIT"
echo "Run: $RUN_NUM"
echo "Target: $TARGET_DIR"
echo ""
#
echo "[1/8] Creating deployment directories..."
mkdir -p "${DEPLOY_BASE}" || { echo "FATAL: Cannot create deploy base"; exit 1; }
mkdir -p "${TARGET_DIR}" || { echo "FATAL: Cannot create target dir"; exit 1; }
echo "OK: Directories created"
echo ""
#
echo "[2/8] Extracting build artifact..."
if ! tar -xzf quantengine.tar.gz -C "${TARGET_DIR}"; then
echo "FATAL: Failed to extract artifact"
exit 1
fi
echo "OK: Artifact extracted"
ls "${TARGET_DIR}" | head -10
echo ""
#
echo "[3/8] Normalizing deployment structure..."
if [ -d "${TARGET_DIR}/net10.0" ]; then
echo "Found net10.0 subdirectory, moving to root..."
if ! mv "${TARGET_DIR}/net10.0"/* "${TARGET_DIR}/"; then
echo "WARNING: Some files could not be moved from net10.0"
fi
if [ -d "${TARGET_DIR}/net10.0" ]; then
rmdir "${TARGET_DIR}/net10.0" 2>/dev/null || echo "Warning: Could not remove net10.0 dir"
fi
fi
echo "OK: Structure normalized"
echo ""
#
echo "[4/8] Validating deployment contents..."
if [ ! -f "${TARGET_DIR}/QuantEngine.Web.dll" ]; then
echo "FATAL: QuantEngine.Web.dll not found in deployment"
exit 1
fi
if [ ! -f "${TARGET_DIR}/appsettings.json" ]; then
echo "FATAL: appsettings.json not found"
exit 1
fi
echo "OK: All required files present"
echo ""
#
echo "[5/8] Installing environment configuration..."
mkdir -p /home/kjh2064/.config || { echo "WARNING: Cannot create config dir"; }
install -m 600 ./deploy/quantengine.env /home/kjh2064/.config/quantengine.env || { echo "WARNING: Config file install failed"; }
echo "OK: Configuration installed"
echo ""
# appsettings.Production.json
echo "[6/8] Creating production appsettings..."
mkdir -p "${TARGET_DIR}"
DB_PASSWORD="${{ secrets.QUANTENGINE_DB_PASSWORD }}"
cat > "${TARGET_DIR}/appsettings.Production.json" << EOF
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Host=127.0.0.1;Database=quantenginedb;Username=quantengine_app;Password=${DB_PASSWORD};Search Path=quantengine;"
},
"AdminSettings": {
"Username": "admin",
"Password": "quant123!"
}
}
EOF
chmod 600 "${TARGET_DIR}/appsettings.Production.json"
echo "OK: appsettings.Production.json created"
echo ""
} | tee "$DEPLOYMENT_LOG"
echo "timestamp=${TIMESTAMP}" >> $GITHUB_OUTPUT
echo "commit=${COMMIT}" >> $GITHUB_OUTPUT
echo "target_dir=${TARGET_DIR}" >> $GITHUB_OUTPUT
# ()
PREV_VERSION="none"
if [ -L "${ACTIVE_LINK}" ]; then
PREV_VERSION=$(readlink -f "${ACTIVE_LINK}")
PREV_TIMESTAMP=$(basename "${PREV_VERSION}")
else
PREV_TIMESTAMP="none"
fi
echo "[7/8] Executing Green-Blue deployment..."
export DEPLOY_FROM_CI=1
chmod +x "${TARGET_DIR}/deploy_gb.sh"
if ! "${TARGET_DIR}/deploy_gb.sh" >> "$DEPLOYMENT_LOG" 2>&1; then
echo "DEPLOYMENT FAILED: Green-Blue swap error"
send_telegram "DEPLOYMENT FAILED: Green-Blue swap failed for $COMMIT"
exit 1
fi
echo "OK: Green-Blue deployment completed"
#
cat > "${TARGET_DIR}/.deployment_info" << EOF
Deployed: $(date -u +'%Y-%m-%dT%H:%M:%SZ')
Commit: ${COMMIT}
Timestamp: ${TIMESTAMP}
Run: ${RUN_NUM}
Previous: ${PREV_TIMESTAMP}
Status: DEPLOYED
EOF
echo "timestamp=${TIMESTAMP}" >> $GITHUB_OUTPUT
echo "commit=${COMMIT}" >> $GITHUB_OUTPUT
echo "target_dir=${TARGET_DIR}" >> $GITHUB_OUTPUT
echo "prev_version=${PREV_TIMESTAMP}" >> $GITHUB_OUTPUT
- name: Health Check & Verification
id: health-check
run: |
TIMESTAMP="${{ steps.deploy.outputs.timestamp }}"
COMMIT="${{ steps.deploy.outputs.commit }}"
TARGET_DIR="${{ steps.deploy.outputs.target_dir }}"
PREV_TIMESTAMP="${{ steps.deploy.outputs.prev_version }}"
DEPLOY_BASE="/home/kjh2064/deployments"
ACTIVE_LINK="/home/kjh2064/quantengine_active"
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
send_telegram() {
local text="$1"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text=${text}" \
-d "parse_mode=HTML" >/dev/null || true
}
echo "=== POST-DEPLOYMENT HEALTH CHECKS ==="
# 1.
echo "[1/4] Verifying deployment directory..."
if [ ! -d "$TARGET_DIR" ]; then
echo "FATAL: Deployment directory not found: $TARGET_DIR"
exit 1
fi
if [ ! -f "${TARGET_DIR}/QuantEngine.Web.dll" ]; then
echo "FATAL: Application DLL not found in deployment"
exit 1
fi
echo "OK: Deployment directory verified"
# 2. Loopback
echo "[2/4] Performing loopback health checks..."
health_check_passed=0
for i in $(seq 1 ${{ env.HEALTH_CHECK_RETRIES }}); do
echo " Attempt $i/${{ env.HEALTH_CHECK_RETRIES }}..."
if timeout 10 curl -s -f -o /dev/null -w '%{http_code}' http://127.0.0.1:5000/ 2>/dev/null | grep -qE '^(200|302|401)$'; then
echo " OK: Service responding"
health_check_passed=1
break
fi
if [ $i -lt ${{ env.HEALTH_CHECK_RETRIES }} ]; then
sleep ${{ env.HEALTH_CHECK_DELAY }}
fi
done
if [ $health_check_passed -eq 0 ]; then
echo "FAILED: Health check did not pass after ${{ env.HEALTH_CHECK_RETRIES }} attempts"
echo "status=failed" >> $GITHUB_OUTPUT
exit 1
fi
echo "OK: Loopback health check passed"
# 3.
echo "[3/4] Verifying database connectivity..."
if timeout 10 bash -c 'cat /home/kjh2064/.config/quantengine.env | grep -q "postgresql"' 2>/dev/null; then
echo "OK: Database credentials configured"
else
echo "WARNING: Could not verify database credentials"
fi
# 4.
echo "[4/4] Checking service status..."
if systemctl is-active --quiet quantengine; then
echo "OK: Service is running"
else
echo "WARNING: Service may not be running, but health checks passed"
fi
echo "status=success" >> $GITHUB_OUTPUT
echo "=== ALL HEALTH CHECKS PASSED ==="
send_telegram "OK: QuantEngine deployed successfully (commit: ${COMMIT})"
- name: Auto-Rollback on Health Check Failure
if: failure() && steps.health-check.outcome == 'failure'
run: |
COMMIT="${{ steps.deploy.outputs.commit }}"
PREV_TIMESTAMP="${{ steps.deploy.outputs.prev_version }}"
DEPLOY_BASE="/home/kjh2064/deployments"
ACTIVE_LINK="/home/kjh2064/quantengine_active"
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
send_telegram() {
local text="$1"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text=${text}" \
-d "parse_mode=HTML" >/dev/null || true
}
echo "=== AUTOMATIC ROLLBACK INITIATED ==="
echo "Health check failed, rolling back to previous version..."
if [ "$PREV_TIMESTAMP" != "none" ]; then
PREV_DEPLOY="${DEPLOY_BASE}/quantengine_${PREV_TIMESTAMP}"
if [ -d "$PREV_DEPLOY" ]; then
echo "Restoring symlink to: $PREV_DEPLOY"
ln -sfn "${PREV_DEPLOY}" "${ACTIVE_LINK}"
echo "Restarting service..."
systemctl restart quantengine 2>&1 || echo "WARNING: Service restart may have issues"
sleep 3
echo "Rollback completed"
send_telegram "ROLLBACK: Deployment of ${COMMIT} failed, rolled back to ${PREV_TIMESTAMP}"
else
echo "ERROR: Previous deployment directory not found"
send_telegram "CRITICAL: Rollback failed - previous deployment not found"
exit 1
fi
else
echo "ERROR: No previous deployment available for rollback"
send_telegram "CRITICAL: Health check failed - no previous deployment to rollback to"
exit 1
fi
echo "=== Verifying Database Connectivity ==="
db_status=$(psql -U quantengine_app -d quantenginedb -h 127.0.0.1 -c 'SELECT 1;' 2>&1 | head -1)
if echo "$db_status" | grep -q "1"; then
echo " Database connectivity verified"
else
echo " Database connectivity check: $db_status"
fi
- name: Post-Deployment Verification
if: success()
run: |
echo "=== POST-DEPLOYMENT VERIFICATION ==="
# Public endpoints
echo "[1/3] Verifying public endpoints..."
for endpoint in "/" "/Account/Login"; do
code=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 5 "https://quant.taxbaik.com${endpoint}")
echo " https://quant.taxbaik.com${endpoint} -> $code"
if ! echo "$code" | grep -qE '^(200|302|401)$'; then
echo " WARNING: Unexpected response code"
fi
done
# Nginx
echo "[2/3] Verifying Nginx configuration..."
if nginx -t 2>&1 | grep -q "successful"; then
echo " OK: Nginx syntax valid"
else
echo " WARNING: Nginx validation may have issues"
fi
#
echo "[3/3] Creating deployment record..."
DEPLOYMENT_SUMMARY="deployment_summary_${{ steps.deploy.outputs.timestamp }}.txt"
cat > "$DEPLOYMENT_SUMMARY" << EOF
DEPLOYMENT SUCCESSFUL
=====================
Timestamp: ${{ steps.deploy.outputs.timestamp }}
Commit: ${{ steps.deploy.outputs.commit }}
Target: ${{ steps.deploy.outputs.target_dir }}
Previous: ${{ steps.deploy.outputs.prev_version }}
Status: ACTIVE
Health Check: PASSED
Service: RUNNING
Database: CONNECTED
Public Endpoints: RESPONDING
EOF
echo "OK: Deployment record created"
echo "=== VERIFICATION COMPLETE ==="
- name: Cleanup Old Deployments
if: always()
run: |
DEPLOY_BASE="/home/kjh2064/deployments"
KEEP_COUNT=5
echo "Cleaning up old deployments (keeping $KEEP_COUNT most recent)..."
cd "$DEPLOY_BASE"
count=$(ls -d quantengine_* 2>/dev/null | wc -l)
if [ $count -gt $KEEP_COUNT ]; then
remove_count=$((count - KEEP_COUNT))
echo "Removing $remove_count old deployment(s)..."
ls -dt quantengine_* | tail -n +$((KEEP_COUNT + 1)) | while read -r old_dir; do
echo " Removing: $old_dir"
rm -rf "$old_dir" 2>/dev/null || echo " WARNING: Could not remove $old_dir"
done
fi
echo "Cleanup complete. Current deployments:"
ls -ldt quantengine_* | head -5 | awk '{print $9, "(" $5 " bytes)"}'
- name: Notify Success
if: success()
run: |
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text=SUCCESS: QuantEngine deployment complete (commit: ${{ steps.deploy.outputs.commit }})" \
-d "parse_mode=HTML" >/dev/null || true
- name: Notify Failure
if: failure()
run: |
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text=FAILURE: QuantEngine deployment failed (commit: ${{ steps.deploy.outputs.commit }})
Logs: https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/actions/runs/${{ github.run_id }}" \
-d "parse_mode=HTML" >/dev/null || true
- name: Cleanup Old Deployments
run: |
DEPLOY_BASE="/home/kjh2064/deployments"
echo "Cleaning up obsolete deployments (keeping last 5)..."
cd "${DEPLOY_BASE}"
ls -dt quantengine_* | tail -n +6 | while read -r old_dir; do
echo "Removing old release: ${old_dir}"
rm -rf "${old_dir}"
done
echo "Cleanup complete"
ls -ldt quantengine_* | head -5
- name: Notify Failure
if: failure()
run: |
COMMIT=$(git rev-parse --short HEAD)
TELEGRAM_BOT_TOKEN="${{ secrets.TELEGRAM_BOT_TOKEN }}"
[ -z "$TELEGRAM_BOT_TOKEN" ] && TELEGRAM_BOT_TOKEN="${{ env.TELEGRAM_BOT_TOKEN_DEFAULT }}"
TELEGRAM_CHAT_ID="${{ secrets.TELEGRAM_CHAT_ID }}"
[ -z "$TELEGRAM_CHAT_ID" ] && TELEGRAM_CHAT_ID="${{ env.TELEGRAM_CHAT_ID_DEFAULT }}"
curl -fsS -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
-d "chat_id=${TELEGRAM_CHAT_ID}" \
--data-urlencode "text= QuantEngine \n: ${COMMIT}\n: https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/actions/runs/${{ github.run_id }}" \
-d "parse_mode=HTML" || true
+17
View File
@@ -0,0 +1,17 @@
name: Daily T+20 Outcome Ledger Build
on:
schedule:
- cron: '0 8 * * 1-5' # KST 17:00 (Mon-Fri)
workflow_dispatch:
jobs:
build-t20-ledger:
runs-on: self-hosted
steps:
- name: Checkout Code
uses: actions/checkout@v3
- name: Build T+20 Outcome Ledger
run: |
python3 tools/build_operational_t20_outcome_ledger_v1.py
+6
View File
@@ -28,6 +28,12 @@ src/dotnet/QuantEngine.Web/wwwroot/_framework/
# 런타임 감사 로그 (append-only, 매 DAG 실행마다 증가) # 런타임 감사 로그 (append-only, 매 DAG 실행마다 증가)
runtime/lineage_events.jsonl runtime/lineage_events.jsonl
# .NET 런타임 로그 (Serilog 등, 실행마다 재생성)
**/logs/*.log
# Playwright 테스트 산출물 (스크린샷/트레이스, 실행마다 재생성)
test-results/
# OS / 에디터 # OS / 에디터
... ...
.DS_Store .DS_Store
+1
View File
@@ -104,6 +104,7 @@
- `docs/CLOUD_SERVER_SETUP.md`: 클라우드 서버(hz-prod-01, 178.104.200.7) 설정 하네스 가이드. 시놀로지 → 클라우드 마이그레이션 매핑 포함. - `docs/CLOUD_SERVER_SETUP.md`: 클라우드 서버(hz-prod-01, 178.104.200.7) 설정 하네스 가이드. 시놀로지 → 클라우드 마이그레이션 매핑 포함.
- `docs/ENTERPRISE_CRUD_DESIGN_SPECIFICATION.md`: OMS·WMS·ERP CRUD 화면 및 입력 컴포넌트 상용화 지침 명세 (엔터프라이즈 컴포넌트/트랜잭션 헌법). - `docs/ENTERPRISE_CRUD_DESIGN_SPECIFICATION.md`: OMS·WMS·ERP CRUD 화면 및 입력 컴포넌트 상용화 지침 명세 (엔터프라이즈 컴포넌트/트랜잭션 헌법).
- `docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md`: OMS·WMS·ERP 공통 CRUD 화면 템플릿 상용화 WBS & 로드맵. - `docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md`: OMS·WMS·ERP 공통 CRUD 화면 템플릿 상용화 WBS & 로드맵.
- `docs/QUANTENGINE_MASTERPIECE_ROADMAP.md`: 프로젝트 냉정 분석 & 마스터피스 3-Stream 로드맵 (Alpha Validation / Platform Consolidation / Professional Operation).
- `src/frontend/src/types/enterpriseTemplateContracts.ts`: OMS·WMS·ERP 11대 표준 템플릿 TypeScript 공통 계약. - `src/frontend/src/types/enterpriseTemplateContracts.ts`: OMS·WMS·ERP 11대 표준 템플릿 TypeScript 공통 계약.
- `docs/GITEA_SECRETS_SETUP.md`: Gitea secrets setup and verification guide. - `docs/GITEA_SECRETS_SETUP.md`: Gitea secrets setup and verification guide.
- `docs/GATHERTRADINGDATA_XLSX_OPERATING_RUNBOOK.md`: `GatherTradingData.xlsx` 보조 자산 런북. - `docs/GATHERTRADINGDATA_XLSX_OPERATING_RUNBOOK.md`: `GatherTradingData.xlsx` 보조 자산 런북.
+187 -1614
View File
File diff suppressed because it is too large Load Diff
+13 -7
View File
@@ -28,15 +28,12 @@ CI 스케줄러는 `GatherTradingData.json`을 seed snapshot으로 사용하고,
```powershell ```powershell
npm install npm install
node core_satellite_collector.js
``` ```
OpenDART 공시까지 확인하려면: **⚠️ 2026-07-30 정정**: 이 섹션은 예전에 `node core_satellite_collector.js`를 실행 커맨드로
안내했지만, 그 파일은 git 히스토리에 한 번도 존재한 적이 없다 (`package.json``ops:dev`
```powershell 스크립트도 같은 phantom 파일을 가리키고 있어 같은 날 함께 정리함). 실제 수집기는
$env:DART_API_KEY="발급받은키" Python으로 구현되어 있다 — 아래 커맨드를 사용할 것.
node core_satellite_collector.js
```
SQLite 기반 데이터 수집을 실행하려면: SQLite 기반 데이터 수집을 실행하려면:
@@ -44,6 +41,15 @@ SQLite 기반 데이터 수집을 실행하려면:
$env:KIS_APP_Key="실제계좌키" $env:KIS_APP_Key="실제계좌키"
$env:KIS_APP_Secret="실제계좌시크릿" $env:KIS_APP_Secret="실제계좌시크릿"
python tools/run_kis_data_collection_v1.py --input-json GatherTradingData.json --sqlite-db src/quant_engine/kis_data_collection.db --output-json Temp/kis_data_collection_v1.json --kis-account real python tools/run_kis_data_collection_v1.py --input-json GatherTradingData.json --sqlite-db src/quant_engine/kis_data_collection.db --output-json Temp/kis_data_collection_v1.json --kis-account real
# 또는: npm run ops:data-collect
```
OpenDART 공시까지 확인하려면 (2026-07-30 기준 `_dart_fundamentals()`는 아직 스텁 — 실제
호출은 미구현, `tools/ingest_fundamental_raw.py` 참고):
```powershell
$env:OPENDART_OPENAPI_KEY="발급받은키"
python tools/ingest_fundamental_raw.py
``` ```
### Snapshot admin web UI ### Snapshot admin web UI
+53
View File
@@ -0,0 +1,53 @@
# QuantEngine API Reference
Full API endpoint tables, extracted from CLAUDE.md (2026-07-30) to keep the main file within
the character budget.
## Workspace & History (Phase 1)
All endpoints prefixed with `/api/`:
| Route | Purpose |
|-------|---------|
| `GET /state` | Full UI state snapshot |
| `GET /tables` | Browsable tables list |
| `GET /table-rows` | Paginated rows |
| `POST /settings/save` | Save settings |
| `POST /account-snapshot/save` | Save snapshots |
| `POST /bootstrap` | Seed DB from JSON |
| `POST /account-snapshot/import-tsv` | Import TSV |
| `POST /autofix` | Auto-correct data |
## Collection Pipeline (Phase 2)
| Route | Purpose |
|-------|---------|
| `GET /collection/state` | Dashboard summary (runs, snapshots, errors) |
| `GET /collection/runs` | Recent collection runs (paginated) |
| `GET /collection/runs/{runId}/snapshots` | Snapshots from a run |
| `GET /collection/runs/{runId}/errors` | Errors from a run |
| `GET /collection/latest/{ticker}` | Latest snapshots for ticker |
| `POST /collection/run` | Start new collection run (async) |
## Collection Run Status Values
| Status | Meaning | UI Badge | Transitions |
|--------|---------|----------|------------|
| `running` | Collection in progress | <span class="badge bg-warning">진행 중</span> | → completed or failed |
| `completed` | Collection finished (may have errors) | <span class="badge bg-success">완료</span> | (final) |
| `failed` | Collection crashed/aborted | <span class="badge bg-danger">실패</span> | (final) |
| `pending` | Queued, not yet started | <span class="badge bg-secondary">대기 중</span> | → running |
## Collection Run Success Criteria
**Success** is defined as:
- Status = `completed` (not `failed`)
- `TotalSnapshots > 0` (at least one snapshot captured)
- `TotalErrors == 0` OR `TotalErrors < TotalSnapshots * 0.1` (error rate < 10%)
**Partial Success** (warning state):
- Status = `completed`
- `TotalSnapshots > 0` (some data captured)
- `TotalErrors > 0` (has errors, but not total loss)
**Failure**:
- Status = `failed` OR
- Status = `completed` + `TotalSnapshots == 0` (no data captured)
UI: `Pages/Admin/Collection/Index.cshtml` — status 값에 따라 배지 색상 결정, 향후 TotalSnapshots/TotalErrors로 상세 상태 표시
+107
View File
@@ -0,0 +1,107 @@
# QuantEngine CI/CD Pipeline Structure
Full Gitea Actions workflow structure, extracted from CLAUDE.md (2026-07-30) to keep the main
file within the character budget.
## Workflow Architecture Refactoring (2026-07-24)
**2026-07-24 refactoring**: Single-job ci.yml (30+ steps, ~40min runtime) → **9-job parallel pipeline** (~15-20min runtime).
## CI Pipeline Jobs (ci.yml)
| Job | Dependencies | Purpose | Parallelizable |
|-----|--------------|---------|---|
| **core** | — | CRITICAL: .NET tests, API trading gate, KIS creds, DB migrations | ✗ (blocks others) |
| **wbs-audit** | core | WBS validation, platform migration, coverage audits | ✓ |
| **dotnet-contracts** | core | .NET parity, provenance, scheduler, normalization contracts | ✓ |
| **ui-storage** | — | Admin UI, storage backend, integration tests | ✓ |
| **database-schema** | — | DB pipeline, PostgreSQL schema, history contracts | ✓ |
| **calibration-pipeline** | core | Calibration priority, change ledger, qualitative sell strategy | ✓ |
| **operational-reporting** | calibration | Decision packet, operational report, performance metrics | ✗ (depends on calibration) |
| **security-validation** | — | Secrets contract, workflow validation | ✓ |
| **workflow-lint** | — | CI workflow structure, secrets contract | ✓ |
| **notify-results** | ALL | PR notification with job status summary | — |
**Dependency Graph**:
```
core ─┬─> wbs-audit ─────────────────────┐
├─> dotnet-contracts ─────────────┤
└─> calibration-pipeline ────────┤
└─> operational-reporting ─┤
└─> notify-results
ui-storage ────────────────────────────────┘
database-schema ──────────────────────────┘
security-validation ───────────────────────┘
workflow-lint ─────────────────────────────┘
```
## Other Workflow Files
| File | Trigger | Purpose | Status |
|------|---------|---------|--------|
| **kis_data_collection.yml** | cron (00:30 KST M-F) + dispatch | Validate KIS credentials & PostgreSQL pipeline | ✓ 2026-07-24 |
| **qualitative_sell_strategy.yml** | cron (00:15 KST M-F) + push + dispatch | Validate sell strategy pipeline & store | ✓ 2026-07-24 |
| **ci_lint.yml** | push (.gitea/workflows/) + dispatch | Lint all workflow files, validate job dependencies, secrets contract | ✓ 2026-07-24 |
| **snapshot_admin.yml** | push (snapshot_admin_*) + dispatch | Validate snapshot admin workflow & UI (2 jobs) | ✓ 2026-07-24 |
| **ci-frontend.yml** | push (main/master/feature/**) + PR | 8-step `src/frontend/` pipeline: install, typecheck, import-boundary lint, unit test, enterprise CRUD contract parity, Vite build, Playwright E2E, npm audit | ✓ (undocumented until 2026-07-30) |
| **t20_ledger.yml** | cron (17:00 KST M-F) + dispatch | Build `tools/build_operational_t20_outcome_ledger_v1.py` daily T+20 outcome ledger | ✓ (undocumented until 2026-07-30) |
| **prepare-release.yml** | workflow_run (ci.yml success) + dispatch | Build, tag, create Gitea Release with artifact + checksums | — |
| **deploy-prod.yml** | dispatch | Deploy release, run health checks, report status (3 jobs) | — |
**Note (2026-07-30)**: An earlier version of this table claimed `ci_lint.yml` had been renamed to
`workflow_lint.yml`. That rename was never actually carried out — the file on disk is still
`ci_lint.yml`. Corrected here after direct verification against `.gitea/workflows/`.
## Performance Improvements (2026-07-24)
**ci.yml refactoring results**:
- **Before**: 1 job, 30+ sequential steps, ~40min runtime
- **After**: 9 jobs, 7 in parallel, ~15-20min total runtime
- **Speedup**: ~2-2.5x faster CI feedback (core branch blocks only downstream, others parallel)
- **Fault isolation**: Single validation failure no longer blocks unrelated checks
**Key changes**:
1. **Setup consolidation**: Database migrations, Python, .NET setup in `core` job only
2. **Parallel validation groups**: 7 jobs run independently from core (ui-storage, database-schema, security-validation, workflow-lint, etc.)
3. **Dependency clarity**: `needs:` explicitly defines blocking relationships
4. **Error reporting**: `notify-results` summarizes all 9 job statuses in PR comment
## Workflow Maintenance Checklist
When modifying workflows (.gitea/workflows/*.yml):
1. ✅ Update `ci_lint.yml` if adding new triggers or job dependencies
2. ✅ Test locally with `python3 tools/validate_gitea_ci_workflow_lint_v1.py`
3. ✅ Verify all `needs:` references point to existing jobs
4. ✅ Document new jobs in this section above
5. ✅ Validate YAML syntax: `python3 -m yaml < .gitea/workflows/new.yml`
6. ✅ Ensure no hardcoded secrets in workflow files (env vars only)
## Troubleshooting Workflows
**Symptom**: CI job timeout
- **Check**: Does your job need PostgreSQL? Only `core` provides it; others must be independent.
- **Fix**: Add `services: postgres:` block or restructure to parallel-safe job.
**Symptom**: Cascading failure (multiple jobs fail)
- **Check**: Does your job have missing dependencies? Review `needs:` and dependency graph above.
- **Fix**: Add explicit `needs: [job_name]` if job depends on another's output.
**Symptom**: "job not found" error in notify-results
- **Check**: Job name typo in `notify-results.needs` list.
- **Fix**: Match job name exactly (case-sensitive).
## Workflow Trigger Schedule (2026-07-24)
| Time (KST) | Workflow | Trigger | Purpose |
|-----------|----------|---------|---------|
| 00:15 | qualitative_sell_strategy.yml | cron (M-F) | Validate sell strategy before daily operations |
| 00:30 | kis_data_collection.yml | cron (M-F) | Validate KIS API & DB pipeline before data collection |
| Push | ci.yml | on:push (main) | Validate code on every push to main |
| PR | ci.yml | on:pull_request | Gate PR merges with full validation suite |
| Manual | prepare-release.yml | workflow_dispatch | Create release tag & artifact |
| Manual | deploy-prod.yml | workflow_dispatch | Deploy release to production |
**Dependencies**:
- Release creation (prepare-release.yml) is gated by ci.yml success (workflow_run trigger)
- Deployment (deploy-prod.yml) is manual — only after release artifact exists
+337
View File
@@ -0,0 +1,337 @@
# QuantEngine Deployment Runbook
Full deployment procedure, extracted from CLAUDE.md (2026-07-30) to keep the main file within
the character budget. CLAUDE.md keeps the CRITICAL rules (CI/CD-only mandate, DB secret
management); this file has the complete step-by-step runbook.
**Production Server**: Hetzner Cloud `178.104.200.7` (kjh2064@178.104.200.7)
Projects on server:
1. **TaxBaik** (홈페이지) — Nginx location `/taxbaik`
2. **QuantEngine** (데이터 수집/분석) — Nginx location `/quantengine`
## ⚠️ CRITICAL: CI/CD-Only Deployment Mandate
**Rule**: ALL production deployments MUST go through Gitea Actions CI/CD. Manual SSH deployments are **FORBIDDEN**.
**Why**:
- Automatic validation (build, health checks, version verification)
- Audit trail (all deployments logged in Gitea Actions)
- Consistent process (no manual errors)
- Rollback safety (deployment history retained)
- Release traceability (version control via git tags)
## ⚠️ CRITICAL: DB Secret Management (Incident 2026-07-12)
**Incident**: `quant.taxbaik.com/login``28P01 password authentication failed`로 장애 발생.
원인: `appsettings.Production.json`에 하드코딩되어 배포된 DB 비밀번호가, 실제 DB 비밀번호가
로테이션된 이후에도 계속 옛날 값(심지어 이전 세션에서 검증 없이 넣은 placeholder였던 적도 있음)
그대로 배포되고 있었음.
**Rule**: **DB 접속 문자열(`ConnectionStrings`)은 절대 `appsettings.Production.json`이나
워크플로우 파일에 하드코딩하지 않는다.** `prepare-release.yml`이 생성하는
`appsettings.Production.json`에는 `Logging` 설정만 있고 `ConnectionStrings`는 없다 —
이는 의도된 설계다 (Gitea Release는 누구나 다운로드 가능한 아티팩트이므로 시크릿을
담으면 안 됨).
**실제 DB 비밀번호의 출처**: 프로덕션 서버의 `/home/kjh2064/.config/quantengine.env`
파일 (`ConnectionStrings__DefaultConnection=...` 형식) 하나뿐이며,
`quantengine.service.d/env.conf` drop-in의 `EnvironmentFile=` 지시자로 systemd가
이 값을 환경변수로 주입한다. ASP.NET Core 설정 우선순위상 **환경변수가
`appsettings.Production.json`을 오버라이드**하므로, 배포되는 아티팩트 자체에는
DB 정보가 없어도 서비스는 정상 동작한다.
**DB 비밀번호가 바뀌면** (로테이션 등): `/home/kjh2064/.config/quantengine.env` 파일만
갱신하고 `sudo systemctl restart quantengine`. 워크플로우 파일이나 Gitea Secrets는
건드릴 필요 없음 (배포 파이프라인은 DB 비밀번호를 모른 채로 동작해야 정상).
**배포 전 체크리스트에 추가**:
- ✅ 새 릴리즈 배포 후 반드시 `/Account/Login` 실제 HTTP 응답 + `journalctl -u quantengine`에서
`28P01`/`password authentication failed` 부재 확인 (단순 프로세스 `active` 상태만으로는
DB 연결 실패를 못 잡음 — ASP.NET Core는 DB 없이도 기동은 되고 로그인 요청 시점에야 실패함)
-`.config/quantengine.env`의 존재와 `quantengine.service.d/env.conf`
`EnvironmentFile=` 배선이 서버에 유지되고 있는지 (systemd unit 자체를 재생성/덮어쓰는
배포 방식으로 전환할 경우 이 drop-in이 날아가지 않는지 확인 필요)
## Production Deployment Strategy (Release-Based)
**Architecture**: Two-Workflow System (Release Creation → Deployment)
### Workflow 1: prepare-release.yml (Release Creation)
**Purpose**: Create a release with built artifact
**Trigger**: Manual (`workflow_dispatch`)
```bash
# Visit Gitea Actions and select prepare-release.yml
# Input version: v0.1.20260711 (or any semantic version)
```
**What it does**:
1. ✓ Build (restore, build, publish)
2. ✓ Generate `appsettings.Production.json`
3. ✓ Package artifact: `.tar.gz`
4. ✓ Create git tag: `v0.1.20260711`
5. ✓ Create Gitea Release with artifact attached
6. ✓ Notify: Release ready for deployment
**Output**: Gitea Release with downloadable artifact
### Workflow 2: deploy-prod.yml (Deployment)
**Purpose**: Deploy a release to production
**Trigger**: Manual (`workflow_dispatch`)
```bash
# Visit Gitea Actions and select deploy-prod.yml
# Input release: v0.1.20260711 (optional — uses latest if empty)
```
**What it does**:
1. ✓ Fetch Release (from Gitea Releases)
2. ✓ Download artifact
3. ✓ Verify SSH credentials
4. ✓ Upload to production server
5. ✓ Extract and symlink
6. ✓ Restart service
7. ✓ 6-point health checks
8. ✓ Report deployment status
**Deployment Pipeline (5 Stages)**:
| Stage | Purpose | Timeout |
|-------|---------|---------|
| 1. Fetch Release | Query Gitea Releases, download artifact | 10min |
| 2. Pre-Check | Verify SSH keys, secrets, release | 5min |
| 3. Deploy | Upload, extract, symlink, restart service | 30min |
| 4. Health Check | 6-point verification (HTTP, CSS, login, service, release, DB auth) | 10min |
| 5. Report | Final deployment status | Auto |
**Health Checks (Automatic)**:
- ✓ HTTP 200 on `/Account/Login`
- ✓ Login page content verification
- ✓ CSS file loads (`/css/admin.css`)
- ✓ Service status (systemctl active)
- ✓ Release verification (deployed release tag matches)
-**DB authentication check** (`journalctl`에서 `28P01`/`password authentication failed`
부재 확인 — GET `/Account/Login`은 DB가 끊겨도 200을 반환하므로 이 체크가 없으면
DB 장애를 배포 파이프라인이 놓친다. 2026-07-12 사고 이후 추가됨)
**Complete Deployment Flow**:
```
1. Code committed to main branch
2. Create release: prepare-release.yml workflow_dispatch (manual)
→ Builds code
→ Creates Gitea Release with artifact
→ Tags repository
3. Deploy release: deploy-prod.yml workflow_dispatch (manual)
→ Selects release version
→ Downloads artifact from Gitea Release
→ Deploys to production server
→ Runs health checks
→ Reports status
```
## Pre-Deployment Checklist
**Before creating a release**, verify:
1. ✅ Local build: `dotnet build src/dotnet/QuantEngine.Web/QuantEngine.Web.csproj -c Release` (0 errors, 0 warnings)
2. ✅ E2E tests pass: `npx playwright test`
3. ✅ Admin pages verified (200 status, no 500 errors)
4. ✅ All changes committed and pushed to main branch
5. ✅ No uncommitted changes: `git status`
## Release & Deployment Workflow
**Step 1: Create Release (prepare-release.yml)**
```bash
# Visit Gitea Actions
# https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/actions
# Run prepare-release.yml workflow
# Input: version = v0.1.20260711
# Workflow will:
# - Build and publish
# - Package artifact
# - Create git tag
# - Create Gitea Release
# - Attach artifact
```
**Step 2: Deploy Release (deploy-prod.yml)**
```bash
# Visit Gitea Actions (same page)
# Run deploy-prod.yml workflow
# Input: release = v0.1.20260711 (leave empty for latest)
# Workflow will:
# - Download artifact from release
# - Deploy to production server
# - Run health checks
# - Report status
```
## SSH Key Configuration (Required)
**Setup (One-time)**:
1. Generate ED25519 key locally (or reuse existing):
```bash
ssh-keygen -t ed25519 -f ~/.ssh/quantengine_deploy -C "QuantEngine CI/CD"
```
2. Add public key to production server:
```bash
ssh-copy-id -i ~/.ssh/quantengine_deploy.pub kjh2064@178.104.200.7
```
3. Get private key in base64 format:
```bash
# macOS/Linux
base64 -w 0 ~/.ssh/quantengine_deploy > /tmp/key_b64.txt
cat /tmp/key_b64.txt | pbcopy
# Or Windows PowerShell
$key = Get-Content ~/.ssh/quantengine_deploy -Raw
[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($key)) | Set-Clipboard
```
4. Configure in Gitea:
- URL: https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/settings/secrets
- Add secret: `DEPLOY_SSH_KEY_B64` (base64-encoded private key)
- Or: `DEPLOY_SSH_KEY` (raw PEM format)
- Also add: `GITEA_TOKEN` (for release API access)
- Generate at: https://gitea.taxbaik.com/user/settings/applications
- Required permissions: `repo` + `read:actions`
## Deployment Monitoring
**During Deployment**:
- Watch live in Gitea Actions UI
- Jobs complete in order: Build → Pre-Check → Deploy → Health Check → Report
**After Deployment**:
```bash
# SSH into server
ssh kjh2064@178.104.200.7
# Check active deployment
readlink ~/quantengine_active
# View service status
systemctl status quantengine
# Tail live logs
journalctl -u quantengine -f
# Health check
curl -I http://127.0.0.1:5000/Account/Login
```
## Automatic Rollback (if health check fails)
If health check fails, deployment stops automatically:
1. Service restart may fail
2. Symlink update reverts to previous deployment
3. Gitea Actions marks deployment as FAILED
4. Logs include failure details
Manual rollback (if needed):
```bash
# List deployments
ls -lht ~/deployments/quantengine_*
# Revert symlink to previous version
ln -sfn /home/kjh2064/deployments/quantengine_YYYYMMDD_HHMMSS_COMMIT ~/quantengine_active
# Restart service
sudo systemctl restart quantengine
# Verify
curl http://127.0.0.1:5000/Account/Login
```
## Troubleshooting Deployment Failures
**Issue**: Build fails
- Check: `dotnet build` locally first
- Ensure: No compilation errors, 0 warnings
**Issue**: Health check timeout
- Check: Service logs: `journalctl -u quantengine -n 50`
- Check: Port 5000 listening: `ss -tlnp | grep 5000`
- Check: DB connectivity in appsettings.Production.json
**Issue**: SSH key error
- Verify: `DEPLOY_SSH_KEY_B64` or `DEPLOY_SSH_KEY` in Gitea Secrets
- Check: Public key added to `~/.ssh/authorized_keys` on server
- Test: `ssh -i ~/.ssh/key_file kjh2064@178.104.200.7 echo OK`
## Git Repository
**Gitea Server** (동일 호스트):
- **HTTP**: `https://gitea.taxbaik.com/kjh2064/QuantEngineByItz.git`
- **SSH**: `ssh://git@gitea.taxbaik.com:2222/kjh2064/QuantEngineByItz.git`
## Active Gitea Workflows (summary)
1. **prepare-release.yml** — Release creation (workflow_dispatch only)
- Build → Publish → Package → Tag → Gitea Release
- Does NOT write ConnectionStrings into the artifact (see DB Secret Management above) —
only `Logging` config ships in `appsettings.Production.json`
2. **deploy-prod.yml** — Production deployment (workflow_dispatch only, takes a release tag)
- 5 stages: Fetch Release → Pre-Check → Deploy → Health Check → Report
- 6-point health checks (HTTP, login page, CSS, service, release, DB auth)
- SSH-based deployment with artifact validation
3. **ci.yml** — PR validation (on:pull_request), 29 validators, runs on every pull request
**Accessing Gitea Actions**:
- Web UI: https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/actions
- Runs API: https://gitea.taxbaik.com/api/v1/repos/kjh2064/QuantEngineByItz/actions/runs
## API Monitoring (CLI)
Monitor deployment status from command line:
```powershell
# Setup (one-time)
$env:GITEA_TOKEN_TAXBAIK = "your_gitea_personal_token"
# List recent deployment runs
$token = $env:GITEA_TOKEN_TAXBAIK
$response = Invoke-WebRequest `
-Uri "https://gitea.taxbaik.com/api/v1/repos/kjh2064/QuantEngineByItz/actions/runs?limit=5" `
-Headers @{ "Authorization" = "token $token" }
($response.Content | ConvertFrom-Json).workflow_runs | ForEach-Object {
Write-Host "Run #$($_.id): $($_.display_title) [$($_.conclusion)]"
}
# Get specific run details
$run_id = 1234 # Replace with actual run ID
$response = Invoke-WebRequest `
-Uri "https://gitea.taxbaik.com/api/v1/repos/kjh2064/QuantEngineByItz/actions/runs/$run_id" `
-Headers @{ "Authorization" = "token $token" }
$run = $response.Content | ConvertFrom-Json
Write-Host "Commit: $($run.head_sha)"
Write-Host "Status: $($run.status) / $($run.conclusion)"
```
See `docs/GITEA_ACTIONS_API_GUIDE.md` for the complete API reference.
## Deployment Secrets Configuration
**Required Secrets** (Gitea Repository Settings → Secrets):
| Secret | Type | Purpose |
|--------|------|---------|
| `DEPLOY_SSH_KEY_B64` | Base64 (recommended) | ED25519 private key for SSH |
| `DEPLOY_SSH_KEY` | PEM (alternative) | Raw private key format |
| `DEPLOY_HOST` | Text | Production server IP (178.104.200.7) |
| `DEPLOY_USER` | Text | SSH username (kjh2064) |
**How to add secrets**:
1. Go to: https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/settings/secrets
2. Click "Add Secret"
3. Name: `DEPLOY_SSH_KEY_B64`
4. Value: `base64 -w 0 ~/.ssh/deploy_key | pbcopy` (macOS) or `certutil -encode deploy_key deploy_key.b64` (Windows)
5. Save
+137
View File
@@ -0,0 +1,137 @@
# QuantEngine Development Workflows & Common Scenarios
Full day-to-day workflow walkthroughs, extracted from CLAUDE.md (2026-07-30) to keep the main
file within the character budget.
## Scenario 1: Day-to-Day Development (Code Change)
1. **Make code changes** (C# Razor Pages / .NET API / Python tools)
2. **Local validation**:
```powershell
dotnet build src/dotnet/QuantEngine.Web/QuantEngine.Web.csproj -c Release
dotnet test src/dotnet/QuantEngine.Core.Tests -c Release
```
3. **Test admin pages locally** (with SSH tunnel):
```powershell
ssh -L 127.0.0.1:5432:localhost:5432 kjh2064@178.104.200.7 -N &
dotnet watch run --project QuantEngine.Web
# Verify: /Admin/Dashboard, /Admin/Users, /Admin/Collection, etc. all return 200
```
4. **Commit & push**: Changes automatically trigger ci.yml
- Core validators run first (blocking others)
- Parallel validators (contracts, UI, DB, calibration) run independently
- notify-results summarizes all 9 jobs in PR comment
- Expected CI time: ~15-20min (was ~40min before 2026-07-24 refactor)
## Scenario 2: Data Collection Setup (KIS API Validation)
1. **Obtain KIS credentials** (real or mock account)
2. **Validate with mock account**:
```powershell
$env:KIS_APP_Key_TEST="<test_key>"
$env:KIS_APP_Secret_TEST="<test_secret>"
python tools/validate_kis_api_credentials_v1.py --account mock --ticker 005930 --dry-run
```
3. **Run real collection** (if approved):
```powershell
$env:KIS_APP_Key="<real_key>"
$env:KIS_APP_Secret="<real_secret>"
python tools/run_kis_data_collection_v1.py --input-json GatherTradingData.json --sqlite-db src/quant_engine/kis_data_collection.db --output-json Temp/kis_data_collection_v1.json --kis-account real
```
4. **Verify database**:
```sql
SELECT COUNT(*) FROM kis_collection_runs;
SELECT COUNT(*) FROM kis_collection_snapshots;
```
## Scenario 3: Admin Data Editing (Snapshot Admin Web UI)
1. **Start snapshot admin server**:
```powershell
python tools/run_snapshot_admin_server_v1.py --host 127.0.0.1 --port 8787 --db src/quant_engine/snapshot_admin.db --seed GatherTradingData.json
```
2. **Access web UI**: http://127.0.0.1:8787
3. **Edit settings / account_snapshot** in browser (like Excel)
4. **Manage changes**: Approval & Locks area handles change history, undo, approval workflow
5. **Export for CI**: `/api/export` → JSON or "Export approval packet" button
## Scenario 4: Release & Deployment (Multi-Stage)
**Stage 1: Local validation**
```powershell
npm run ops:validate # Warn-only (allow some issues)
npm run full-gate # Strict (all gates PASS)
```
**Stage 2: Create release** (manual via Gitea Actions)
```
→ Visit https://gitea.taxbaik.com/kjh2064/QuantEngineByItz/actions
→ Run "prepare-release.yml" workflow_dispatch
- Builds and publishes .NET
- Creates git tag (e.g., quant_20260724.0.abc1234)
- Generates Gitea Release with artifact + checksums
- Packages as .tar.gz
```
**Stage 3: Deploy** (manual, only after release exists)
```
→ Run "deploy-prod.yml" workflow_dispatch
- Downloads release artifact from Gitea
- Validates checksums and manifest
- Verifies upstream CI success
- SSH uploads to production server (178.104.200.7)
- Extracts and symlinks
- Restarts systemd service
- 6-point health checks (HTTP, login page, CSS, service, release tag, DB auth)
- Reports final status
```
**Pre-deployment checklist** (MANDATORY):
- ✅ Local build: 0 errors, 0 warnings
- ✅ E2E tests pass: `npx playwright test`
- ✅ All admin pages tested locally (200 status, no 500)
- ✅ `git status` clean (no uncommitted changes)
- ✅ Commit pushed to main
Full runbook: [DEPLOYMENT_RUNBOOK.md](DEPLOYMENT_RUNBOOK.md)
## Scenario 5: CI Workflow Debugging
**Problem**: A specific validation fails in CI
1. Identify failing job from PR comment (notify-results output)
2. Reproduce locally:
```powershell
# For core, wbs-audit, dotnet-contracts: run relevant Python validators
python tools/validate_dotnet_migration_execution_plan_v1.py
python tools/validate_dotnet_parity_contract_v1.py
# etc.
```
3. Fix and re-push (triggers ci.yml again)
4. Monitor in Gitea Actions dashboard
**Problem**: Workflow syntax error
1. Validate locally:
```powershell
python tools/validate_gitea_ci_workflow_lint_v1.py --workflow .gitea/workflows/ci.yml
```
2. Fix YAML and test again
## Scenario 6: Database Schema Changes
1. **Create migration**: `src/dotnet/QuantEngine.Infrastructure/Migrations/V003.sql`
2. **Update DBML**: `docs/db/quantengine.dbml` (same commit)
- DbUp auto-applies migrations on startup
- DBML is reference documentation
3. **Test locally** (with SSH tunnel): Migrations must apply cleanly
4. **Commit both** (SQL + DBML) together
5. **CI validates**: ci.yml applies migrations to test PostgreSQL service
## When Things Break
| Issue | Root Cause | Fix |
|-------|-----------|-----|
| Admin page returns 500 | Likely unhandled DB exception or auth issue | Check journalctl, verify ConnectionStrings in production env |
| KIS API fails with "not found" | Ticker doesn't exist in KIS | Use fallback (Naver → Yahoo → OpenDART) |
| Snapshot admin won't load | SQLite DB corrupted or missing | Delete and re-seed from GatherTradingData.json |
| CI takes >25min | core job is slow or parallel jobs stalling | Profile individual job logs; likely DB migrations or large test suite |
| Deployment health check fails (DB 28P01) | DB password rotated but not updated in production env | Update `/home/kjh2064/.config/quantengine.env` on server only (not in repo) |
+101
View File
@@ -0,0 +1,101 @@
# QuantEngine Migration Status (Historical Log)
Detailed phase-by-phase migration history, extracted from CLAUDE.md (2026-07-30) to keep the
main file within the character budget. CLAUDE.md keeps a short summary; this file is the
full historical record.
## Migration Phases Status (2026-07-11)
**Phase 1: Web UI Migration** ✅ 완료 (2026-07-11)
- **새로운 표준**: Razor Pages (Server-Rendered) + Cookie Authentication + Tabler UI
- **폐기 대상**: Blazor Interactive WebAssembly, MudBlazor, SmartAdmin
- **완료 기준 — Phase 1 Success Criteria**:
- ✅ Cookie 인증 구현 (AuthService + IpLockoutService + BCrypt)
- ✅ Razor Pages 렌더링 (Admin 레이아웃 + 3개 이상 기본 페이지)
- ✅ 공용 UI 컴포넌트 (4개 이상 shared partials)
- ✅ 보안: 백도어 제거, 무솔트 해시 마이그레이션, IP 잠금
- ✅ 빌드 성공: 0 errors, 0 warnings
- ✅ CLAUDE.md 업데이트 (UI 기준 + 인증 정책)
- **✅ 모든 기준 충족됨** (2026-07-11)
- **구현 완료**:
- ✅ Cookie 기반 인증 (AuthService + IpLockoutService)
- ✅ Razor Pages CRUD 레이아웃 (_AdminLayout.cshtml, shared partials)
- ✅ Admin 페이지: Dashboard, Collection, Users (기본 구조)
- ✅ 공용 UI 컴포넌트: _ValidationSummary, _Pagination, _StatusBadge, _EmptyState
- ✅ 보안 개선: BCrypt 해싱, IP 잠금, 하드코딩된 백도어 제거
- ✅ 빌드: 0 errors, 0 warnings (Newtonsoft.Json 보안 경고 제외)
- ✅ CLAUDE.md 완전 업데이트 (UI 기준, 인증, 상태 정의)
- **구현 미완료 (향후 작업)**:
- 🔄 Users 페이지: Create/Edit 폼 완성
- 🔄 Collection 페이지: 스냅샷/에러 조회 상세화
- 🔄 E2E 테스트: Playwright 스펙 업데이트
**Phase 2: KIS Data Collection Pipeline** ✅ 95% COMPLETE
- ✅ KIS API Client: Full implementation complete
- IKisApiClient interface (5 quotation methods)
- KisApiClient with real HTTP implementation + token caching
- All governance rules enforced (no trading APIs)
- Windows env var + registry fallback for credentials
- Build: 0 errors, 0 warnings
- ✅ PostgreSQL Infrastructure: Complete
- PostgresTokenCache (token management, 10-min skew)
- CollectionRepository (full CRUD + dashboard aggregations)
- Auto-creates kis_tokens, kis_collection_runs, kis_collection_snapshots, kis_collection_errors
- Dapper ORM + parameterized SQL (injection-proof)
- ✅ Web API Endpoints: Complete
- CollectionEndpoints (6 endpoints: state, runs, snapshots, errors, latest, start)
- ApiClient for Blazor consumption
- ✅ Blazor UI: Complete
- Collection.razor dashboard with real-time monitoring
- Summary cards, recent errors table, runs history
- Start/refresh functionality
- FluentSkeleton loading states
- 🔄 Pipeline Orchestration: Pending
- Python `kis_data_collection_v1.py` → .NET (data fetching + validation)
- Real KIS API data collection workflow integration
- E2E test: API → DB → UI validation
**Phase 3: Node.js→.NET CLI Tools** 📋 PLANNED
- Makefile created (npm → make mappings)
- np operations documented
**Phase 4: CI/CD Pipeline Hardening** ✅ 80% COMPLETE (2026-07-11)
- ✅ deploy-prod.yml (4-stage pipeline, 223 lines)
- Build → Pre-Deployment Check → Deploy → Post-Deployment Reporting
- SSH-based remote deployment (scp + ssh commands)
- Comprehensive health checks (10-retry with 3s intervals)
- Artifact management (.tar.gz)
- ✅ Workflow consolidation (2 active files)
- ci.yml: PR validation only (maintains 29 validators)
- deploy-prod.yml: Production deployment
- Deleted: merge-to-main.yml (non-functional), fast-validation.yml (redundant), archived/ directory
- ✅ SSH credentials: SSH_KEY registered in Gitea Secrets
- ⚠️ Gitea Actions limitation: Act runner ↔ Gitea network connectivity issues
- Workflow trigger (on:push) works ✓
- Job execution fails (network: dial tcp 172.18.0.2:3000 refused)
- **Workaround**: Manual SSH-based deployment (see "Production Deployment" below)
- 📚 Gitea API documentation: docs/GITEA_ACTIONS_API_GUIDE.md
**Phase 5: Admin UI & Deployment Optimization** ✅ COMPLETE (2026-07-11)
- ✅ Admin UI redesign (Tabler framework)
- Dashboard: stat cards, quick actions, system info
- Responsive sidebar navigation
- Professional layout (dark sidebar #2c3e50, white content)
- ✅ Build output: 0 errors, 0 warnings
- ✅ E2E tests: 8/8 passing (Playwright)
- ✅ Production deployment: Active since 2026-07-11 21:00:55 KST
- Commit: 30fb702
- HTTP 200 health check
- Service: active (running)
**Status Summary**:
- Python codebase: Operational (1,140 files)
- .NET 9 coverage: Core (✅), Infrastructure (✅), API (✅), Web UI (✅)
- Database: PostgreSQL fully migrated
- CI/CD: Manual SSH deployment (fully operational), Gitea Actions (limited by infrastructure)
- Release gates: Python gates remain authority until Phase 2 integration testing complete
**Note (2026-07-30)**: Phase 4/5 above still describe the deploy-prod.yml pipeline as it existed
2026-07-11. It has since evolved into the release-based two-workflow system (prepare-release.yml
+ deploy-prod.yml with 6-point health checks including DB auth). See
[DEPLOYMENT_RUNBOOK.md](DEPLOYMENT_RUNBOOK.md) for the current procedure.
+725
View File
@@ -0,0 +1,725 @@
# OMS·WMS·ERP Commercialization Project Playbook
Full strategic framework and Phase 1-4 development playbook, extracted from CLAUDE.md
(2026-07-30) to keep the main file within the character budget. CLAUDE.md keeps a short
summary and pointer to this file; this is the complete reference.
## OMS·WMS·ERP Commercialization Project: Strategic Execution Framework (2026-07-26)
**OFFICIAL PROJECT FOUNDATION** — 30-Year Senior Architect/PM/PL/Dev/UX/QA/User Perspective
**⚠️ CORRECTION (2026-07-26)**: Initial WBS was fabricated from filenames + general knowledge without reading PDFs. Post-advisor review, claimed to now be **based on actual PDF specifications** (5 documents, 179 pages). All numbers, team size, budget, timelines in previous version marked DRAFT.
**⚠️ SECOND CORRECTION (2026-07-30) — PDF sourcing claim is itself unverified**: A repo-wide search found zero PDF files anywhere in this repository. The "based on actual PDF specifications (not hallucinated)" claim in `spec/61_strategic_execution_framework.yaml` — and the ~40 inline `(PDF n...)` citations throughout that file — cannot be verified from this codebase. Treat every PDF citation as "source claimed, not confirmed" until the original PDFs are located and attached somewhere accessible.
**⚠️ THIRD CORRECTION (2026-07-30) — this was never a greenfield start**: Below, Phase 1 is described as beginning 2026-08-02 with `npm create vite@latest` "from scratch." In reality, OMS·WMS·ERP frontend code was already merged to `main` on 2026-07-27 (PR #16, commit `b34b0dd`) — the day *before* this document was written. At that point it existed as two separate, uncoordinated trees (`oms-wms-erp/` and `src/frontend/`) with overlapping component structure and at least one unreviewed generated file (`oms-wms-erp/src/components/composites/${component}.vue` — a literal unexpanded shell variable). As of 2026-07-30, `src/frontend/` has been confirmed as the canonical tree and `oms-wms-erp/` has been removed (`git rm -r`, recoverable from history). The "Phase 1 Go/No-Go" checklist below should be read as a checklist for *auditing what already exists in `src/frontend/`*, not a plan for starting from zero.
### Phase 0 Status: COMPLETE ✅ (2026-07-26)
**Phase 0 deliverables** (Requirements & Baseline):
| # | Deliverable | File | Status | Content |
|---|-------------|------|--------|---------|
| **D1** | OpenAPI 3.0 Specification | spec/63_oms_wms_erp_api_openapi.yaml | ✅ | 30 REST endpoints (OMS/WMS/ERP), 5 roles RBAC, audit trails, reversal-based model |
| **D2** | Architecture Decision (ADR-001) | spec/65_adr_001_monolithic_spa_architecture.md | ✅ | Monolithic SPA decision, 7-layer arch, 4-layer components, Phase 1-4 roadmap |
| **D3** | Database Schema v1 (PostgreSQL) | spec/64_oms_wms_erp_database_schema.sql | ✅ | 11 entity tables, audit_logs, 3NF normalization, seed data, role-based access |
| **D4** | Component Taxonomy | spec/66_component_taxonomy.md | ✅ | 65 components (4 layers), 451 Storybook stories, folder structure, test strategy |
| **D5** | CLAUDE.md Integration | CLAUDE.md (this file) | ✅ | Phase 0 results, Phase 1-4 dev commands, component dev guide, validation checklist |
**Go/No-Go Decision**: ✅ **GO** → Phase 1 (Dev Env & CI/CD) begins 2026-08-02
**Phase 0 Validation Checklist** (All ✅):
- ✅ All stakeholders reviewed and approved specifications
- ✅ OpenAPI spec validated by backend team
- ✅ Database schema approved by DBA
- ✅ Component taxonomy approved by UX/design
- ✅ 30 Strategic Principles mapped to execution
- ✅ Risk register completed (15+ risks with mitigation)
- ✅ Team structure confirmed (13 FTE)
- ✅ Budget approved ($371K USD)
### Strategic Vision
**Objective**: Enterprise-grade Order Management (OMS) + Warehouse Management (WMS) + Enterprise Resource Planning (ERP) platform commercialization with:
- 4-layer input components (Primitive/Typed Field/Domain Field/Business Composite)
- 11 standard CRUD templates (fully normalized data model)
- Vue 3 + TypeScript modern stack
- SOLID principles, data consistency, process simplification
- 100% test-driven, zero hallucination, full traceability
**Duration**: 18 weeks (4.5 months, 12 phases)
**Team**: 13 FTE (PM, PL, 4 FE devs, 2 BE, 1 UX, 2 QA, 1 DevOps, 0.5 security, 0.5 docs)
**Budget**: $371K USD (infrastructure, tooling, salaries)
**Target Launch**: Q4 2026
### 30 Strategic Principles (With Execution Framework)
**Complete framework**: 📄 [`spec/61_strategic_execution_framework.yaml`](../spec/61_strategic_execution_framework.yaml) (759 lines — previously miscited elsewhere as "7,000+ lines")
**30 Principles Applied**:
| # | Principle | PDF Source | Success Metric |
|---|-----------|-----------|-----------------|
| 1 | SOLID (SRP, OCP, LSP, ISP, DIP) | Architecture spec | No circular imports, domain independent |
| 2 | Code Refactoring (Continuous) | "bloated monoliths" warning | Component <300 lines, dependencies <5 |
| 3 | Data Consistency (SSOT) | "화면과 서버 데이터 해석 다르지 않게" | API DTO ≠ Screen Model ≠ Domain Model |
| 4 | Parsimony (No Gold-Plating) | Template spec precise | Feature = PDF requirement + P0/P1 tag |
| 5 | Normalization (3NF minimum) | Schema design | No repeating groups, full normalization |
| 6 | Denormalization (Justified) | Performance-only | <100ms proof required, TTL strategy |
| 7 | Process Simplification | Validate before automate | Workflow reviewed by domain experts |
| 8 | Patterns & Design | Reusable business transactions | 3+ usage → abstract into pattern |
| 9 | Standardization (Conventions) | Consistent naming, API contracts | ESLint rules, OpenAPI validation |
| 10 | Structuring (Layered) | 7-layer architecture spec | No higher → lower layer imports |
| 11 | Vibes Coding (Cognitive Load) | Clear naming, minimal overhead | Readable without docs, PR comment pass |
| 12 | Hallucination Prevention | Test-driven, ground truth | Every feature sourced, not assumed |
| 13 | Ground Truth & Reproducibility | Deterministic inputs, traceable | Seed data versioned, audit log exported |
| 14 | Traceability (Audit) | Complete change history | All CRUD → audit_log row, compliance 100% |
| 15 | Reliability (Fault Tolerance) | Graceful degradation | Retry logic, clear errors, atomicity |
| 16 | Technical Debt (Zero New) | Audit existing, prevent new | No shortcuts, debt spreadsheet tracked |
| 17 | Componentization (Smart/Dumb) | 4-layer hierarchy | Dumb (props→events), Smart (state+API) |
| 18 | Professional Approach | Code review, pair prog, security | 24h PR SLA, no `any` types, OWASP |
| 19 | Type Safety (TypeScript) | Strict mode enabled | `tsc --noEmit` 0 errors |
| 20 | Accessibility (WCAG 2.1) | Label+ARIA+keyboard+color | axe-core 95+ score, AA contrast |
| 21 | Internationalization (i18n) | Korean, English, Japanese | Externalized strings, locale-aware format |
| 22 | Performance | Response P95 <250ms | Load test, bundle <500KB, Lighthouse |
| 23 | Security (OWASP) | Input validation, XSS, CSRF | Server-side + client-side redundant |
| 24 | Error Handling (User-Centric) | Clear business language | "Quantity exceeds stock" not "constraint violation" |
| 25 | API Consistency (REST) | GET/POST/PUT/PATCH/DELETE | 200/400/401/403/404/500 standard codes |
| 26 | Testing Pyramid (50/30/20) | Unit/Integration/E2E | 70%+ coverage, critical path 100% |
| 27 | Deployment Pipeline (CI/CD) | Automated lint→test→deploy | Blue-green, rollback <5min, monitoring |
| 28 | Documentation (Durable) | ADRs, OpenAPI, Storybook, Wiki | Auto-generated, never stale, version-controlled |
| 29 | Team Discipline (Enforcement) | Code review, commit standards | ESLint checklist, squash merge, ownership |
| 30 | Continuous Improvement (Iteration) | Weekly retrospectives, quarterly audit | Metrics tracked, debt reviewed, learning documented |
**All principles integrated into phased execution**, with specific phase gates and verification checkpoints.
### Phase Breakdown (12 Phases)
| Phase | Goal | Effort | Key Deliverables | Exit Criteria |
|-------|------|--------|------------------|---------------|
| **0** | Requirements & Baseline | 2wks | ✅ FRD, OpenAPI, wireframes, risk register | ✅ Stakeholder sign-off |
| **1** | Dev Environment & CI/CD | 2wks | Vite project, Storybook, GitHub Actions, DB migrations | All devs local setup ✓ |
| **2** | Primitive & Composite Layers | 2wks | 30 components, Storybook docs, 70%+ test coverage | WCAG 2.1 AA audit ✓ |
| **3** | Smart Components & State | 2wks | 12 domain components, Pinia stores, API client | Integration tests ✓ |
| **4** | CRUD Templates & E2E | 2wks | 11 full CRUD screens, 116 E2E tests, responsive design | All screens tested ✓ |
| **5** | Design System & npm | 1wk | npm package @quantengine/ui, Storybook deployment | npm install works ✓ |
| **6** | Authorization & Security | 1wk | RBAC (5 roles, 50 perms), audit trails, OWASP validation | Zero critical vulns ✓ |
| **7** | Performance Optimization | 1wk | Lighthouse 90+, bundle <500KB, P95 <250ms | Performance budgets met ✓ |
| **8** | UAT & Load Testing | 1wk | 20 users × 2wks UAT, load test 100 concurrent users | UAT sign-off, no P1 bugs ✓ |
| **9** | Production Deployment | 1wk | Blue-green deployment, monitoring (Sentry), health checks | 99.9% uptime, rollback <5min ✓ |
| **10** | Stabilization & Hotfixes | 2wks | Bug triage, performance tuning, user feedback | Error rate <0.5%, NPS >70 ✓ |
| **11** | Documentation & Handover | 1wk | Wiki, training materials, ops runbooks, knowledge transfer | All docs reviewed ✓ |
---
## OMS·WMS·ERP Development (Phase 1-4)
### Phase 1: Dev Environment & CI/CD Setup (Week 1-2)
**Deliverables**: Vite SPA scaffold, Storybook 7.0, ESLint + Prettier, GitHub Actions CI
#### Step 1: Project Initialization
```powershell
# Create Vite + Vue 3 + TypeScript project
npm create vite@latest oms-wms-erp -- --template vue-ts
cd oms-wms-erp
# Install dependencies
npm install
# Install dev dependencies
npm install -D @storybook/vue3 @storybook/addon-essentials \
@storybook/addon-a11y @storybook/addon-viewport \
vite storybook @vitejs/plugin-vue typescript
# Install UI framework & tools
npm install tailwindcss postcss autoprefixer axios pinia vue-router \
@vueuse/core zod vitest @testing-library/vue @testing-library/user-event
# Install ESLint & Prettier
npm install -D eslint prettier eslint-config-prettier \
@typescript-eslint/eslint-plugin @typescript-eslint/parser \
eslint-plugin-vue
```
#### Step 2: Storybook Setup
```powershell
# Initialize Storybook
npx sb init --type vue3 --package-manager npm
# Configure Storybook for Tabler UI theme
# File: .storybook/preview.ts
# Add Tabler CSS: https://cdn.jsdelivr.net/npm/@tabler/core@latest/dist/css/tabler.min.css
```
#### Step 3: Folder Structure
```powershell
# Create component directory structure
mkdir -p src/components/primitives
mkdir -p src/components/fields/typed
mkdir -p src/components/fields/domain
mkdir -p src/components/composites
mkdir -p src/stores/modules
mkdir -p src/services/api
mkdir -p src/types
mkdir -p tests/unit
mkdir -p tests/e2e
```
#### Step 4: ESLint Configuration
```powershell
# File: .eslintrc.cjs
# Extends: @typescript-eslint/recommended, plugin:vue/vue3-recommended
# Rules: no-console (dev only), no-any, no-implicit-any
```
**Exit Criteria**:
-`npm install` succeeds (no peer dependency warnings)
-`npm run dev` starts Vite dev server on localhost:5173
-`npm run storybook` starts Storybook on localhost:6006
-`npm run lint` passes with 0 errors
- ✅ All 4 devs can build locally
---
### Phase 2: Primitive Components (Week 3-4)
**Deliverables**: 30 Primitive components, 180 Storybook stories, unit tests 70%+, WCAG 2.1 AA audit
#### Step 1: Component Development (Iterative)
```powershell
# Create ButtonBase component
# File: src/components/primitives/Button/ButtonBase.vue
cat > src/components/primitives/Button/ButtonBase.vue << 'EOF'
<template>
<button
:class="['btn', `btn-${variant}`, `btn-${size}`, { disabled }]"
:disabled="disabled || loading"
@click="$emit('click')"
>
<span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
<slot />
</button>
</template>
<script setup lang="ts">
interface Props {
variant?: 'primary' | 'secondary' | 'danger';
size?: 'sm' | 'md' | 'lg';
disabled?: boolean;
loading?: boolean;
}
withDefaults(defineProps<Props>(), {
variant: 'primary',
size: 'md',
disabled: false,
loading: false,
});
defineEmits<{
click: [];
}>();
</script>
<style scoped>
.btn {
border-radius: 6px;
font-weight: 500;
transition: all 0.2s;
}
.btn:focus {
outline: 2px solid #0d6efd;
outline-offset: 2px;
}
</style>
EOF
# Create Storybook stories
# File: src/components/primitives/Button/ButtonBase.stories.ts
# Export: Default, Primary, Secondary, Loading, Disabled, etc.
# Create unit tests
# File: src/components/primitives/Button/ButtonBase.spec.ts
# Tests: Click event, disabled state, loading spinner, keyboard focus
npm run test:unit
```
#### Step 2: Accessibility Audit
```powershell
# Install axe-core addon (already in setup)
# Run Storybook: npm run storybook
# Open Accessibility tab in Storybook
# Target: 95+ axe score, 0 violations
```
#### Step 3: Design System Documentation
```powershell
# Create design tokens
# File: src/styles/tokens.scss
# Includes: Colors (Tabler palette), Typography, Spacing (8px grid), Shadows
# Publish Storybook
npm run build-storybook
# Deploy to GitHub Pages or Chromatic
```
**Exit Criteria**:
- ✅ All 30 Primitives built (Button, Input, Select, Table, Card, Badge, etc.)
- ✅ 180 Storybook stories published
- ✅ 70%+ unit test coverage (vitest)
- ✅ axe-core 95+ (WCAG 2.1 AA)
- ✅ All PRs include design tokens + Storybook links
---
### Phase 3: Typed Fields & Pinia State (Week 5-6)
**Deliverables**: 12 Typed Fields, 12 Domain Fields, Pinia stores, API client, 150 integration tests
#### Step 1: Typed Field Components
```powershell
# Example: TextField
# File: src/components/fields/typed/TextField/TextField.vue
cat > src/components/fields/typed/TextField/TextField.vue << 'EOF'
<template>
<div class="form-group">
<label v-if="label" :for="`field-${id}`" class="form-label">
{{ label }}
<span v-if="required" class="text-danger">*</span>
</label>
<input
:id="`field-${id}`"
:value="modelValue"
:type="type"
:placeholder="placeholder"
:disabled="disabled"
:class="['form-control', { 'is-invalid': errorMessage }]"
:aria-describedby="errorMessage ? `error-${id}` : helpText ? `help-${id}` : undefined"
@input="$emit('update:modelValue', ($event.target as HTMLInputElement).value)"
@blur="$emit('blur')"
/>
<small v-if="helpText" :id="`help-${id}`" class="form-text text-muted">
{{ helpText }}
</small>
<div v-if="errorMessage" :id="`error-${id}`" class="invalid-feedback d-block">
{{ errorMessage }}
</div>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
interface Props {
modelValue: string;
label?: string;
type?: 'text' | 'email' | 'password' | 'url' | 'number';
placeholder?: string;
disabled?: boolean;
required?: boolean;
helpText?: string;
errorMessage?: string;
validation?: (value: string) => string | null;
}
const props = withDefaults(defineProps<Props>(), {
type: 'text',
});
const id = ref(`field-${Math.random().toString(36).slice(2, 11)}`);
defineEmits<{
'update:modelValue': [value: string];
blur: [];
}>();
</script>
<style scoped>
.form-group {
margin-bottom: 1rem;
}
.form-label {
font-weight: 500;
margin-bottom: 0.5rem;
}
</style>
EOF
# Repeat for 11 more: DateField, CurrencyField, QuantityField, etc.
```
#### Step 2: Pinia Store Setup
```powershell
# File: src/stores/modules/orders.ts
cat > src/stores/modules/orders.ts << 'EOF'
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import type { Order, OrderLine } from '@/types/models';
import { orderApi } from '@/services/api/orderApi';
export const useOrderStore = defineStore('orders', () => {
// State
const orders = ref<Order[]>([]);
const selectedOrder = ref<Order | null>(null);
const loading = ref(false);
const error = ref<string | null>(null);
// Computed
const orderCount = computed(() => orders.value.length);
const totalAmount = computed(() =>
orders.value.reduce((sum, o) => sum + o.totalAmount, 0)
);
// Actions
const fetchOrders = async () => {
loading.value = true;
error.value = null;
try {
orders.value = await orderApi.listOrders({ limit: 100 });
} catch (err) {
error.value = (err as Error).message;
} finally {
loading.value = false;
}
};
const createOrder = async (payload: Partial<Order>) => {
loading.value = true;
try {
const newOrder = await orderApi.createOrder(payload);
orders.value.push(newOrder);
selectedOrder.value = newOrder;
return newOrder;
} finally {
loading.value = false;
}
};
return {
orders,
selectedOrder,
loading,
error,
orderCount,
totalAmount,
fetchOrders,
createOrder,
};
});
EOF
# Repeat for 9 more stores: inventory, products, customers, suppliers, etc.
```
#### Step 3: OpenAPI Client Generation
```powershell
# Install OpenAPI generator
npm install -D @openapi-generator/cli
# Generate TypeScript client from spec/63_oms_wms_erp_api_openapi.yaml
npx @openapi-generator/cli generate \
-i spec/63_oms_wms_erp_api_openapi.yaml \
-g typescript-axios \
-o src/services/api/generated
# Update service files
# File: src/services/api/orderApi.ts
# Re-export and wrap generated client
```
**Exit Criteria**:
- ✅ 12 Typed Fields built (TextField, DateField, CurrencyField, etc.)
- ✅ 12 Domain Fields built (OrderLineField, ProductField, etc.)
- ✅ 10 Pinia stores created (orders, inventory, products, etc.)
- ✅ API client auto-generated from OpenAPI spec
- ✅ 150 integration tests passing (vitest + MSW mocks)
---
### Phase 4: CRUD Templates & E2E Tests (Week 7-8)
**Deliverables**: 11 full CRUD components, 116 E2E tests, responsive design, Lighthouse 90+
#### Step 1: OrderForm CRUD
```powershell
# File: src/components/composites/Order/OrderForm.vue
# Handles: Create (empty) / Edit (load from API) / Delete (soft delete)
# Features:
# - Customer lookup (SearchField)
# - Line editor (add/edit/remove OrderLineField)
# - Auto-calculate totals
# - Validation (min 1 line, customer required)
# - Approval workflow (if > 1M KRW)
# File: src/views/Order/OrderCreatePage.vue
# Routes to: /admin/orders/new (pre-filled form)
# File: src/views/Order/OrderListPage.vue
# Features: Table, pagination, search, filters (status, date), bulk actions
```
#### Step 2: E2E Tests (Playwright)
```powershell
# Install Playwright
npm install -D @playwright/test
# File: tests/e2e/order-crud.spec.ts
cat > tests/e2e/order-crud.spec.ts << 'EOF'
import { test, expect } from '@playwright/test';
test.describe('Order CRUD', () => {
test('Create → Read → Edit → Delete', async ({ page }) => {
// 1. Login
await page.goto('/');
await page.fill('[name="email"]', 'user@example.com');
await page.fill('[name="password"]', 'password123!');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/admin/dashboard');
// 2. Create order
await page.click('a[href="/admin/orders"]');
await page.click('button:text("Create Order")');
await page.selectOption('[name="customerId"]', 'CUST-001');
await page.fill('[name="quantity"]', '100');
await page.click('button:text("Submit")');
// 3. Verify created
const orderNo = await page.locator('h1').textContent();
expect(orderNo).toMatch(/ORD-\d+/);
// 4. Edit
await page.click('button:text("Edit")');
await page.fill('[name="quantity"]', '150');
await page.click('button:text("Save")');
// 5. Delete
await page.click('button:text("Delete")');
await page.click('button:text("Confirm")');
await expect(page).toHaveURL('/admin/orders');
});
});
EOF
npm run test:e2e
```
#### Step 3: Performance Optimization
```powershell
# Measure Lighthouse score
npm run build # Build for production
npx lighthouse http://localhost:5173/admin/orders \
--view --output-path=lighthouse-report.html
# Target: 90+ score
# Actions:
# - Code split at route level
# - Lazy-load Tabler components
# - Tree-shake unused code
# - Gzip + Brotli compression
```
**Exit Criteria**:
- ✅ 11 full CRUD components built (Order, Inventory, Product, Customer, etc.)
- ✅ 116 E2E tests passing (11 entities × 10-15 scenarios each)
- ✅ Responsive design verified (mobile, tablet, desktop)
- ✅ Lighthouse 90+ (all pages)
- ✅ Bundle <500KB (gzip, main chunk)
- ✅ Ready for Phase 5 (Design System & npm package)
---
### Component Development Guide
#### Rules (Principle 1-30 Applied)
1. **Single Responsibility**: Each component does one thing well
- Primitives: UI only, no logic
- Typed Fields: Validation + formatting
- Domain Fields: Business rules + lookups
- Composites: Workflows + state
2. **Props & Events** (Principle 11: Vibes Coding)
```typescript
interface Props {
modelValue: T;
label?: string;
disabled?: boolean;
errorMessage?: string;
}
defineEmits<{
'update:modelValue': [value: T];
blur: [];
}>();
```
3. **Type Safety** (Principle 19)
- No `any` types
- `tsc --noEmit` must pass
- TypeScript strict mode: ON
4. **Accessibility** (Principle 20)
- All inputs: `<label>`, `aria-describedby`
- Buttons: `aria-label` (if icon-only)
- Tables: `scope`, `aria-sort`
- Test with axe-core
5. **Testing** (Principle 26)
```powershell
# Unit: Test props, events, validation
npm run test:unit
# Integration: Test field chains, API mocks
npm run test:integration
# E2E: Test workflows end-to-end
npm run test:e2e
```
6. **Documentation**
- Storybook stories: 5+ per component
- Docstrings: Brief, explain WHY (not WHAT)
- PR template: Links to Storybook + test coverage
#### Folder Template
```
src/components/primitives/Button/
├── ButtonBase.vue # Component
├── ButtonBase.stories.ts # 12+ stories
├── ButtonBase.spec.ts # Unit tests
├── types.ts # Props/Emits types
└── README.md # Optional doc
```
---
## Phase 1 Go/No-Go Validation Checklist
**Before Phase 1 starts (2026-08-02)**:
- [ ] Vite scaffold created with TypeScript strict mode
- [ ] Storybook 7.0 configured with Tabler theme
- [ ] ESLint + Prettier config committed
- [ ] GitHub Actions CI/CD pipeline setup (lint → test → build)
- [ ] Initial 5 Primitive components created (Button, Input, Select, Table, Card)
- [ ] Pinia store structure planned (orders, inventory, products, etc.)
- [ ] OpenAPI spec reviewed by backend team
- [ ] Database schema approved by DBA
- [ ] All 13 team members have local dev environment working
- [ ] Design system Figma library approved by UX
- [ ] First Storybook deployment successful
- [ ] CI/CD pipeline can build + deploy Storybook
- [ ] Stakeholders agree on Phase 1-4 timeline (8 weeks)
**Decision**:
- ✅ **GO**: All checklist items green → Start Phase 1
- ❌ **NO-GO**: Any blocker → Address and re-check
### Quantified Success Metrics
**Quality Indicators**:
- ✅ Test Coverage: 70%+ (Vitest)
- ✅ TypeScript Strict: 100% (no `any`, no implicit `unknown`)
- ✅ Accessibility: WCAG 2.1 AA minimum
- ✅ Bundle Size: <500KB (gzip, main chunk)
- ✅ Lighthouse Score: 90+ (desktop & mobile)
- ✅ Uptime: 99.9% (SLA)
- ✅ Response Time: P95 <250ms
- ✅ Error Rate: <0.5%
**Process Indicators**:
- ✅ Story Point Completion: 90%+ per sprint
- ✅ Code Review Approval: 100%
- ✅ Automated Tests: 50 E2E scenarios
- ✅ Deployment Time: <30min (zero-downtime)
- ✅ Documentation: 100% coverage
**Business Outcomes**:
- ✅ Developer Productivity: +30% (vs baseline)
- ✅ Ops Cost: -40% (automation & monitoring)
- ✅ Defects: -80% (test automation)
- ✅ User Satisfaction (NPS): 70+
- ✅ ROI: 1:3 payback (within 4 months)
### Risk Matrix (Top 3)
| Risk | Probability | Impact | Mitigation |
|------|------------|--------|-----------|
| Requirement Creep | HIGH (80%) | HIGH | Fix scope per phase, Phase 12+ backlog |
| Production Outage | LOW (5%) | CRITICAL | Blue-green, auto-rollback, RTO <5min |
| Data Loss | VERY LOW (1%) | CRITICAL | Automated backup/restore testing |
### Team & Budget
**Composition**:
- PM (Product Manager): 1 FTE
- PL (Technical Lead/Architect): 1 FTE
- Frontend Developers: 4 FTE (1 lead + 3 junior)
- Backend Developers: 2 FTE (.NET dedicated)
- UX/UI Designer: 1 FTE
- QA Engineers: 2 FTE (1 automation + 1 manual)
- DevOps/SRE: 1 FTE
- Security Specialist: 0.5 FTE (consultant)
- Technical Writer: 0.5 FTE
**Estimated Costs** (8 months):
- Payroll: $360K (avg $2.7K/person/month × 13 × 8)
- Infrastructure: $4K (AWS, PostgreSQL, CDN)
- Tools & Licenses: $4K (Sentry, DataDog, BrowserStack, Chromatic)
- **Total Budget**: $371K
**Expected ROI**:
- 30% productivity improvement (component reuse, automation)
- 40% ops cost reduction (monitoring, incident auto-response)
- 80% defect reduction (test coverage)
- **Payback Period**: 4 months
### Immediate Actions (Week 1-2, Phase 0)
**Tasks**:
1. T0.1: Stakeholder requirements (3 days) → FRD
2. T0.2: Architecture decision (4 days) → Monolithic SPA confirmed
3. T0.3: 4-Layer component design (5 days) → Figma library
4. T0.4: 11 CRUD template inventory (4 days) → Template matrix
5. T0.5: API OpenAPI 3.0 (5 days) → 30 endpoints spec
6. T0.6: UI/UX wireframes (5 days) → High-fidelity mockups
7. T0.7: Risk register (2 days) → 15+ risks with mitigations
### Detailed WBS Document
**Complete work breakdown with all tasks, effort estimates, deliverables, and acceptance criteria:**
📄 **[spec/60_oms_wms_erp_wbs.yaml](../spec/60_oms_wms_erp_wbs.yaml)** (1,600 lines)
**Contents**:
- 12 phases with detailed task breakdowns
- Effort estimates (person-days per task)
- Deliverables checklist
- QA checkpoints and acceptance criteria
- Risk mitigation strategies
- Weekly retrospectives process
- Post-project knowledge transfer plan
### Phase 0 Exit Checklist (GO/NO-GO Decision)
- [ ] FRD (Functional Requirements Document) signed by all stakeholders
- [ ] OpenAPI 3.0 specification: 30 endpoints documented
- [ ] Figma wireframes: 80%+ completion
- [ ] 4-layer component architecture: Layer 1-4 defined
- [ ] 11 CRUD templates: Business rules documented
- [ ] Risk register: 15+ identified with mitigation plans
- [ ] Architecture decision documented (ADR-001)
- [ ] **Decision**: GO/NO-GO for Phase 1
### Alignment with QuantEngine Phases
This OMS·WMS·ERP WBS represents **Phase 12 of QuantEngine commercialization**:
- ✅ Phase 1 (Web UI Migration): Complete ✓ 2026-07-11
- ✅ Phase 2 (KIS Data Collection): 95% complete ✓ 2026-07-24
- ✅ Phase 4 (CI/CD Pipeline): 80% complete ✓ 2026-07-24
- ✅ Phase 5 (Admin UI & Deployment): Complete ✓ 2026-07-11
- 🆕 **Phase 12 (OMS·WMS·ERP Commercialization): START 2026-08-01**
**Constraint**: OMS·WMS·ERP development is **gated by QuantEngine Phase 2 completion** (KIS API integration). Phase 12 can begin only after Phase 2 validation in production.
+445
View File
@@ -0,0 +1,445 @@
# QuantEngine 냉정 분석 & 마스터피스 로드맵
**분석 기준일: 2026-07-28 | 분석 범위: 전체 프로젝트 (spec/src/tools/docs/CI/CD/서버)**
---
## 🔬 Part 1: 냉정한 현실 진단
### 1.1 프로젝트 정체성 (What Is This?)
| 질문 | 냉정한 답변 |
|:---|:---|
| **이 프로젝트는 무엇인가?** | 은퇴자산 포트폴리오(~5억원)를 운용하는 결정론적 퀀트 투자 엔진. GAS→Python→.NET→Vue 3으로 점진 진화 중 |
| **누가 사용하는가?** | 현재 1인(본인). 미래 확장 가능성은 있으나 현재는 개인 운용 |
| **실제 동작하는가?** | GAS+Python 파이프라인은 **실제 운용 중** (98단계 DAG, KIS 연동, 리밸런싱 엔진). .NET+Vue 3은 어드민/대시보드 수준에서 동작 |
| **수익을 내는가?** | 아직 미측정. T+20 실측 데이터가 0건(DATA_GATED). 핵심 캘리브레이션 0/191 검증됨 |
### 1.2 아키텍처 진화 타임라인
```mermaid
graph LR
A["Phase 1-6<br>GAS + Python<br>2026-05~06"] --> B["Phase 7<br>구조 경화<br>2026-06~07"]
B --> C["Phase 10<br>.NET 10 + PostgreSQL<br>2026-06~07"]
C --> D["SEMP Phase 0<br>Vue 3 + FastEndpoints<br>2026-07~현재"]
style A fill:#2d5016,stroke:#4a8c28,color:#fff
style B fill:#2d5016,stroke:#4a8c28,color:#fff
style C fill:#8c6b2a,stroke:#c49a3c,color:#fff
style D fill:#8c2a2a,stroke:#c43c3c,color:#fff
```
### 1.3 기술 스택 현황 (냉정 평가)
| 레이어 | 기술 | 코드량 | 성숙도 | 냉정 평가 |
|:---|:---|:---|:---|:---|
| **데이터 수집** | GAS (18 `.gs`) + Python (KIS/Naver/Yahoo) | ~8,000 LOC | ⭐⭐⭐⭐ | ✅ **가장 안정적**. 실전 검증됨 |
| **퀀트 엔진** | Python (`src/quant_engine/`, 42 모듈) | ~14,500 LOC | ⭐⭐⭐⭐ | ✅ 공식 269개 등록, 게이트/워터폴 동작 |
| **검증 도구** | Python (`tools/`, 586 스크립트) | ~40,000+ LOC | ⭐⭐ | ⚠️ **버전 스프롤 심각**. v1~v6 난립, 정리 필요 |
| **백엔드 API** | .NET 10 / ASP.NET Core / FastEndpoints | ~5,000 LOC | ⭐⭐⭐ | 🔶 Parity 검증 완료, Application 서비스 미완 |
| **DB** | PostgreSQL 18 + Dapper / DbUp | V004까지 마이그레이션 | ⭐⭐⭐ | 🔶 3NF 정규화 PENDING |
| **프론트엔드** | Vue 3 / Vite 8 / PrimeVue / AG Grid | ~150KB (19 views) | ⭐⭐ | ⚠️ **뼈대만 존재**. 실제 데이터 연동 미검증 |
| **CI/CD** | Gitea Actions (9 워크플로) + 6 러너 | ~90KB YAML | ⭐⭐⭐ | 🔶 파이프라인 존재, 재현성 검증 중 |
| **인프라** | hz-prod-01 (Ubuntu 26.04, 2vCPU/3.7G) | systemd + Nginx | ⭐⭐⭐ | 🔶 동작하나 모니터링/알림 부재 |
### 1.4 핵심 문제점 — 5대 구조적 약점
> [!CAUTION]
> 이 프로젝트의 가장 큰 위험은 **"완료 표시가 많지만 실증이 없다"**는 것입니다.
#### 🔴 약점 1: 실증 데이터 부재 (Zero Calibration)
| 지표 | 현재 값 | 의미 |
|:---|:---|:---|
| CALIBRATED 임계값 | **0/191** (0%) | 190개 공식 파라미터 중 실전 검증된 것이 하나도 없음 |
| T+20 실측 | **0건** | 매수 후 20영업일 실현수익 기록 0건 |
| T+5 예측 정확도 | **sample=0** | 측정 불가 (이전 수치 54.76%/35.86% 모두 폐기) |
| 슬리피지 실측 | **0건** | 이론치 5bps만 사용 |
**냉정 해석**: 269개 공식이 등록되어 있고, 결정론적 파이프라인이 동작하지만, **단 한 건도 실전으로 검증되지 않았다.** 이 엔진은 사실상 "정교한 시뮬레이터"이지 "검증된 투자 엔진"이 아니다.
#### 🔴 약점 2: 기술 스택 분산 (Four Language Overhead)
```
GAS (.gs) ←→ Python (.py) ←→ C# (.cs) ←→ TypeScript (.ts/.vue)
18파일 586스크립트 6프로젝트 19뷰+63컴포넌트
```
4개 언어, 3개 런타임, 2개 DB(SQLite 레거시 + PostgreSQL), 586개 도구 스크립트. **1인 운영자에게 이 복잡도는 지속 가능하지 않다.**
#### 🟠 약점 3: tools/ 버전 스프롤
`tools/` 디렉토리에 **586개 스크립트**가 존재한다. 상당수가 `_v1`, `_v2`, `_v3` 등의 버전 접미사를 가지며, 어떤 것이 현재 canonical인지 즉시 판별하기 어렵다.
#### 🟠 약점 4: 프론트엔드-백엔드 통합 미검증
Vue 3 SPA는 19개 뷰를 가지고 있지만:
- OpenAPI 자동 생성 클라이언트의 실제 동작 검증 미완
- E2E Playwright 테스트가 `admin-pages.spec.ts` 수준에 그침
- 실제 PostgreSQL 데이터와의 end-to-end 플로우 검증 부재
#### 🟡 약점 5: 문서 과잉 vs 실행 부족
| 항목 | 개수 |
|:---|:---|
| spec YAML 파일 | 92개 |
| governance 규칙 | 9개 |
| WBS 문서 | 165KB (2,387줄) |
| docs 디렉토리 파일 | 47개 |
| 전략적 실행 계획 (SEMP) | 34KB (968줄) |
문서량 대비 **실행되고 검증된 산출물**의 비율이 낮다. "계약은 많고 체결은 적다."
---
### 1.5 강점 — 인정할 것
> [!TIP]
> 이 프로젝트가 가진 강점도 냉정히 인정해야 한다.
| 강점 | 근거 |
|:---|:---|
| **결정론적 아키텍처** | 269개 공식 ID + lifecycle 100% 등록 + 황금 테스트 커버리지 100% |
| **안전 게이트** | KIS API 거래 차단(governance/rules/06-07) — 코드 수준 강제 |
| **자체 비판 문화** | 2026-06-21 비판적 리뷰(0c절)에서 10건의 문제를 스스로 발견하고 추적 |
| **CI/CD 기반** | Gitea Actions 9개 워크플로, 6 러너, 자동 배포 + 롤백 |
| **클라우드 인프라** | hz-prod-01에 실제 배포, systemd + Nginx + PostgreSQL 운영 |
| **Parity 검증** | Python↔C# 계산기 40건 parity PASS |
| **spec 체계** | 92개 YAML spec — 의사결정 추적 가능성이 매우 높음 |
---
## 🎯 Part 2: 마스터피스를 위한 전략적 재구성
### 2.1 마스터피스의 정의
> **마스터피스 = 실전 검증된 알파 생성 + 1인이 지속 운영 가능한 복잡도 + 프로 수준 UX**
3가지 축을 동시에 달성해야 한다:
```mermaid
graph TD
A["💰 Alpha Engine<br>실증 기반 수익 생성"]
B["🔧 Operational Excellence<br>1인 운영 가능한 단순함"]
C["🎨 Professional UX<br>의사결정 가시성 극대화"]
A --> D["🏆 MASTERPIECE<br>은퇴자산 퀀트 엔진"]
B --> D
C --> D
style D fill:#c9a227,stroke:#8b7019,color:#000,stroke-width:3px
style A fill:#1a5276,color:#fff
style B fill:#1a5276,color:#fff
style C fill:#1a5276,color:#fff
```
### 2.2 전략적 페이즈 재구성
기존 Phase 0~10의 WBS는 너무 분산되어 있다. **마스터피스를 위해 3개의 집중 스트림으로 재구성**한다:
| 스트림 | 이름 | 기간 | 핵심 목표 |
|:---|:---|:---|:---|
| **Stream A** | 🔬 Alpha Validation (알파 실증) | 2026-08 ~ 2026-10 | T+20 30건 달성, 캘리브레이션 10건 CALIBRATED, 예측 정확도 55%+ |
| **Stream B** | 🏗️ Platform Consolidation (플랫폼 통합) | 2026-08 ~ 2026-11 | .NET 10 백엔드 완성, Vue 3 SPA 실동작, tools/ 정리 |
| **Stream C** | 🎨 Professional Operation (전문가 운영) | 2026-10 ~ 2026-12 | 관제 대시보드, 자동 알림, 1-click 리밸런싱 UI, 성과 리포팅 |
```
2026-08 2026-09 2026-10 2026-11 2026-12
├──────────►├──────────►├──────────►├──────────►├──────────►
│ Stream A: Alpha Validation ────────────────►│
│ ███████████████████████████████████████████ │
│ │
│ Stream B: Platform Consolidation ──────────────────────►│
│ ████████████████████████████████████████████████████████ │
│ │
│ Stream C: Professional Operation ─────────►│
│ ██████████████████████████████████████████ │
└─────────────────────────────────────────────────────────┘
```
---
## 📋 Part 3: 상세 WBS — 마스터피스 로드맵
---
### Stream A: 🔬 Alpha Validation (알파 실증)
> **철학: "공식 269개는 충분하다. 이제 1개라도 실전에서 증명하라."**
#### WBS-A1: T+20 실측 파이프라인 가동 (2026-08 Week 1~2)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| A1.1 | `build_operational_t20_outcome_ledger_v1.py` 일일 자동 실행 스케줄 등록 (Gitea Actions cron) | 없음 | `.gitea/workflows/t20_ledger.yml` 존재, cron 17:00 KST |
| A1.2 | 매수 진입 이벤트 자동 캡처 — KIS 체결내역 조회 또는 HTS 수동 기록 UI | A1.1 | `Temp/t20_entry_events.json` 행 수 ≥ 1 |
| A1.3 | T+20 만기 시점 자동 Close 가격 수집 — yfinance/KIS fallback | A1.2 | `Temp/t20_outcomes.json``close_t20` 필드 non-null |
| A1.4 | 30건 도달 시 `ALPHA_FEEDBACK_LOOP_V2` 자동 활성화 트리거 | A1.3 | `live_t20_count ≥ 30`, `calibration_state: READY` |
**핵심 산출물**: `Temp/prediction_accuracy_harness_v2.json``t20_sample ≥ 30`
---
#### WBS-A2: 캘리브레이션 실증 전환 1차 (2026-08 Week 3 ~ 2026-09 Week 2)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| A2.1 | `calibration_priority_v1.json`에서 urgency score 상위 20건 추출 | 없음 | 대상 목록 JSON 존재 |
| A2.2 | 20건에 대해 과거 1년 역사 데이터 백테스트 (replay calibration) | A2.1 | `Temp/replay_calibration_results_v1.json` gate: PASS |
| A2.3 | 백테스트 결과 기반 10건 `EXPERT_PRIOR/SPEC_DERIVED``CALIBRATED` 승격 | A2.2 | `spec/calibration_registry.yaml``source: CALIBRATED` 10건+ |
| A2.4 | 승격된 임계값으로 엔진 재실행, 결과 비교 (before/after) | A2.3 | `Temp/calibration_impact_report_v1.json` 존재 |
**핵심 산출물**: CALIBRATED ≥ 10/191 (5.2%+ 달성)
---
#### WBS-A3: 예측 정확도 목표 달성 (2026-09 ~ 2026-10)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| A3.1 | T+20 30건 기반 첫 match_rate 산출 | A1.4 | `match_rate_pct ≥ 50%` (1차 목표) |
| A3.2 | SS001 가중치(P/V/F) 1차 재보정 | A3.1 | `Temp/alpha_calibration_v1.json` — 보정 전후 개선 ≥ 2%p |
| A3.3 | 슬리피지 실측 5건 기록 (HTS 체결 후 수동 입력) | 없음 | `outputs/execution_slippage.db` sample ≥ 5 |
| A3.4 | 슬리피지 실측값 vs 5bps 이론값 비교 및 spec 갱신 | A3.3 | `gap_bps` 보고서 존재, 3bps 초과 시 spec 갱신 |
| A3.5 | 섹터 플로우 30일 달성 후 `FLOW_CREDIT_V1` 활성화 | 없음 | `days_accumulated ≥ 30`, lifecycle → ACTIVE |
**핵심 산출물**: `match_rate_pct ≥ 55%`, `honest_proof_score ≥ 70`
---
### Stream B: 🏗️ Platform Consolidation (플랫폼 통합)
> **철학: "복잡도를 줄여라. 1인이 유지할 수 없는 구조는 마스터피스가 아니다."**
#### WBS-B1: tools/ 대정리 (2026-08 Week 1~2)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| B1.1 | `tools/` 586개 파일 전수 인벤토리 — canonical/deprecated/dead 3등급 분류 | 없음 | `Temp/tools_inventory_v1.json` 생성 |
| B1.2 | Dead 스크립트 → `tools/archive/` 이동 (삭제하지 않고 보존) | B1.1 | `tools/archive/` 100건+ 이동 |
| B1.3 | Canonical 스크립트에 `#!/usr/bin/env python` + docstring 표준화 | B1.2 | canonical 스크립트 100% docstring 보유 |
| B1.4 | `tools/README.md` — canonical 도구 목록 + 사용법 작성 | B1.3 | README 존재, 검증 명령 포함 |
| B1.5 | GAS 중복 정리: `src/gas/` + `src/gas_adapter_parts/` + `src/google_apps_script/``src/gas/` 단일화 | 없음 | 3개 디렉토리 → 1개로 통합 |
| B1.6 | `src/client/` 레거시 삭제 | 없음 | 디렉토리 미존재 |
| B1.7 | `.gitea/workflows/deploy-prod.yml.backup` 삭제 | 없음 | 파일 미존재 |
**핵심 산출물**: `tools/` 파일 수 300개 이하, canonical 도구 목록 문서
---
#### WBS-B2: .NET 10 백엔드 완성 (2026-08 Week 3 ~ 2026-09)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| B2.1 | Application 서비스 완성 — Workspace/Approval/Collection/Formula 4개 서비스 실구현 | 없음 | `dotnet test --filter ApplicationService` 13+ PASS |
| B2.2 | 데이터 수집 오케스트레이터 — KIS-first → Naver fallback → JSON replay | B2.1 | `dotnet test --filter Collection` 4+ PASS |
| B2.3 | PostgreSQL 3NF 스키마 정규화 (V005~V008 마이그레이션) | 없음 | `dotnet-ef database update` 성공, `stocks`/`sources`/`market_data` 테이블 존재 |
| B2.4 | Repository 패턴 100% 적용 — Dapper + interface 기반 | B2.3 | 직접 SQL 호출 0건 (Service 레이어에서) |
| B2.5 | FastEndpoints API 완성 — 최소 15개 엔드포인트 (CRUD + 퀀트 결과 조회) | B2.1 | OpenAPI spec 자동 생성, endpoint 15개+ 존재 |
| B2.6 | Hangfire 스케줄러 — 일일 수집 + 주간 리밸런싱 + 월간 유니버스 갱신 | B2.2 | Hangfire 대시보드에서 3개 recurring job 확인 |
| B2.7 | 보안 강화 — BCrypt 패스워드 해싱, JWT 토큰 갱신, CSRF 방어 완전 탑재 | B2.5 | `dotnet test --filter Security` 10+ PASS |
**핵심 산출물**: `dotnet build` 경고 0, `dotnet test` 250+ PASS, API 엔드포인트 15+
---
#### WBS-B3: Vue 3 SPA 실동작 검증 (2026-09 ~ 2026-10)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| B3.1 | OpenAPI TypeScript 클라이언트 자동 생성 + Axios interceptor 완성 | B2.5 | `src/frontend/src/api/generated/` 자동 생성, `npm run type-check` 0 에러 |
| B3.2 | 로그인 플로우 — JWT + Refresh Token + 자동 갱신 | B2.7 | Playwright E2E: 로그인→토큰갱신→인증만료 시나리오 PASS |
| B3.3 | DashboardView — 실시간 포트폴리오 요약 (PostgreSQL 데이터 연동) | B3.1 | DashboardView에서 총자산/수익률/포지션 데이터 렌더링 확인 |
| B3.4 | SnapshotAdminView — account_snapshot 편집/검증/저장/승인 4단계 플로우 | B3.1 | Playwright E2E: 편집→저장→diff preview→승인 시나리오 PASS |
| B3.5 | DatabaseView — AG Grid 기반 전체 테이블 브라우저 | B3.1 | 10,000행 렌더링 성능 P95 < 200ms |
| B3.6 | SystemSettingsView — 전체 시스템 설정 관리 UI 실연동 | B3.1 | 설정 변경 → DB 반영 → 화면 갱신 round-trip |
| B3.7 | Vitest 단위 테스트 20+ 작성, Playwright E2E 10+ 시나리오 | B3.2 | `npm run test:unit` 20+ PASS, `npm run test:e2e` 10+ PASS |
**핵심 산출물**: Vue 3 SPA 완전 동작, E2E 테스트 10+, 타입 에러 0
---
#### WBS-B4: CI/CD 파이프라인 통합 (2026-10)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| B4.1 | CI 파이프라인 단일화 — Python/dotnet/frontend 3-stage gate 직렬 | B3.7 | `ci.yml` 실행 시간 ≤ 20분 |
| B4.2 | 배포 파이프라인 — frontend build → dotnet publish → tar.gz → 배포 → 헬스체크 | B4.1 | `deploy-prod.yml` 자동 실행, 6개 헬스체크 PASS |
| B4.3 | 배포 후 Playwright smoke 테스트 — 운영 서버 접속 + 로그인 + 대시보드 확인 | B4.2 | `tests/e2e/production-smoke.spec.ts` PASS |
| B4.4 | CI 재현성 검증 — 3회 연속 실행 결과 100% 동일 | B4.1 | `Temp/ci_reproducibility_report.json` variance < 5% |
**핵심 산출물**: 단일 `git push` → 15~20분 내 자동 배포 + 검증 완료
---
### Stream C: 🎨 Professional Operation (전문가 운영)
> **철학: "마스터피스는 보는 순간 신뢰감을 준다."**
#### WBS-C1: 관제 대시보드 (2026-10 ~ 2026-11)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| C1.1 | **Portfolio Overview** — 총자산, 일일/주간/월간 수익률, KOSPI 대비 알파, MDD | B3.3 | 첫 화면에서 5초 내 전체 상황 파악 가능 |
| C1.2 | **Position Heat Map** — 종목별 손익 히트맵 + Core/Satellite/Cash 버킷 시각화 | B3.3 | 11개 포지션 히트맵 렌더링, 색상으로 건강도 즉시 인지 |
| C1.3 | **Signal Dashboard** — SS001 점수, 라우팅 게이트 상태, 매수/매도 신호 실시간 표시 | B3.3 | HOLD/SELL_READY/BLOCKED 상태 색상 chips 표시 |
| C1.4 | **Calibration Health** — 191개 임계값 중 CALIBRATED/PROVISIONAL/미검증 비율 진행바 | B3.3 | 캘리브레이션 건강도 게이지 차트 |
| C1.5 | **Engine Activity Log** — 최근 엔진 실행 이력, 성공/실패/경고 타임라인 | B3.3 | 최근 30일 실행 이력 스크롤 가능 |
**핵심 산출물**: 한 화면에서 포트폴리오 건강도 + 신호 + 엔진 상태를 즉시 파악
---
#### WBS-C2: 자동 알림 & 모니터링 (2026-11)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| C2.1 | Telegram Bot 알림 — 일일 엔진 실행 결과, 매도 신호 발생, MDD 경고 | 없음 | Telegram 메시지 수신 확인 |
| C2.2 | 장애 자동 감지 — CI 실패, 서버 다운, 데이터 수집 중단 시 즉시 알림 | C2.1 | 의도적 장애 주입 → 5분 내 알림 수신 |
| C2.3 | Serilog + OpenTelemetry 구조화 로깅 — JSON 형식 로그 + 메트릭 수집 | B2.5 | `journalctl -u quantengine` JSON 구조 확인 |
| C2.4 | 주간 자동 리포트 — 포트폴리오 성과, 신호 변화, 캘리브레이션 진척 | C1.1 | 매주 일요일 Telegram 리포트 수신 |
**핵심 산출물**: 수동 확인 없이 이상 상황 자동 통보
---
#### WBS-C3: 1-Click 리밸런싱 워크플로 (2026-11 ~ 2026-12)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| C3.1 | 리밸런싱 제안 화면 — 버킷 밴드 위반 시 자동 제안, 주문표 생성 | C1.2 | 리밸런싱 필요 시 자동 제안 카드 표시 |
| C3.2 | 주문 시뮬레이션 — 지정가/호가단위 정규화 결과 미리보기 | C3.1 | 시뮬레이션 결과 테이블 (ticker/수량/지정가/슬리피지) |
| C3.3 | 승인 → HTS 주문표 export (CSV/클립보드) | C3.2 | "승인" 버튼 → CSV 다운로드/클립보드 복사 |
| C3.4 | 체결 후 실측 기록 UI — 의도가/실제체결가 입력 → 슬리피지 DB 저장 | C3.3 | `execution_slippage` 레코드 생성 확인 |
**핵심 산출물**: 리밸런싱 판단 → 주문 → 체결 기록의 완전한 루프
---
#### WBS-C4: 성과 리포팅 & 아카이빙 (2026-12)
| WBS | 작업 | 선행 | 성공 판단 데이터 |
|:---|:---|:---|:---|
| C4.1 | 월간 성과 보고서 자동 생성 — PDF/마크다운 (수익률, 알파, MDD, 매매 이력) | C1.1 | `Temp/monthly_report_2026_12.pdf` 존재 |
| C4.2 | 벤치마크 비교 차트 — KOSPI, S&P 500 대비 누적 수익률 | C4.1 | 차트에서 3개 라인 비교 가능 |
| C4.3 | 연간 결산 보고서 — 세금 계산, 배당 수입, 실현/미실현 손익 | C4.1 | 연간 보고서 항목 100% 채움 |
| C4.4 | 이력 아카이빙 — 일일 포트폴리오 스냅샷 PostgreSQL 시계열 저장 | B2.3 | `portfolio_daily_snapshots` 테이블 행 수 ≥ 30 |
**핵심 산출물**: 전문가급 성과 리포트 자동 생성
---
## 📊 Part 4: 완성도 매트릭스 & 마일스톤
### 4.1 마스터피스 완성도 KPI (2026-12-31 목표)
| 차원 | 지표 | 현재 | 마스터피스 목표 | 판정 |
|:---|:---|:---|:---|:---|
| **Alpha** | T+20 실측 건수 | 0 | ≥ 50 | 🔴 |
| **Alpha** | CALIBRATED 임계값 | 0/191 | ≥ 30/191 (15%+) | 🔴 |
| **Alpha** | 예측 정확도 (match_rate) | DATA_GATED | ≥ 55% | 🔴 |
| **Alpha** | 슬리피지 실측 | 0건 | ≥ 10건 | 🔴 |
| **Alpha** | KOSPI 대비 알파 | 미측정 | > 0%p/분기 | 🔴 |
| **Platform** | .NET 테스트 | 214 | ≥ 300 | 🟠 |
| **Platform** | Vue 3 E2E 테스트 | ~3 | ≥ 15 | 🟠 |
| **Platform** | tools/ 파일 수 | 586 | ≤ 200 (canonical) | 🟠 |
| **Platform** | CI 재현성 | 미검증 | 3회 연속 100% 동일 | 🟠 |
| **Platform** | 배포 소요시간 | 수동 | ≤ 20분 (자동) | 🟠 |
| **Operation** | 수동 개입 | 매일 | ≤ 1회/주 | 🟡 |
| **Operation** | 장애 알림 | 없음 | 5분 내 Telegram | 🔴 |
| **Operation** | 월간 리포트 | 없음 | 자동 생성 | 🔴 |
| **Operation** | 리밸런싱 워크플로 | CLI 전용 | 웹 UI 1-Click | 🔴 |
### 4.2 월별 마일스톤
| 월 | 마일스톤 | 핵심 증빙 |
|:---|:---|:---|
| **2026-08** | **M1: Alpha Pipeline Live** — T+20 수집 자동화 + tools/ 대정리 완료 | T+20 entry 10건+, tools/ 300개 이하 |
| **2026-09** | **M2: Backend Complete** — .NET Application 서비스 + PostgreSQL 3NF + API 15개 | `dotnet test` 250+, endpoint 15+ |
| **2026-10** | **M3: SPA Live** — Vue 3 전체 뷰 실동작 + CI/CD 통합 | E2E 10+, 자동 배포 동작 |
| **2026-11** | **M4: Professional Ops** — 관제 대시보드 + Telegram 알림 + 리밸런싱 UI | 대시보드 5개 패널, 알림 동작 |
| **2026-12** | **M5: Masterpiece** — 알파 실증 + 성과 리포트 + 연간 결산 | match_rate ≥ 55%, 월간 리포트 자동 |
---
## 🔥 Part 5: 즉시 실행 — Sprint-0 (이번 주, 2026-07-28 ~ 2026-08-01)
> **이번 주에 할 수 있는 가장 가치 있는 4가지**
### Sprint-0.1: T+20 수집 자동화 파이프라인 (Day 1~2)
```bash
# 1. Gitea Actions 일일 cron 등록
# .gitea/workflows/t20_ledger.yml
# 매 영업일 17:00 KST 자동 실행
python tools/build_operational_t20_outcome_ledger_v1.py --auto
```
- 이것이 **가장 시급**하다. 알파 검증의 전제조건이 데이터 누적이고, 하루라도 빨리 시작해야 한다.
### Sprint-0.2: tools/ 파일 인벤토리 자동 분류 (Day 2~3)
```bash
python tools/build_tools_inventory_v1.py
# 586개 → canonical / deprecated / dead 3등급 분류
# Temp/tools_inventory_v1.json 산출
```
### Sprint-0.3: 슬리피지 실측 첫 기록 (Day 3~4)
```bash
# 최근 체결 이력에서 1건이라도 기록
python tools/evaluate_execution_slippage_v1.py record \
--ticker 005930 --side BUY \
--intended-price 71000 --actual-price 71050 \
--recorded-at 2026-07-28
```
### Sprint-0.4: 레거시 파일 정리 (Day 4~5)
```bash
# 즉시 삭제 가능한 레거시
rm -rf src/client/
rm .gitea/workflows/deploy-prod.yml.backup
```
---
## 📐 Part 6: 의존성 차트 (전체)
```mermaid
graph TD
subgraph "Stream A: Alpha Validation"
A11["A1: T+20 파이프라인"]
A21["A2: 캘리브레이션 실증"]
A31["A3: 예측 정확도"]
A11 --> A31
A21 --> A31
end
subgraph "Stream B: Platform"
B11["B1: tools 정리"]
B21["B2: .NET 완성"]
B31["B3: Vue 3 SPA"]
B41["B4: CI/CD 통합"]
B21 --> B31
B31 --> B41
end
subgraph "Stream C: Operation"
C11["C1: 관제 대시보드"]
C21["C2: 자동 알림"]
C31["C3: 리밸런싱 UI"]
C41["C4: 성과 리포팅"]
B31 --> C11
C11 --> C21
C11 --> C31
C31 --> C41
end
A31 --> C41
```
---
> [!IMPORTANT]
> **마스터피스의 핵심은 기술이 아니라 실증이다.**
>
> 269개 공식, 92개 spec, 586개 도구 — 이 모든 것은 **T+20 30건이 쌓이고, 캘리브레이션 10건이 CALIBRATED되고, match_rate가 55%를 넘는 순간** 비로소 의미를 갖는다.
>
> 지금 이 순간부터 가장 중요한 것은 **데이터 누적**이다. 하루라도 빨리 T+20 파이프라인을 돌려야 한다.
+9
View File
@@ -1,3 +1,12 @@
> **정정 (2026-07-30)**: 이 문서는 잠시 `docs/archive/`로 옮겨졌다가 같은 날 다시 원래 위치로
> 복구되었다. `tools/validate_enterprise_crud_specification_v1.py:29`가 이 경로
> (`docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md`)를 직접 참조하고, 이 검증은
> `.gitea/workflows/ci-frontend.yml`의 "Enterprise Contract Parity Test" 단계에서 실제로
> 실행된다 — 즉 이 파일을 옮기면 CI가 깨진다. 내용상 권위는
> [`../spec/60_oms_wms_erp_wbs.yaml`](../spec/60_oms_wms_erp_wbs.yaml) 또는
> [`OMS_WMS_ERP_PLAYBOOK.md`](OMS_WMS_ERP_PLAYBOOK.md)에 있을 수 있지만, 파일 자체는
> 검증기가 요구하는 이 경로에 계속 있어야 한다.
# OMS·WMS·ERP 입력 컴포넌트 & 공통 CRUD 템플릿 & 상용화 제안 마스터 WBS (WBS-MASTER-2026) # OMS·WMS·ERP 입력 컴포넌트 & 공통 CRUD 템플릿 & 상용화 제안 마스터 WBS (WBS-MASTER-2026)
## 0. 개요 및 3대 명세 통합 권위 ## 0. 개요 및 3대 명세 통합 권위
+8
View File
@@ -1,3 +1,11 @@
> **정정 (2026-07-30)**: 이 문서는 잠시 `docs/archive/`로 옮겨졌다가 같은 날 다시 원래 위치로
> 복구되었다. 내용 자체는 2026-06-13 기준으로 오래됐지만(최신 마이그레이션 상태는
> [`../CLAUDE.md`](../CLAUDE.md) Migration Status 참고), `tools/validate_quant_engine_wbs_v1.py`,
> `tools/validate_platform_transition_wbs_v1.py`, `tests/unit/test_validate_quant_engine_wbs_v1.py`,
> `spec/60_quant_engine_wbs.yaml` 등 release gate 검증 스크립트/스펙이 이 경로(`docs/ROADMAP_WBS.md`)의
> 존재와 특정 내용을 실제로 검사하므로, "오래됐다"는 이유만으로 archive하면 검증 파이프라인이 깨진다.
> 문서 정리가 필요하면 이 파일을 지우거나 옮기지 말고, 먼저 위 검증 스크립트들을 갱신해야 한다.
# 퀀트투자 엔진 — 전체 로드맵 & WBS & 하네스 성공 기준 # 퀀트투자 엔진 — 전체 로드맵 & WBS & 하네스 성공 기준
> 작성일: 2026-06-13 | 엔진 버전: REBALANCE_ENGINE_V1 기준 > 작성일: 2026-06-13 | 엔진 버전: REBALANCE_ENGINE_V1 기준
+135
View File
@@ -0,0 +1,135 @@
# 2026-07-30 QuantEngine 전략 감사 세션 — 인수인계
19개 원칙(SOLID, 정공법, 홀루시네이션, 재현성, 데이터정합성, 과유불급, 정규화/역정규화,
프로세스 단순화, 패턴화, 표준화, 구조화, 바이브코딩, 현장감, 이력성, 안정성, 고도화,
컴포넌트화, 기술부채) 기준으로 저장소를 감사하고 발견된 문제를 수정한 세션의 기록이다.
8개 커밋이 `main`에 반영·푸시됐다 (HEAD: `823a9a6`). 무엇이 바뀌었는지는 `git log`
권위 있는 출처이니 여기서 반복하지 않는다 — 이 문서는 **커밋 로그만 봐서는 알 수 없는
맥락**(미해결 항목, 판단 근거, 재발 방지 트랩)만 담는다.
## 미해결 / 다음에 이어갈 것
- **전체 release DAG(`npm run ops:validate` / `full-gate`)를 끝까지 검증하지 못함.**
`GatherTradingData.xlsx`(gitignore 대상, 실거래 데이터 시드)가 이 개발 환경에는 없어서
`convert_xlsx` 노드에서 막힌다. 이 파일이 있는 실제 환경(사용자 로컬 또는 운영 서버)에서
한 번 돌려서 이번 세션의 변경사항이 데이터 수집 경로를 깨지 않았는지 최종 확인 필요.
- **`docs/db/quantengine.dbml``engine_history` vs `quantengine` 스키마 동명 테이블 4개**
— 실제 .NET 호출부를 grep으로 대조해 "둘 다 살아있는 서로 다른 모델"로 확정하고 DBML에
근거를 남겼지만, 코드 통합/리네임은 하지 않았다. "정리해달라"는 요청이 오면 DBML의
`V8: PostgreSQL History-First Operating Model` 섹션 노트부터 다시 읽을 것 — 죽은 코드로
섣불리 판단하지 말 것.
- **OpenDART는 배선만 맞춰뒀고 실제로 호출하는 워크플로우가 아직 없다.** 환경변수명은
`OPENDART_OPENAPI_KEY`로 코드·Gitea Secrets 양쪽 통일 완료. 나중에
`tools/ingest_fundamental_raw.py`를 CI에서 처음 호출할 때는 별도 매핑 없이
`secrets.OPENDART_OPENAPI_KEY`를 그 job의 `env:`에 바로 연결하면 된다.
- **KRX Open API는 구현이 전혀 없다** — CLAUDE.md에 환경변수명(`KRX_OPENAPI_KEY`, 실제
Gitea Secrets 이름과 일치)만 예약해뒀다. 호출 한도 등은 사용자가 알려주지 않아 기록하지
않았다 — 추측해서 채우지 말 것.
## 파일 수 최종 현황 (같은 날, 3차 라운드)
`tests/unit/test_kis_data_collection_v1.py`가 F8과 같은 원인(deprecated/ 이동)으로 import가
깨져 있던 걸 발견해 고쳤다 (오늘 삭제와 무관, 이전부터 있던 버그 — `pytest --collect-only`
실제 실행해서 발견). 그리고 `tests/golden/generated/` 174개 — 스펙(QE-M0-06)이 스스로
"M3 패리티 대체 후 삭제" 조건을 걸어뒀고, M3-01~05가 전부 DONE인 걸 확인한 뒤 삭제. CI/커버리지
게이트 어디서도 이 파일들을 쓰지 않는다는 것까지 확인 완료. **최종 파일 수: 4,523 → 1,687**
(예산 2,200 대비 77%, 여유 513개). 이 지표는 이제 확실히 건강한 상태 — 추가로 파일 수를
줄이려는 시도는 과유불급이다(이미 통과한 지표를 더 깎으려다 실수로 쓰이는 파일을 지울 위험이
더 크다). `tools/`에는 아직 그레이존 파일이 좀 더 있을 수 있지만(74개 삭제 후 남은 것들은
전부 검토 완료), 더 뒤지는 것보다 실제 필요가 생겼을 때 개별적으로 판단하는 게 낫다.
## orphan 스크립트 정리 (같은 날, 2차 조사)
`tools/*.py` + `src/quant_engine/*.py` 619개 파일 전수 스캔(파일명이 저장소 어디에도 안 나오는
것 탐지) 결과 81개 orphan 후보 발견. 두 단계로 나눠 총 74개 삭제:
- 1차 34개: 명백한 버전 중복(`_v2`/`_correct`/`_properly` 짝) + tools/에 섞인 임시 테스트/디버그
스크립트.
- 2차 40개: WBS 티켓 전용 1회성 스크립트 + 기타 build_*/validate_* 진단 도구. **주의**: 스크립트
자체 이름 검색만으로는 부족했다 — 47개 후보 중 7개는 이름은 안 불려도 만들어내는
`Temp/*.json` 산출물이 다른 도구에서 계속 읽히고 있어 실제로는 살아있었다
(`build_outcome_ledger_v1.py`, `build_pre_distribution_early_warning_v3.py`,
`build_shadow_ledger_v1.py`, `build_p2_01_live_outcome_ledger.py`,
`build_p2_02_calibration_promotion.py`, `build_p1_01_execution_verdict_unify.py`,
`run_release_ci_gate_v2.py` — 이 7개는 삭제하지 않고 남겨둠). **다음에 orphan 스캔할 때는
스크립트명뿐 아니라 그 스크립트가 쓰는 `Temp/*.json` 출력 경로까지 같이 검색할 것.**
나머지 orphan 후보(그레이존 밖, 원래 81개에 없던 것들)는 손대지 않았다 — 전수조사가 아니라
`tools/`+`src/quant_engine/`만 스캔한 결과다.
## GatherTradingData.xlsx 관련 (같은 날, 추가 조사)
로컬에는 `.xlsx`가 없지만, 운영 서버(`~/QuantEngineByItz/GatherTradingData.json`)에는 이미
xlsx→json 변환이 끝난 정본 시드 파일이 있다 (저장소 자체 설계 문서
`docs/GATHERTRADINGDATA_XLSX_DECISION_2026-06-21.md`가 "json을 정본으로, xlsx는 미추적"으로
결정한 바로 그 파일). SCP로 로컬에 받아왔다(`./GatherTradingData.json`, gitignore 대상이라
커밋 안 됨). 그런데 `tools/run_release_dag_v3.py``convert_xlsx` 노드는 xlsx 파일이 실제로
없으면 무조건 하드 실패하도록 짜여 있어(캐시/스킵 로직 없음, 코드 주석에 "optional 최적화,
아직 미구현"이라고 명시됨), json이 이미 있어도 release DAG를 처음부터 끝까지 돌릴 수는 없다.
남은 WBS 태스크 10개(QE-M3-03, M4-01~05, M5-01~04)를 이 json만으로 복구하려 했으나:
- **M3-03**: `engine_history.factor_output_history`에 최근 24시간 데이터가 있어야 하는 라이브
신선도 게이트 — 데이터 유무와 무관, 운영 파이프라인이 최근 실제로 돌았는지에 달림.
- **M4-01~04, M5-01~03**: `Temp/backtest_result_v1.json` 등은 Python 스크립트가 아니라
**`src/dotnet/QuantEngine.Tools`/`QuantEngine.Web`를 실제로 띄우고 Playwright로 백테스트/
캘리브레이션 화면을 조작해야** 생성된다(M4-05 검증 커맨드가 `npx playwright test`
`verify_wbs_task_v1.py` 순서인 게 근거). 로컬 웹서버 기동 + Playwright 브라우저 설치 +
실제 가격/팩터 이력 DB 데이터 충분 여부까지 얽혀 있어 이번 세션에서는 시도하지 않았다.
- **M4-05, M5-04**: 위와 같은 이유로 막힘.
다음 세션에서 이어가려면: SSH 터널 + `dotnet watch run --project QuantEngine.Web` +
`npx playwright test --project=evidence tests/e2e/evidence/qe-m4-05-backtest.spec.ts` 순으로
시도. DB에 실제 가격 이력이 충분한지부터 확인할 것 (부족하면 백테스트 자체가 의미있는 결과를
못 낼 수 있음).
## 추가 발견 (같은 날, entropy 정리 이후)
- **`Temp/*` 전체 삭제가 WBS 검증 캐시를 깼다.** `tools/verify_wbs_task_v1.py`가 만드는
`Temp/evidence/<task_id>/verdict.json`과 각종 `Temp/*.json`(golden_coverage_100,
market_time_series_schema 등)은 git에 추적되지 않지만 "완료된 검증의 증적"이라 순수
빌드 캐시가 아니었다. `spec/60_quant_engine_wbs.yaml`의 13개 태스크가 FAIL로 나타났었음.
- 3개(QE-M0-06, QE-M2-06, QE-M2-01)는 해당 generator 재실행 + DB 재접속으로 복구 완료.
- QE-M3-03은 무관 — `engine_history.factor_output_history`에 최근 24시간 내 데이터가
있어야 하는 라이브 신선도 게이트. 오늘 세션과 상관없이 운영 파이프라인이 최근 안
돌았으면 원래도 FAIL이다.
- 나머지 7개(QE-M4-01~04, QE-M5-01~03)는 `Temp/prediction_accuracy_harness_v2.json`
등 실거래 데이터 파생 체인이 필요 — 이 저장소 스냅샷엔 `GatherTradingData.xlsx`
없어서(이미 위에서 언급한 그 문제) 복구 불가. 실거래 데이터가 있는 환경에서 전체
파이프라인을 한 번 돌리면 자동 복구된다.
- QE-M4-05/QE-M5-04(Playwright evidence)도 같은 체인에 의존해 사실상 같이 막혀있음.
- **교훈**: `Temp/`가 git 미추적이라고 전부 "순수 빌드 산출물"은 아니다 — `Temp/evidence/`처럼
"재실행하면 되지만 재실행에 실제 데이터/DB가 필요한 캐시"가 섞여 있다. 다음에 비슷한
정리를 할 때는 삭제 전에 `rg -l "Temp/" spec/ tools/` 정도로 어떤 하위 경로가 검증
체인에 물려있는지 먼저 확인할 것.
## 이번 세션에서 걸린 함정 — 재발 방지
- **문서를 "오래됐다"고 archive하기 전에 `tools/*.py`, `spec/*.yaml`, `tests/*.py`,
`.gitea/workflows/*.yml`까지 전부 grep할 것** — 다른 문서/CLAUDE.md만 검색해서는 부족하다.
`docs/ROADMAP_WBS.md``docs/ROADMAP_ENTERPRISE_TEMPLATES_WBS.md`를 이 방식으로 archive
했다가, 실제로는 release gate 검증기와 `ci-frontend.yml`의 Enterprise Contract Parity
Test가 그 경로를 직접 참조하고 있어서 되돌려야 했다. 지금은 이 두 파일 다시 원위치, 검증기
3개 직접 실행해서 통과 확인 완료.
- **DbUp 마이그레이션은 파일명을 순수 문자열로 정렬한다**`V10__``V2__`보다 먼저
정렬되는 문제가 있었다. `MigrationScriptNameComparer`(이번 세션에 추가, `DbMigrator.cs`
연결)로 해결됨 — 새 마이그레이션은 zero-padding 없이 다음 정수만 쓰면 된다.
- **`runtime/`은 대부분 git 추적되는 이력 데이터다** (`refactor_baseline_v*.yaml`,
`rollback_manifest_v*.yaml` 등) — 스크래치 공간이 아니다. 확인용 명령의 `--out`
실수로 이 경로로 잡아서 이력 파일 2개를 덮어썼다가 `git diff`로 발견하고
`git checkout --`으로 복구했다. 1회성 도구 출력은 `/tmp/` 등으로 보낼 것.
- **이 머신에 Python이 두 개 설치돼 있다**`python`(3.11, 대부분의 서브프로세스가
실제로 쓰는 것)과 `python3`(3.14). 한쪽에 패키지를 설치해도 다른 쪽엔 없다.
- **repository entropy 감사(`audit_repository_entropy_v2.py`)가 git 추적 파일이 아니라
로컬 디스크 전체를 세고 있었다** — `.gitignore`와 제외 목록이 어긋나 있어 로컬 빌드 한 번에
4,523개까지 부풀었다(예산 2,200). `.gitignore`와 일치하도록 제외 목록을 갱신해 재발을
막았다 (`tools/audit_repository_entropy_v1.py`). 이 게이트가 다시 실패하면 먼저 "새로운
미추적 빌드 산출물 디렉터리가 생겼나"부터 확인할 것 — 바로 대규모 파일 삭제로 가지 말 것.
## 이번 세션에서 확립된 작업 방식
- 작업 라운드가 끝나면 다음에 할 만한 구체적인 후보를 먼저 제안한다 (사용자가 같은 지시를
반복해서 보내는 걸 방지).
- 단순 기계적 조사/위임은 `model: "haiku"`로, 판단이 필요한 작업만 Sonnet급으로.
- 커밋/푸시는 명시적으로 요청받았을 때만, 항상 경로를 지정해서 스테이징(`git add -A` 금지),
세션 시작 전부터 있던 무관한 변경사항은 요청 없이는 포함하지 않는다.
- 채팅에 붙여넣어진 실제 API 키(KIS, OpenDART, KRX)는 어떤 파일에도 적지 않는다 — 환경변수
*이름*만 기존 KIS 관례(환경변수/Gitea Secrets 전용, 하드코딩 금지)에 맞춰 기록한다.
+54
View File
@@ -0,0 +1,54 @@
# QuantEngine UI Design Guidelines
Full UI design principles, extracted from CLAUDE.md (2026-07-30) to keep the main file within
the character budget. CLAUDE.md keeps a condensed summary; this file has the complete rules
and the component mapping table.
## Framework & Design System (2026-07-11)
- **Primary Framework**: ASP.NET Core Razor Pages + Bootstrap 5 + Tabler UI
- **Design System**: Tabler (Bootstrap 5 기반), 밀집 레이아웃 + 전통 서버 렌더링
- **Render Mode**: **Server-side Razor Pages** — 모든 Admin UI는 서버에서 렌더링, Cookie 기반 인증 (API-First WASM 폐기)
- **Authentication**: Cookie Authentication (HttpOnly) + BCrypt password hashing + IP lockout (3 strikes, 15-min)
- **Deprecation**: **Blazor Interactive WebAssembly 폐기**, **MudBlazor 컴포넌트 폐기** (2026-07-11), **SmartAdmin 폐기**. `QuantEngine.Web.Client` 폴더는 저장소에 실재하지 않는다 — `.sln`에서 제외된 것이 아니라 완전히 삭제됨 (2026-07-30 확인)
## Component Development Rules
1. **All Admin UI Development** (New + Refactored):
- Use **Razor Pages** (.cshtml + .cshtml.cs PageModel) exclusively for admin
- UI는 Repository/Service를 생성자 DI로 직접 호출 (API 홉 없음)
- Bootstrap 5 + Tabler UI CSS classes for styling
- **Form Validation**: DataAnnotations DTO + FluentValidation IValidator<T> 이중 검증
- HTML `<form>` + tag helpers (`asp-for`, `asp-action`, `asp-page`)
2. **Authentication & Authorization**:
- Cookie name: `QuantEngine.Admin.Auth` (HttpOnly, SameSite=Lax)
- Session duration: 12 hours (sliding expiration)
- Folder-level `[Authorize]` via `AuthorizeFolder("/Admin")` convention (per-page 반복 금지)
- Login: `/Account/Login` (Razor Page, NO WASM)
- Password: BCrypt-hashed (auto-migrates existing SHA-256 hashes on first login)
- IP Lockout: 3 failed attempts → 15-minute lockout
3. **Data & Form Patterns**:
- PageModel constructor: `public IndexModel(IWorkspaceRepository repo, ILogger<IndexModel> logger)`
- Form submission: `OnPostAsync()` / `OnPostDeleteAsync()` (multi-handler pattern)
- Validation failures: return `Page()` (re-render with ModelState errors)
- Pagination: `PaginationModel` record (Page, TotalPages, Func<int,string> BuildPageUrl)
- Empty states: `<PartialView name="_EmptyState" model="message" />`
4. **Component Mapping** (Bootstrap 5 + Tabler):
| UI Element | Component | Notes |
|-----------|-----------|-------|
| Button | `<button class="btn btn-primary">` | — |
| Input field | `<input asp-for="Property" class="form-control">` | tag helper |
| Dropdown | HTML `<select asp-for="Property">` | tag helper |
| Data grid | HTML `<table class="table">` | plain, no virtualization |
| Card | `<div class="card">` | Bootstrap card |
| Badge/Status | `<span class="badge bg-success">Active</span>` | Bootstrap badge |
| Layout container | `<div class="container-xl">` / `<div class="row">` | Bootstrap grid |
| Navigation | HTML navbar in `_AdminLayout.cshtml` | sidebar + topbar |
| Loading | N/A (server-rendered) | no loading states needed |
| Icons | Bootstrap Icons (`<i class="bi bi-*"></i>`) | CDN |
| Modal/Dialog | Bootstrap modal or inline `confirm()` | avoid unnecessary modals |
| Validation msg | `<span asp-validation-for="Property" class="d-block alert alert-danger mt-2">` | tag helper |
+40
View File
@@ -0,0 +1,40 @@
version: "1.0.0"
objective: "oms-wms-erp의 계약 중심 리팩토링을 안전한 증분 단위로 수행"
scope:
canonical_code_root: "oms-wms-erp"
excluded_roots:
- "src/frontend"
- "Temp"
- "archive"
work_items:
- id: "WBS-20260728-01"
title: "baseline 및 계약 경계 확인"
status: "in_progress"
success_data:
- "npm run type-check exit code 0"
- "npm run build exit code 0"
- "npm run test exit code 0"
- "python tools/validate_enterprise_crud_specification_v1.py exit code 0"
- id: "WBS-20260728-02"
title: "공통 계약·타입·오류 처리의 단일 진실원 확립"
status: "pending"
success_data:
- "중복 API 오류·감사·그리드 계약 0건"
- "기존 소비자 타입체크 통과"
- id: "WBS-20260728-03"
title: "삭제·동시성·금액 정합성 보호"
status: "pending"
success_data:
- "물리 삭제 경로 신규 추가 0건"
- "낙관적 잠금 실패가 명시적 오류 계약으로 매핑"
- "금액 계산의 부동소수점 암묵 변환 0건"
- id: "WBS-20260728-04"
title: "사후 검증·재현성·증빙 기록"
status: "pending"
success_data:
- "검증 명령과 결과가 Temp/ 증빙 파일에 존재"
- "변경 파일이 WBS 항목에 매핑됨"
constraints:
- "가격·수량·공식은 quant-engine spec을 재계산하지 않음"
- "Temp/ 산출물은 직접 편집하지 않음"
- "기존 사용자 변경을 덮어쓰지 않음"
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 2026-07-11 시점 build.yml/wbs_9_3_*.yml/merge-to-main.yml 등
> 이후 삭제된 워크플로우를 전제로 쓰였습니다. 현재 CI 구조는
> [`../CICD_PIPELINE.md`](../CICD_PIPELINE.md)를 참고하세요.
# QuantEngine CI/CD 파이프라인 — 근본적 개선 분석 및 로드맵 # QuantEngine CI/CD 파이프라인 — 근본적 개선 분석 및 로드맵
**작성일**: 2026-07-11 **작성일**: 2026-07-11
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 2026-07-11 시점 파이프라인 구조 기준입니다. 현재 모니터링
> 방법은 [`../DEPLOYMENT_RUNBOOK.md`](../DEPLOYMENT_RUNBOOK.md)의 "Deployment Monitoring" /
> "API Monitoring (CLI)" 절을 참고하세요.
# CI/CD Pipeline 모니터링 가이드 # CI/CD Pipeline 모니터링 가이드
**작성일**: 2026-07-11 **작성일**: 2026-07-11
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 본 문서의 CI/CD 로드맵은 2026-07-11 이후 구현 완료되었습니다.
> 현재 CI/CD 가이드는 [`docs/CICD_PIPELINE.md`](docs/CICD_PIPELINE.md) 및
> [`docs/DEPLOYMENT_RUNBOOK.md`](docs/DEPLOYMENT_RUNBOOK.md)을 참고하세요.
# QuantEngine Gitea Actions CI/CD 개선 로드맵 # QuantEngine Gitea Actions CI/CD 개선 로드맵
**최종 목표**: 신뢰성 높은 자동화된 배포 파이프라인 구축 **최종 목표**: 신뢰성 높은 자동화된 배포 파이프라인 구축
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: "로컬 Green-Blue 배포(SSH 제거)" 방식은 이후
> SSH 기반 release-artifact 배포(prepare-release.yml → deploy-prod.yml)로 대체되었습니다.
> 현재 배포 방식은 [`../DEPLOYMENT_RUNBOOK.md`](../DEPLOYMENT_RUNBOOK.md)를 참고하세요.
# QuantEngine CI/CD 파이프라인 구현 완료 보고서 # QuantEngine CI/CD 파이프라인 구현 완료 보고서
**작성일**: 2026-07-11 **작성일**: 2026-07-11
@@ -1,3 +1,8 @@
> **ARCHIVED (2026-07-30)**: 이미 삭제된 `merge-to-main.yml`, 옛 `deploy_gb.sh` Green-Blue
> 스크립트를 전제로 쓰였습니다. 현재 트러블슈팅 가이드는
> [`../DEPLOYMENT_RUNBOOK.md`](../DEPLOYMENT_RUNBOOK.md)의 "Troubleshooting Deployment
> Failures" 절을 참고하세요.
# CI/CD 배포 트러블슈팅 가이드 # CI/CD 배포 트러블슈팅 가이드
**작성일**: 2026-07-11 **작성일**: 2026-07-11
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 본 문서는 Phase 0-1 실행 계획(2026-07-24)으로, 현재 상태와 일부 차이가 있습니다.
> 최신 정보는 [`../CLAUDE.md`](../CLAUDE.md) Migration Status 섹션 또는
> [`STRATEGIC_EXECUTION_MASTER_PLAN.md`](../STRATEGIC_EXECUTION_MASTER_PLAN.md)를 참고하세요.
# QuantEngine 현대화 실행 계획 # QuantEngine 현대화 실행 계획
**Phase 0 마무리 + Phase 1 준비** (2026-07-24 ~ 2026-09-30) **Phase 0 마무리 + Phase 1 준비** (2026-07-24 ~ 2026-09-30)
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 본 문서의 Gantt 차트는 2026-07-24 기준 Phase 0-4 일정입니다.
> 최신 마이그레이션 상태는 [`../CLAUDE.md`](../CLAUDE.md)의 Migration Status 섹션 또는
> [`STRATEGIC_EXECUTION_MASTER_PLAN.md`](../STRATEGIC_EXECUTION_MASTER_PLAN.md)를 참고하세요.
# QuantEngine 현대화 로드맵 (시각화) # QuantEngine 현대화 로드맵 (시각화)
## 1. 전체 진행도 (Gantt Chart) ## 1. 전체 진행도 (Gantt Chart)
@@ -1,3 +1,7 @@
> **ARCHIVED (2026-07-30)**: 본 문서의 Phase 0-3 전략은 2026-07-24 기준이며, 최신 버전으로 대체되었습니다.
> 현재 마이그레이션 상태는 [`../CLAUDE.md`](../CLAUDE.md) Migration Status 또는
> [`STRATEGIC_EXECUTION_MASTER_PLAN.md`](../STRATEGIC_EXECUTION_MASTER_PLAN.md)를 참고하세요.
# QuantEngine 데이터 기반 고도화 로드맵 # QuantEngine 데이터 기반 고도화 로드맵
**2026-07-24 ~ 2027-06-30** **2026-07-24 ~ 2027-06-30**
@@ -1,3 +1,8 @@
> **ARCHIVED (2026-07-30)**: 테스트 섹션은 bUnit + MudBlazor 컴포넌트(`Dashboard.razor`,
> `mud-card-kpi` 등) 기준으로, MudBlazor/Blazor WASM이 Razor Pages로 대체된 2026-07-11
> Phase 1 이후 더 이상 유효하지 않습니다. 배포 섹션은
> [`../DEPLOYMENT_RUNBOOK.md`](../DEPLOYMENT_RUNBOOK.md)로 대체되었습니다.
# QuantEngine - Testing & Deployment Guide # QuantEngine - Testing & Deployment Guide
**Status**: Phase 6 (Testing) & Phase 8 (Deployment) - Configuration & Documentation **Status**: Phase 6 (Testing) & Phase 8 (Deployment) - Configuration & Documentation
+262 -2
View File
@@ -1,8 +1,17 @@
// ============================================================================= // =============================================================================
// QuantEngine Database Schema (DBML) // QuantEngine Database Schema (DBML)
// DbUp 마이그레이션(V1~V5)과 1:1 동기화 — 마이그레이션 추가 시 이 파일도 반드시 갱신 // DbUp 마이그레이션(V1~V10)과 1:1 동기화 — 마이그레이션 추가 시 이 파일도 반드시 갱신
// (CLAUDE.md 규칙: schema 변경 → DBML + 문서 동기화) // (CLAUDE.md 규칙: schema 변경 → DBML + 문서 동기화)
// //
// 2026-07-30 해결됨: 예전에 V003_name.sql/V004_name.sql(싱글언더스코어, zero-pad)이
// V1__Name.sql(더블언더스코어, zero-pad 없음) 방식과 섞여 있어, DbUp의 기본 알파벳순
// 정렬에서 "V003" < "V1"로 먼저 실행되는 문제가 있었다 (V004는 V2가 만드는 테이블에 대한
// 하드 FK 제약이 있어 빈 DB에 처음부터 배포하면 V004에서 하드 실패 → V1~V8 전체가 실행
// 안 되는 재현성 버그였음). 조치: V003→V9, V004→V10으로 리네임 + DbMigrator.cs에
// MigrationScriptNameComparer(숫자 기반 비교자)를 추가해 "V{n}"이 몇 자리 숫자든 항상
// 숫자 크기순으로 정렬되도록 함. 신규 마이그레이션은 V{n}__Name.sql 규칙만 사용할 것
// (이 비교자 덕분에 V11, V12... 로 계속 늘어나도 더 이상 이 문제가 재발하지 않는다).
//
// 참고: Hangfire 스키마는 Hangfire.PostgreSql 라이브러리가 자동 생성 // 참고: Hangfire 스키마는 Hangfire.PostgreSql 라이브러리가 자동 생성
// (DbUp 마이그레이션으로 관리하지 않음, 여기서도 제외) // (DbUp 마이그레이션으로 관리하지 않음, 여기서도 제외)
// ============================================================================= // =============================================================================
@@ -382,7 +391,7 @@ Table engine_history.market_vs_engine_gap_history {
} }
// ============================================================================= // =============================================================================
// Schema: engine_history (V5 normalized learning history) // V6: Market Time Series (quantengine schema)
// ============================================================================= // =============================================================================
Table quantengine.price_history_daily { Table quantengine.price_history_daily {
@@ -415,6 +424,10 @@ Table quantengine.macro_history_daily {
} }
} }
// =============================================================================
// V5: Normalized Learning History (engine_history schema, event-sourcing style)
// =============================================================================
Table engine_history.source_observation { Table engine_history.source_observation {
observation_id UUID [pk] observation_id UUID [pk]
observed_at TIMESTAMPTZ [not null] observed_at TIMESTAMPTZ [not null]
@@ -493,6 +506,253 @@ Table engine_history.outcome_evaluation {
} }
} }
// =============================================================================
// V9: Audit Trail Tables (quantengine schema, 파일: V9__Add_Audit_Trail_Tables.sql,
// 원래 이름 V003_add_audit_trail_tables.sql, 2026-07-30에 V9로 리네임 — 위 헤더 참고)
//
// 2026-07-30 확정 (실제 프로덕션 DB 조회로 검증): 리네임 전 이 마이그레이션은 CREATE TABLE
// 안에 MySQL 전용 인라인 "INDEX name (cols)" 구문을 사용해 PostgreSQL에서 문법 오류로
// 실패했고, quantengine.schemaversions(DbUp 저널)에도 전혀 기록되어 있지 않았다 — 아래 3개
// 테이블은 프로덕션에 실제로 존재하지 않음을 확인했다. 인라인 INDEX 구문은 별도 CREATE INDEX
// 문으로 수정했고, V003→V9 리네임으로 실행 순서 문제도 해결했으므로 다음 배포 시 DbUp가 이
// 마이그레이션을 최초로 실행해 아래 3개 테이블을 생성할 것이다.
// =============================================================================
Table quantengine.kis_collection_runs_audit {
id BIGSERIAL [pk]
run_id "UUID" [not null]
action "VARCHAR(10)" [not null, note: "INSERT/UPDATE/DELETE"]
changed_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
changed_by "VARCHAR(256)" [default: "CURRENT_USER"]
change_reason TEXT
old_values JSONB
new_values JSONB
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "kis_collection_runs 변경 이력 (트리거 자동 기록) — ⚠️ 마이그레이션 문법 오류로 실제 생성 여부 미확인"
}
Table quantengine.kis_collection_snapshots_audit {
id BIGSERIAL [pk]
snapshot_id "UUID" [not null]
action "VARCHAR(10)" [not null, note: "INSERT/UPDATE/DELETE"]
changed_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
changed_by "VARCHAR(256)" [default: "CURRENT_USER"]
change_reason TEXT
old_values JSONB
new_values JSONB
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "kis_collection_snapshots 변경 이력 — ⚠️ 마이그레이션 문법 오류로 실제 생성 여부 미확인"
}
Table quantengine.kis_collection_errors_audit {
id BIGSERIAL [pk]
error_id "UUID" [not null]
action "VARCHAR(10)" [not null, note: "INSERT/UPDATE/DELETE"]
changed_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
changed_by "VARCHAR(256)" [default: "CURRENT_USER"]
change_reason TEXT
old_values JSONB
new_values JSONB
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "kis_collection_errors 변경 이력 — ⚠️ 마이그레이션 문법 오류로 실제 생성 여부 미확인"
}
// =============================================================================
// V10: 3NF Normalization / Star Schema (quantengine schema, 파일:
// V10__Normalize_Snapshots_Schema.sql, 원래 이름 V004_normalize_snapshots_schema.sql,
// 2026-07-30에 V10로 리네임 — 위 헤더 참고. Adapter 패턴으로 기존
// kis_collection_snapshots와 병행 운영 — 마이그레이션 자체 주석에 명시됨)
// =============================================================================
Table quantengine.stocks {
id SERIAL [pk]
ticker "VARCHAR(10)" [unique, not null]
name "VARCHAR(255)"
sector "VARCHAR(50)"
market "VARCHAR(20)" [note: "KOSPI/KOSDAQ 등"]
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
updated_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "종목 차원 테이블 (Star Schema dimension)"
}
Table quantengine.sources {
id SERIAL [pk]
name "VARCHAR(50)" [unique, not null]
priority INT [not null, note: "1=주 소스, 2 이상=폴백"]
fallback_to_id INT [ref: > quantengine.sources.id]
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "데이터 소스 차원 테이블 (KIS→Naver→Yahoo→OpenDART 폴백 체인)"
}
Table quantengine.market_data {
id BIGSERIAL [pk]
stock_id INT [not null, ref: > quantengine.stocks.id]
source_id INT [not null, ref: > quantengine.sources.id]
price DECIMAL [not null]
bid DECIMAL
ask DECIMAL
volume BIGINT
collected_at TIMESTAMPTZ [not null]
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
collection_run_id "UUID" [note: "kis_collection_runs 추적용"]
Note: "정규화된 시장 데이터 팩트 테이블 (Star Schema fact)"
}
Table quantengine.kis_collection_snapshots_v2 {
id "UUID" [pk]
run_id "UUID" [not null, ref: > quantengine.kis_collection_runs.run_id]
stock_id INT [not null, ref: > quantengine.stocks.id]
market_data_id BIGINT [ref: > quantengine.market_data.id, note: "조회 성능을 위한 의도적 역정규화"]
created_at TIMESTAMPTZ [not null, default: "CURRENT_TIMESTAMP"]
Note: "정규화된 kis_collection_snapshots — 레거시 kis_collection_snapshots와 Adapter 패턴으로 병행 운영, 완전 전환 여부 미확인"
}
// =============================================================================
// V8: PostgreSQL History-First Operating Model (quantengine schema)
//
// ⚠️ 동명이의 테이블 (통합 대상 아님, 2026-07-30 코드 조사로 확정): 아래 4개 테이블
// (market_raw_history, factor_version_history, factor_output_history,
// decision_result_history)은 engine_history 스키마(V3, 위 참고)에도 같은 이름으로 존재하지만,
// 마이그레이션 버그도 아니고 죽은 코드도 아니다 — 둘 다 실제로 읽고 쓰는 라이브 코드가 있는
// 서로 다른 두 모델이다:
// - engine_history.*: PostgresqlHistoryStore.AppendAsync() + HistoryIngestionService가
// 쓰는 범용 append-only 이력 저장소 (EAV형 원본 관측 이력)
// - quantengine.*(이 섹션): PostgresqlHistoryStore의 RecordWaterfallExecutionAsync 등
// + Admin 엔드포인트(BulkInsertMarketExcelEndpoint, UpdateFactorThresholdEndpoint,
// ExportStreamingFactorOlapEndpoint)가 쓰는 신형 구조화 운영 모델 (OHLCV 와이드 테이블 /
// 팩터ID-스코어 구조)
// 결론: 둘 다 유지해야 한다. 다만 같은 개념에 같은 테이블명을 두 스키마에서 쓰는 것 자체가
// 향후 개발자가 착각하기 쉬우므로(예: quantengine.market_raw_history에 쓸 걸 실수로
// engine_history.market_raw_history에 씀), 신규 코드 작성 시 스키마를 명시적으로 지정하고
// 반드시 어느 모델을 쓰는지 주석으로 남길 것.
// =============================================================================
Table quantengine.market_raw_history {
id BIGSERIAL [pk]
ticker "VARCHAR(32)" [not null]
as_of_date "VARCHAR(10)" [not null]
open_price "NUMERIC(18,4)"
high_price "NUMERIC(18,4)"
low_price "NUMERIC(18,4)"
close_price "NUMERIC(18,4)" [not null]
volume BIGINT
nav_price "NUMERIC(18,4)"
disparate_ratio "NUMERIC(10,6)"
tracking_error "NUMERIC(10,6)"
aum_krw "NUMERIC(20,2)"
raw_payload JSONB [not null]
provenance JSONB [not null]
created_at TIMESTAMPTZ [default: "NOW()"]
indexes {
(ticker, as_of_date) [unique, name: "uk_market_raw_ticker_date"]
}
Note: "OHLCV 와이드 테이블 — engine_history.market_raw_history(EAV형)와는 별개 설계"
}
Table quantengine.factor_version_history {
factor_id "VARCHAR(64)" [pk]
formula_name "VARCHAR(128)" [not null]
version "VARCHAR(32)" [not null]
category "VARCHAR(64)" [not null]
calibration_state "VARCHAR(32)" [not null, default: "'UNTESTED'"]
threshold_params JSONB [not null]
description TEXT
updated_at TIMESTAMPTZ [default: "NOW()"]
Note: "팩터 정의 — engine_history.factor_version_history와는 별개 설계 (PK가 factor_id 단독, 버전 이력 미보존)"
}
Table quantengine.factor_output_history {
id BIGSERIAL [pk]
run_id "VARCHAR(64)" [not null]
ticker "VARCHAR(32)" [not null]
as_of_date "VARCHAR(10)" [not null]
factor_id "VARCHAR(64)" [not null, ref: > quantengine.factor_version_history.factor_id]
score "NUMERIC(10,4)"
calculation_state "VARCHAR(32)" [not null]
provenance JSONB [not null]
created_at TIMESTAMPTZ [default: "NOW()"]
Note: "팩터 계산 결과 — engine_history.factor_output_history와는 별개 설계"
}
Table quantengine.decision_result_history {
id BIGSERIAL [pk]
run_id "VARCHAR(64)" [unique, not null]
as_of_date "VARCHAR(10)" [not null]
market_regime "VARCHAR(32)" [not null]
portfolio_health "VARCHAR(32)" [not null]
rebalance_required BOOLEAN [not null, default: "false"]
mid_check_required BOOLEAN [not null, default: "false"]
total_asset_krw "NUMERIC(20,2)" [not null]
d2_cash_krw "NUMERIC(20,2)" [not null]
decision_packet_json JSONB [not null]
created_at TIMESTAMPTZ [default: "NOW()"]
Note: "의사결정 패킷 이력 — engine_history.decision_result_history와는 별개 설계"
}
Table quantengine.order_waterfall_execution_history {
id BIGSERIAL [pk]
run_id "VARCHAR(64)" [not null, ref: > quantengine.decision_result_history.run_id]
ticker "VARCHAR(32)" [not null]
sell_priority_rank INT [not null]
waterfall_stage "VARCHAR(64)" [not null]
action "VARCHAR(16)" [not null]
target_qty INT [not null]
executed_qty INT [default: "0"]
target_price "NUMERIC(18,4)"
executed_price "NUMERIC(18,4)"
bid_ask_spread_bps "NUMERIC(10,2)"
slippage_bps "NUMERIC(10,2)"
status "VARCHAR(32)" [not null]
rationale TEXT
created_at TIMESTAMPTZ [default: "NOW()"]
Note: "매도 워터폴 실행 이력"
}
Table quantengine.shadow_ledger_history {
id BIGSERIAL [pk]
run_id "VARCHAR(64)" [not null, ref: > quantengine.decision_result_history.run_id]
ticker "VARCHAR(32)" [not null]
blocked_gate "VARCHAR(64)" [not null]
blocked_reason TEXT [not null]
shadow_price "NUMERIC(18,4)" [not null]
shadow_qty INT [not null]
shadow_tp_price "NUMERIC(18,4)"
shadow_sl_price "NUMERIC(18,4)"
created_at TIMESTAMPTZ [default: "NOW()"]
Note: "게이트에 막힌 주문의 가상 체결 감사 기록 (Shadow Ledger)"
}
Table quantengine.scheduler_state_history {
id BIGSERIAL [pk]
task_name "VARCHAR(64)" [not null]
execution_id "VARCHAR(64)" [unique, not null]
state "VARCHAR(32)" [not null]
started_at TIMESTAMPTZ [not null, default: "NOW()"]
finished_at TIMESTAMPTZ
error_message TEXT
lock_token "VARCHAR(64)"
indexes {
(task_name, state) [name: "idx_scheduler_state_task"]
}
Note: "스케줄러 작업 상태 머신 이력"
}
// ============================================================================= // =============================================================================
// Relationships (Logical, not enforced as FKs in DDL) // Relationships (Logical, not enforced as FKs in DDL)
// ============================================================================= // =============================================================================
-1
View File
@@ -47,7 +47,6 @@
"validate-realized-performance": "python tools/validate_realized_performance_v1.py", "validate-realized-performance": "python tools/validate_realized_performance_v1.py",
"validate-gas-recovery": "python tools/validate_gas_orchestration_recovery_v1.py", "validate-gas-recovery": "python tools/validate_gas_orchestration_recovery_v1.py",
"ops:clean": "python tools/clean_temp_artifacts_v1.py", "ops:clean": "python tools/clean_temp_artifacts_v1.py",
"ops:dev": "node core_satellite_collector.js",
"full-gate": "python tools/run_release_dag_v3.py --mode release --strict", "full-gate": "python tools/run_release_dag_v3.py --mode release --strict",
"validate-engine-strict": "python tools/run_release_dag_v3.py --mode release --strict", "validate-engine-strict": "python tools/run_release_dag_v3.py --mode release --strict",
"validate-behavioral-coverage": "python tools/validate_behavioral_coverage_v1.py --strict", "validate-behavioral-coverage": "python tools/validate_behavioral_coverage_v1.py --strict",
+6 -1
View File
@@ -1,5 +1,10 @@
# OMS·WMS·ERP Strategic Execution Framework v1.0 # OMS·WMS·ERP Strategic Execution Framework v1.0
# Based on actual PDF specifications (not hallucinated) # ⚠️ PDF 출처 미검증 (2026-07-30 재정정): 이 헤더는 원래 "실제 PDF 5건(179페이지)에
# 근거" (not hallucinated)라고 주장했으나, 저장소 전체를 검색해도 해당 PDF는 어디에도
# 없다. 본문에 흩어진 "(PDF n...)" 인용 40여 건은 전부 미검증 상태로 취급할 것 —
# 원본 PDF를 저장소(또는 접근 가능한 공유 위치)에서 찾아 재검증하기 전까지는
# "확인됨"이 아니라 "출처 주장됨"이다. (참고: 이 파일은 759줄이며, 다른 문서에서
# "7,000+ lines"로 인용된 것은 사실이 아니다.)
# 30 Strategic Principles Applied Throughout # 30 Strategic Principles Applied Throughout
# Created: 2026-07-26 (Post-Advisor Correction) # Created: 2026-07-26 (Post-Advisor Correction)
-19
View File
@@ -1,19 +0,0 @@
import { createApp } from 'vue';
import PrimeVue from 'primevue/config';
import Aura from '@primevue/themes/aura';
import App from './App.vue';
import router from './router';
import 'ag-grid-community/styles/ag-grid.css';
import 'ag-grid-community/styles/ag-theme-alpine.css';
const app = createApp(App);
app.use(PrimeVue, {
theme: {
preset: Aura
}
});
app.use(router);
app.mount('#app');
@@ -1,122 +0,0 @@
<template>
<div class="douzone-viewport-container d-flex flex-column h-100">
<!-- 1. Douzone Top Toolbar -->
<header class="douzone-header-toolbar d-flex justify-content-between align-items-center p-2 bg-navy text-white">
<div class="d-flex align-items-center gap-3">
<span class="fw-bold fs-4 text-warning">QuantEngine ERP v4.0 (Vue 3 / AG Grid)</span>
<span class="badge bg-success">PostgreSQL 3NF Connected</span>
</div>
<div>
<button class="btn btn-sm btn-secondary me-1" @click="fetchData"><span class="hotkey-badge">F3</span>조회</button>
<button class="btn btn-sm btn-primary me-1"><span class="hotkey-badge">F4</span>저장</button>
<button class="btn btn-sm btn-danger me-1"><span class="hotkey-badge">F5</span>삭제</button>
<button class="btn btn-sm btn-success"><span class="hotkey-badge">F7</span>엑셀</button>
</div>
</header>
<!-- 2. Master-Detail AG Grid Viewport (No Page Scroll) -->
<div class="flex-grow-1 row g-0 overflow-hidden">
<!-- Left: AG Grid Master List (65%) -->
<div class="col-8 border-end h-100 p-2">
<ag-grid-vue
style="width: 100%; height: 100%;"
class="ag-theme-alpine"
:columnDefs="columnDefs"
:rowData="rowData"
:defaultColDef="defaultColDef"
@row-selected="onRowSelected"
rowSelection="single"
>
</ag-grid-vue>
</div>
<!-- Right: Detail & Audit Provenance Inspector (35%) -->
<div class="col-4 h-100 p-3 bg-light overflow-auto">
<h5 class="fw-bold text-navy mb-3"><i class="ti ti-info-circle me-1"></i>상세 Provenance 검토</h5>
<div v-if="selectedRow" class="card p-3 shadow-sm border">
<div class="mb-2"><strong>실행 ID:</strong> {{ selectedRow.runId }}</div>
<div class="mb-2"><strong>시작 시간:</strong> {{ selectedRow.startedAt }}</div>
<div class="mb-2"><strong>종료 시간:</strong> {{ selectedRow.finishedAt || '-' }}</div>
<div class="mb-2">
<strong>상태:</strong>
<span :class="getStatusBadgeClass(selectedRow.status)">{{ selectedRow.status }}</span>
</div>
<div class="mb-2"><strong> 스냅샷:</strong> {{ selectedRow.totalSnapshots }} </div>
<div class="mb-2"><strong>오류 건수:</strong> {{ selectedRow.totalErrors }} </div>
<hr/>
<div class="text-muted small">
<strong>Data Integrity:</strong> 3NF Relational Parity Verified<br/>
<strong>Provenance:</strong> FastEndpoints /api/admin/grid-data
</div>
</div>
<div v-else class="text-muted text-center py-5">
좌측 AG Grid에서 행을 선택하면 상세 정보가 표출됩니다.
</div>
</div>
</div>
<!-- 3. Bottom Hotkey Guidance Footer -->
<footer class="douzone-summary-footer bg-dark text-white p-2 d-flex justify-content-between fs-7">
<div>
<span><span class="hotkey-badge">Enter</span>다음 포커스</span>
<span class="ms-3"><span class="hotkey-badge">F2</span>코드 lookup</span>
<span class="ms-3"><span class="hotkey-badge">F3</span>조회</span>
<span class="ms-3"><span class="hotkey-badge">F4</span>저장</span>
<span class="ms-3"><span class="hotkey-badge">F7</span>엑셀 다운로드</span>
</div>
<div>
<span class="opacity-75">Vue 3 + PrimeVue / AG Grid Modern Frontend Standard</span>
</div>
</footer>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { AgGridVue } from 'ag-grid-vue3';
import axios from 'axios';
const rowData = ref([]);
const selectedRow = ref(null);
const columnDefs = ref([
{ field: 'runId', headerName: '실행 ID', flex: 1, sortable: true, filter: true },
{ field: 'startedAt', headerName: '시작 시간', flex: 1.5, sortable: true },
{ field: 'finishedAt', headerName: '종료 시간', flex: 1.5, sortable: true },
{ field: 'status', headerName: '상태', flex: 1, sortable: true, filter: true },
{ field: 'totalSnapshots', headerName: '스냅샷 수', flex: 1, sortable: true },
{ field: 'totalErrors', headerName: '오류 수', flex: 1, sortable: true }
]);
const defaultColDef = ref({
resizable: true
});
const fetchData = async () => {
try {
const response = await axios.get('/api/admin/grid-data');
if (response.data && response.data.items) {
rowData.value = response.data.items;
}
} catch (err) {
console.error('Failed to fetch grid data:', err);
}
};
const onRowSelected = (event) => {
if (event.node.isSelected()) {
selectedRow.value = event.data;
}
};
const getStatusBadgeClass = (status) => {
const s = (status || '').toLowerCase();
if (s === 'completed' || s === 'pass') return 'badge bg-success';
if (s === 'running' || s === 'warn') return 'badge bg-warning text-dark';
return 'badge bg-danger';
};
onMounted(() => {
fetchData();
});
</script>
@@ -0,0 +1,51 @@
using System.Linq;
using QuantEngine.Infrastructure.Data;
namespace QuantEngine.Core.Tests;
public class MigrationScriptNameComparerTests
{
[Fact]
public void Sorts_DoubleDigit_Version_After_SingleDigit_Versions()
{
var scripts = new[]
{
"QuantEngine.Infrastructure.Migrations.V10__Normalize_Snapshots_Schema.sql",
"QuantEngine.Infrastructure.Migrations.V2__Add_Kis_Collections.sql",
"QuantEngine.Infrastructure.Migrations.V9__Add_Audit_Trail_Tables.sql",
"QuantEngine.Infrastructure.Migrations.V1__Initial_Schema.sql",
"QuantEngine.Infrastructure.Migrations.V8__PostgreSQL_History_First_Schema.sql",
};
var sorted = scripts.OrderBy(s => s, new MigrationScriptNameComparer()).ToArray();
Assert.Equal(new[]
{
"QuantEngine.Infrastructure.Migrations.V1__Initial_Schema.sql",
"QuantEngine.Infrastructure.Migrations.V2__Add_Kis_Collections.sql",
"QuantEngine.Infrastructure.Migrations.V8__PostgreSQL_History_First_Schema.sql",
"QuantEngine.Infrastructure.Migrations.V9__Add_Audit_Trail_Tables.sql",
"QuantEngine.Infrastructure.Migrations.V10__Normalize_Snapshots_Schema.sql",
}, sorted);
}
[Fact]
public void Regression_ZeroPadded_Script_No_Longer_Sorts_Before_V1()
{
// This is the exact bug that shipped 2026-07-24: "V003_..." sorted before "V1__..."
// under plain ordinal comparison, so a migration with unmet table dependencies ran
// first. The comparer must treat "V003" as version 3, landing it between V2 and V4.
var scripts = new[]
{
"QuantEngine.Infrastructure.Migrations.V003_add_audit_trail_tables.sql",
"QuantEngine.Infrastructure.Migrations.V1__Initial_Schema.sql",
"QuantEngine.Infrastructure.Migrations.V4__Add_Initial_Admin.sql",
};
var sorted = scripts.OrderBy(s => s, new MigrationScriptNameComparer()).ToArray();
Assert.Equal("QuantEngine.Infrastructure.Migrations.V1__Initial_Schema.sql", sorted[0]);
Assert.Equal("QuantEngine.Infrastructure.Migrations.V003_add_audit_trail_tables.sql", sorted[1]);
Assert.Equal("QuantEngine.Infrastructure.Migrations.V4__Add_Initial_Admin.sql", sorted[2]);
}
}
@@ -1,6 +1,5 @@
using System.Reflection; using System.Reflection;
using QuantEngine.Infrastructure.External; using QuantEngine.Infrastructure.Services;
using QuantEngine.Infrastructure.Data;
namespace QuantEngine.Core.Tests; namespace QuantEngine.Core.Tests;
@@ -12,9 +11,7 @@ public class SecurityTests
[InlineData("/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice", "FHKST03010100")] [InlineData("/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice", "FHKST03010100")]
public void AssertReadOnly_AllowsReadOnlyQuotationPaths(string path, string trId) public void AssertReadOnly_AllowsReadOnlyQuotationPaths(string path, string trId)
{ {
var client = CreateClient(); var ex = Record.Exception(() => InvokeAssertReadOnly(path, trId));
var ex = Record.Exception(() => InvokeAssertReadOnly(client, path, trId));
Assert.Null(ex); Assert.Null(ex);
} }
@@ -25,45 +22,34 @@ public class SecurityTests
[InlineData("/uapi/domestic-stock/v1/trading/order-cash", "FHKST01010100")] [InlineData("/uapi/domestic-stock/v1/trading/order-cash", "FHKST01010100")]
public void AssertReadOnly_BlocksTradingPathsOrIds(string path, string trId) public void AssertReadOnly_BlocksTradingPathsOrIds(string path, string trId)
{ {
var client = CreateClient(); var ex = Assert.Throws<TargetInvocationException>(() => InvokeAssertReadOnly(path, trId));
var ex = Assert.Throws<TargetInvocationException>(() => InvokeAssertReadOnly(client, path, trId));
Assert.IsType<InvalidOperationException>(ex.InnerException); Assert.IsType<InvalidOperationException>(ex.InnerException);
Assert.Contains("BLOCKED", ex.InnerException!.Message); Assert.Contains("BLOCKED", ex.InnerException!.Message);
} }
[Fact] [Theory]
public void AssertReadOnly_BlocksKnownTradingTrIdPrefixes() [InlineData("VTTC8434R00")]
[InlineData("TTTC9912U")]
[InlineData("VTTC5555X")]
public void AssertReadOnly_BlocksEntireTradingTrIdFamily_NotJustHardcodedCodes(string trId)
{ {
var client = CreateClient(); // These TR_IDs are not among the previously hardcoded exact-match list — they only get
// blocked once the guard checks the true TTTC*/VTTC* prefix family instead of a fixed
var ex = Assert.Throws<TargetInvocationException>(() => InvokeAssertReadOnly(client, "/uapi/domestic-stock/v1/quotations/inquire-price", "VTTC8434R00")); // set of known order codes.
var ex = Assert.Throws<TargetInvocationException>(() =>
InvokeAssertReadOnly("/uapi/domestic-stock/v1/quotations/inquire-price", trId));
Assert.IsType<InvalidOperationException>(ex.InnerException); Assert.IsType<InvalidOperationException>(ex.InnerException);
Assert.Contains("TR_ID", ex.InnerException!.Message); Assert.Contains("TR_ID", ex.InnerException!.Message);
} }
private static KisApiClient CreateClient() private static void InvokeAssertReadOnly(string path, string trId)
{ {
Environment.SetEnvironmentVariable("KIS_APP_Key_TEST", "mock-key"); // QuantEngine.Infrastructure.Services.KisApiClient is the class actually DI-registered
Environment.SetEnvironmentVariable("KIS_APP_Secret_TEST", "mock-secret"); // in Program.cs and running in production — a second, unused KisApiClient used to live
return new KisApiClient(new HttpClient(new DummyHandler()), new NoopConnectionFactory()); // under Infrastructure.External with its own independent AssertReadOnly implementation
} // that this test suite exercised instead. That class has been removed.
var method = typeof(KisApiClient).GetMethod("AssertReadOnly", BindingFlags.Static | BindingFlags.NonPublic)
private static void InvokeAssertReadOnly(KisApiClient client, string path, string trId)
{
var method = typeof(KisApiClient).GetMethod("AssertReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
?? throw new InvalidOperationException("AssertReadOnly method not found."); ?? throw new InvalidOperationException("AssertReadOnly method not found.");
method.Invoke(client, new object[] { path, trId }); method.Invoke(null, new object[] { path, trId });
}
private sealed class DummyHandler : HttpMessageHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
=> Task.FromResult(new HttpResponseMessage(System.Net.HttpStatusCode.OK));
}
private sealed class NoopConnectionFactory : IDbConnectionFactory
{
public System.Data.IDbConnection CreateConnection() => throw new NotSupportedException("Not needed for read-only guard tests.");
} }
} }
@@ -28,6 +28,7 @@ namespace QuantEngine.Infrastructure.Data
var upgrader = DeployChanges.To var upgrader = DeployChanges.To
.PostgresqlDatabase(_connectionString) .PostgresqlDatabase(_connectionString)
.WithScriptsEmbeddedInAssembly(typeof(DbMigrator).Assembly, s => s.StartsWith("QuantEngine.Infrastructure.Migrations")) .WithScriptsEmbeddedInAssembly(typeof(DbMigrator).Assembly, s => s.StartsWith("QuantEngine.Infrastructure.Migrations"))
.WithScriptNameComparer(new MigrationScriptNameComparer())
.LogToConsole() .LogToConsole()
.Build(); .Build();
@@ -0,0 +1,43 @@
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace QuantEngine.Infrastructure.Data
{
/// <summary>
/// Orders DbUp migration scripts by their numeric V{n} version instead of plain ordinal
/// string order. Without this, "V10__Name.sql" sorts before "V2__Name.sql" (and, as
/// happened on 2026-07-24, zero-padded "V003_Name.sql" sorts before unpadded
/// "V1__Name.sql") because ordinal comparison looks at characters, not numeric value.
/// That mismatch let a migration with an unmet table dependency run first and silently
/// no-op, and another one run first and hard-fail, blocking every migration after it on a
/// fresh database. This comparer makes the "V{n}" scheme collision-proof regardless of
/// digit count or padding, so it can never happen again.
/// </summary>
public class MigrationScriptNameComparer : IComparer<string>
{
private static readonly Regex VersionPattern = new(@"V(\d+)", RegexOptions.Compiled);
public int Compare(string? x, string? y)
{
if (x == null || y == null)
{
return string.CompareOrdinal(x, y);
}
var matchX = VersionPattern.Match(x);
var matchY = VersionPattern.Match(y);
if (matchX.Success && matchY.Success)
{
var versionX = long.Parse(matchX.Groups[1].Value);
var versionY = long.Parse(matchY.Groups[1].Value);
if (versionX != versionY)
{
return versionX.CompareTo(versionY);
}
}
return string.CompareOrdinal(x, y);
}
}
}
@@ -1,250 +0,0 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;
using Dapper;
using QuantEngine.Core.Interfaces;
using QuantEngine.Infrastructure.Data;
namespace QuantEngine.Infrastructure.External
{
public class KisCredentials
{
public string AppKey { get; }
public string AppSecret { get; }
public string Account { get; } // "real" | "mock"
public string Domain { get; }
public KisCredentials(string appKey, string appSecret, string account)
{
AppKey = appKey;
AppSecret = appSecret;
Account = account;
Domain = account == "real"
? "https://openapi.koreainvestment.com:9443"
: "https://openapivts.koreainvestment.com:29443";
}
public static KisCredentials Load(string account = "mock")
{
string keyVar = account == "real" ? "KIS_APP_Key" : "KIS_APP_Key_TEST";
string secretVar = account == "real" ? "KIS_APP_Secret" : "KIS_APP_Secret_TEST";
string? appKey = Environment.GetEnvironmentVariable(keyVar);
string? appSecret = Environment.GetEnvironmentVariable(secretVar);
if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appSecret))
{
// Fallback registry checks are not cross-platform and environment variables should be defined.
// In production/Linux it is env-only.
throw new InvalidOperationException(
$"KIS Credentials Environment Variables missing: {keyVar} or {secretVar}."
);
}
return new KisCredentials(appKey, appSecret, account);
}
}
public class KisApiClient : IKisApiClient
{
private readonly HttpClient _httpClient;
private readonly IDbConnectionFactory _dbConnectionFactory;
private readonly KisCredentials _creds;
private static readonly string[] ForbiddenPathSubstrings = { "/trading/" };
private static readonly string[] ForbiddenTrIdPrefixes = { "TTTC08", "VTTC08", "TTTC01", "VTTC01", "TTTC8434R", "VTTC8434R" };
public KisApiClient(HttpClient httpClient, IDbConnectionFactory dbConnectionFactory, string account = "mock")
{
_httpClient = httpClient;
_dbConnectionFactory = dbConnectionFactory;
_creds = KisCredentials.Load(account);
}
private void AssertReadOnly(string path, string trId)
{
foreach (var forbidden in ForbiddenPathSubstrings)
{
if (path.Contains(forbidden, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException($"BLOCKED: 주문 관련 경로 호출 시도 차단 — path={path}");
}
}
foreach (var prefix in ForbiddenTrIdPrefixes)
{
if (trId.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException($"BLOCKED: 주문 관련 TR_ID 호출 시도 차단 — tr_id={trId}");
}
}
}
private async Task<string> IssueOrReuseTokenAsync()
{
using var conn = _dbConnectionFactory.CreateConnection();
conn.Open();
// 1. Try to load cached token
var cached = await conn.QueryFirstOrDefaultAsync<(string access_token, string expires_at)>(
"SELECT access_token, expires_at FROM quantengine.kis_tokens WHERE account = @Account",
new { Account = _creds.Account }
);
if (cached.access_token != null)
{
if (DateTime.TryParse(cached.expires_at, out var expiresAtUtc))
{
// Reuse token if it has more than 10 minutes left before expiration
if (DateTime.UtcNow < expiresAtUtc.AddMinutes(-10))
{
return cached.access_token;
}
}
}
// 2. Request new token from KIS API
var requestUrl = $"{_creds.Domain}/oauth2/tokenP";
var requestBody = new
{
grant_type = "client_credentials",
appkey = _creds.AppKey,
appsecret = _creds.AppSecret
};
var response = await _httpClient.PostAsJsonAsync(requestUrl, requestBody);
response.EnsureSuccessStatusCode();
var resData = await response.Content.ReadFromJsonAsync<JsonElement>();
var accessToken = resData.GetProperty("access_token").GetString()
?? throw new InvalidOperationException("Failed to parse access_token from response.");
var expiresInSec = resData.GetProperty("expires_in").GetInt32();
var expiresAt = DateTime.UtcNow.AddSeconds(expiresInSec);
// 3. Upsert token cache into PG database
await conn.ExecuteAsync(@"
INSERT INTO quantengine.kis_tokens (account, access_token, expires_at, updated_at)
VALUES (@Account, @AccessToken, @ExpiresAt, @UpdatedAt)
ON CONFLICT (account) DO UPDATE SET
access_token = EXCLUDED.access_token,
expires_at = EXCLUDED.expires_at,
updated_at = EXCLUDED.updated_at",
new
{
Account = _creds.Account,
AccessToken = accessToken,
ExpiresAt = expiresAt.ToString("o"),
UpdatedAt = DateTime.UtcNow.ToString("o")
}
);
return accessToken;
}
private async Task<string> SendRequestAsync(string path, string trId, Dictionary<string, string> queryParams)
{
AssertReadOnly(path, trId);
var token = await IssueOrReuseTokenAsync();
var queryBuilder = new List<string>();
foreach (var kvp in queryParams)
{
queryBuilder.Add($"{Uri.EscapeDataString(kvp.Key)}={Uri.EscapeDataString(kvp.Value)}");
}
var fullUrl = $"{_creds.Domain}{path}?{string.Join("&", queryBuilder)}";
using var request = new HttpRequestMessage(HttpMethod.Get, fullUrl);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Headers.Add("authorization", $"Bearer {token}");
request.Headers.Add("appkey", _creds.AppKey);
request.Headers.Add("appsecret", _creds.AppSecret);
request.Headers.Add("tr_id", trId);
request.Headers.Add("custtype", "P");
var response = await _httpClient.SendAsync(request);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
public async Task<Dictionary<string, object>> GetCurrentPriceAsync(string code, string account = "mock")
{
var json = await SendRequestAsync(
"/uapi/domestic-stock/v1/quotations/inquire-price",
"FHKST01010100",
new Dictionary<string, string>
{
{ "FID_COND_MRKT_DIV_CODE", "J" },
{ "FID_INPUT_ISCD", code }
}
);
return JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new();
}
public async Task<Dictionary<string, object>> GetAskingPrice10LevelAsync(string code, string account = "mock")
{
var json = await SendRequestAsync(
"/uapi/domestic-stock/v1/quotations/inquire-asking-price-exp-ccn",
"FHKST01010200",
new Dictionary<string, string>
{
{ "FID_COND_MRKT_DIV_CODE", "J" },
{ "FID_INPUT_ISCD", code }
}
);
return JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new();
}
public async Task<Dictionary<string, object>> GetDailyShortSaleAsync(string code, string startDate, string endDate, string account = "mock")
{
var json = await SendRequestAsync(
"/uapi/domestic-stock/v1/quotations/daily-short-sale",
"FHPST04830000",
new Dictionary<string, string>
{
{ "FID_COND_MRKT_DIV_CODE", "J" },
{ "FID_INPUT_ISCD", code },
{ "FID_INPUT_DATE_1", startDate },
{ "FID_INPUT_DATE_2", endDate }
}
);
return JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new();
}
public async Task<Dictionary<string, object>> GetDailyItemChartPriceAsync(string code, string startDate, string endDate, string period = "D", string account = "mock")
{
var json = await SendRequestAsync(
"/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice",
"FHKST03010100",
new Dictionary<string, string>
{
{ "FID_COND_MRKT_DIV_CODE", "J" },
{ "FID_INPUT_ISCD", code },
{ "FID_INPUT_DATE_1", startDate },
{ "FID_INPUT_DATE_2", endDate },
{ "FID_PERIOD_DIV_CODE", period },
{ "FID_ORG_ADJ_PRC", "0" }
}
);
return JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new();
}
public async Task<Dictionary<string, object>> GetInvestorTrendAsync(string code, string account = "mock")
{
var json = await SendRequestAsync(
"/uapi/domestic-stock/v1/quotations/inquire-investor",
"FHKST01010900",
new Dictionary<string, string>
{
{ "FID_COND_MRKT_DIV_CODE", "J" },
{ "FID_INPUT_ISCD", code }
}
);
return JsonSerializer.Deserialize<Dictionary<string, object>>(json) ?? new();
}
}
}
@@ -1,8 +1,18 @@
-- Migration: V004_normalize_snapshots_schema.sql -- Migration: V10__Normalize_Snapshots_Schema.sql (renamed from
-- V004_normalize_snapshots_schema.sql on 2026-07-30 — see note below)
-- Purpose: Implement 3NF normalization for kis_collection_snapshots -- Purpose: Implement 3NF normalization for kis_collection_snapshots
-- Phase: Phase 1 (Normalization & SOLID Refactoring) -- Phase: Phase 1 (Normalization & SOLID Refactoring)
-- Status: APPROVED for Sep 2026 implementation -- Status: APPROVED for Sep 2026 implementation
-- Safety: Parallel operation with existing schema via Adapter pattern -- Safety: Parallel operation with existing schema via Adapter pattern
--
-- 2026-07-30: Originally named V004_normalize_snapshots_schema.sql, which alphabetically
-- sorted BEFORE V1__Initial_Schema.sql. Its FK constraint referencing
-- quantengine.kis_collection_runs(id) (created by V2) is not guarded — on a fresh database
-- this would hard-fail with "relation does not exist" and abort every migration after it,
-- meaning V1 through V8 would never run at all. Renamed to V10 (after DbMigrator.cs was given
-- a numeric-aware script comparer, MigrationScriptNameComparer, so double-digit versions sort
-- correctly) so it now runs after its dependency exists. Confirmed via production query that
-- this migration had never actually applied.
-- ============================================================================ -- ============================================================================
-- DIMENSION TABLES (Star Schema) -- DIMENSION TABLES (Star Schema)
@@ -1,7 +1,18 @@
-- Migration: V003_add_audit_trail_tables.sql -- Migration: V9__Add_Audit_Trail_Tables.sql (renamed from V003_add_audit_trail_tables.sql
-- on 2026-07-30 — see header note below)
-- Purpose: Add audit trail tables for tracking all data changes -- Purpose: Add audit trail tables for tracking all data changes
-- Date: 2026-07-24 -- Date: 2026-07-24
-- Status: APPROVED for Phase 0 implementation -- Status: APPROVED for Phase 0 implementation
--
-- 2026-07-30: Originally named V003_add_audit_trail_tables.sql, which alphabetically sorted
-- BEFORE V1__Initial_Schema.sql. Its trigger-creation guards (IF EXISTS checks on
-- kis_collection_runs / kis_collection_snapshots) would have silently no-op'd forever on a
-- fresh database, since those tables (created by V2) wouldn't exist yet when V003 ran first.
-- Renamed to V9 (after DbMigrator.cs was given a numeric-aware script comparer,
-- MigrationScriptNameComparer, so "V9"/"V10" sort correctly relative to "V1".."V8" regardless
-- of digit count) so it now runs after its dependencies exist. Also fixed a MySQL-only inline
-- INDEX syntax that made this script fail outright on PostgreSQL (separate fix, same day).
-- Confirmed via production query that this migration had never actually applied before either fix.
-- ============================================================================ -- ============================================================================
-- kis_collection_runs_audit: Audit trail for collection runs -- kis_collection_runs_audit: Audit trail for collection runs
@@ -26,12 +37,15 @@ CREATE TABLE IF NOT EXISTS quantengine.kis_collection_runs_audit (
-- Foreign key constraint (optional - don't enforce if kis_collection_runs might be deleted) -- Foreign key constraint (optional - don't enforce if kis_collection_runs might be deleted)
-- CONSTRAINT fk_kis_collection_runs_audit FOREIGN KEY (run_id) -- CONSTRAINT fk_kis_collection_runs_audit FOREIGN KEY (run_id)
-- REFERENCES quantengine.kis_collection_runs(id) ON DELETE CASCADE -- REFERENCES quantengine.kis_collection_runs(id) ON DELETE CASCADE
INDEX idx_kis_collection_runs_audit_run_id (run_id, changed_at DESC),
INDEX idx_kis_collection_runs_audit_changed_by (changed_by, changed_at DESC),
INDEX idx_kis_collection_runs_audit_timestamp (changed_at DESC)
); );
CREATE INDEX IF NOT EXISTS idx_kis_collection_runs_audit_run_id
ON quantengine.kis_collection_runs_audit (run_id, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_runs_audit_changed_by
ON quantengine.kis_collection_runs_audit (changed_by, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_runs_audit_timestamp
ON quantengine.kis_collection_runs_audit (changed_at DESC);
-- ============================================================================ -- ============================================================================
-- kis_collection_snapshots_audit: Audit trail for snapshots -- kis_collection_snapshots_audit: Audit trail for snapshots
-- ============================================================================ -- ============================================================================
@@ -55,12 +69,15 @@ CREATE TABLE IF NOT EXISTS quantengine.kis_collection_snapshots_audit (
-- Foreign key constraint (optional) -- Foreign key constraint (optional)
-- CONSTRAINT fk_kis_collection_snapshots_audit FOREIGN KEY (snapshot_id) -- CONSTRAINT fk_kis_collection_snapshots_audit FOREIGN KEY (snapshot_id)
-- REFERENCES quantengine.kis_collection_snapshots(id) ON DELETE CASCADE -- REFERENCES quantengine.kis_collection_snapshots(id) ON DELETE CASCADE
INDEX idx_kis_collection_snapshots_audit_snapshot_id (snapshot_id, changed_at DESC),
INDEX idx_kis_collection_snapshots_audit_changed_by (changed_by, changed_at DESC),
INDEX idx_kis_collection_snapshots_audit_timestamp (changed_at DESC)
); );
CREATE INDEX IF NOT EXISTS idx_kis_collection_snapshots_audit_snapshot_id
ON quantengine.kis_collection_snapshots_audit (snapshot_id, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_snapshots_audit_changed_by
ON quantengine.kis_collection_snapshots_audit (changed_by, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_snapshots_audit_timestamp
ON quantengine.kis_collection_snapshots_audit (changed_at DESC);
-- ============================================================================ -- ============================================================================
-- kis_collection_errors_audit: Audit trail for error records -- kis_collection_errors_audit: Audit trail for error records
-- ============================================================================ -- ============================================================================
@@ -79,13 +96,16 @@ CREATE TABLE IF NOT EXISTS quantengine.kis_collection_errors_audit (
new_values JSONB, new_values JSONB,
-- Audit trail indexing -- Audit trail indexing
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
INDEX idx_kis_collection_errors_audit_error_id (error_id, changed_at DESC),
INDEX idx_kis_collection_errors_audit_changed_by (changed_by, changed_at DESC),
INDEX idx_kis_collection_errors_audit_timestamp (changed_at DESC)
); );
CREATE INDEX IF NOT EXISTS idx_kis_collection_errors_audit_error_id
ON quantengine.kis_collection_errors_audit (error_id, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_errors_audit_changed_by
ON quantengine.kis_collection_errors_audit (changed_by, changed_at DESC);
CREATE INDEX IF NOT EXISTS idx_kis_collection_errors_audit_timestamp
ON quantengine.kis_collection_errors_audit (changed_at DESC);
-- ============================================================================ -- ============================================================================
-- Trigger Functions: Auto-log changes to kis_collection_runs -- Trigger Functions: Auto-log changes to kis_collection_runs
-- ============================================================================ -- ============================================================================
@@ -22,11 +22,11 @@ public class KisApiClient : IKisApiClient
private const int TokenRefreshSkewMinutes = 10; private const int TokenRefreshSkewMinutes = 10;
private static readonly string[] ForbiddenPathSubstrings = { "/trading/" }; private static readonly string[] ForbiddenPathSubstrings = { "/trading/" };
private static readonly string[] ForbiddenTrIdPrefixes =
{ // 실제 매수/매도 주문 TR_ID는 전부 TTTC/VTTC로 시작한다 (governance/rules/06_no_direct_api_trading.yaml).
"TTTC08", "VTTC08", "TTTC01", "VTTC01", // 개별 주문 코드를 나열하면 목록에 없는 신규 주문 TR_ID가 새어나갈 수 있으므로 접두사 전체를 차단한다.
"TTTC8434R", "VTTC8434R" // 이 클라이언트가 실제로 호출하는 조회용 TR_ID는 전부 FH로 시작해 이 규칙과 절대 겹치지 않는다.
}; private static readonly string[] ForbiddenTrIdPrefixes = { "TTTC", "VTTC" };
private readonly HttpClient _httpClient; private readonly HttpClient _httpClient;
private readonly ITokenCache _tokenCache; private readonly ITokenCache _tokenCache;
@@ -75,6 +75,17 @@ namespace QuantEngine.Web.Pages.Admin.Database
using var conn = _connectionFactory.CreateConnection(); using var conn = _connectionFactory.CreateConnection();
if (conn.State != ConnectionState.Open) conn.Open(); if (conn.State != ConnectionState.Open) conn.Open();
// Column/PK names come from the request, so they must be checked against the
// table's real columns before going anywhere near a SQL string — otherwise an
// attacker-controlled form field name reaches the query unescaped.
var columnWhitelist = await LoadColumnWhitelistAsync(conn, tableName);
if (string.IsNullOrEmpty(pkColumn) || !columnWhitelist.Contains(pkColumn))
{
ErrorMessage = "허용되지 않은 기본 키 컬럼입니다.";
return Page();
}
// Load target columns to update // Load target columns to update
var columns = new List<string>(); var columns = new List<string>();
var parameters = new List<NpgsqlParameter>(); var parameters = new List<NpgsqlParameter>();
@@ -84,6 +95,9 @@ namespace QuantEngine.Web.Pages.Admin.Database
if (key == "tableName" || key == "pkColumn" || key == "pkValue" || key == "__RequestVerificationToken") if (key == "tableName" || key == "pkColumn" || key == "pkValue" || key == "__RequestVerificationToken")
continue; continue;
if (!columnWhitelist.Contains(key))
continue; // 테이블에 실재하지 않는 컬럼명은 무시 (SQL 인젝션 방지)
var val = Request.Form[key].ToString(); var val = Request.Form[key].ToString();
columns.Add($"\"{key}\" = @{key}"); columns.Add($"\"{key}\" = @{key}");
@@ -133,6 +147,8 @@ namespace QuantEngine.Web.Pages.Admin.Database
using var conn = _connectionFactory.CreateConnection(); using var conn = _connectionFactory.CreateConnection();
if (conn.State != ConnectionState.Open) conn.Open(); if (conn.State != ConnectionState.Open) conn.Open();
var columnWhitelist = await LoadColumnWhitelistAsync(conn, tableName);
var colNames = new List<string>(); var colNames = new List<string>();
var paramNames = new List<string>(); var paramNames = new List<string>();
var parameters = new List<NpgsqlParameter>(); var parameters = new List<NpgsqlParameter>();
@@ -142,6 +158,9 @@ namespace QuantEngine.Web.Pages.Admin.Database
if (key == "tableName" || key == "__RequestVerificationToken") if (key == "tableName" || key == "__RequestVerificationToken")
continue; continue;
if (!columnWhitelist.Contains(key))
continue; // 테이블에 실재하지 않는 컬럼명은 무시 (SQL 인젝션 방지)
var val = Request.Form[key].ToString(); var val = Request.Form[key].ToString();
colNames.Add($"\"{key}\""); colNames.Add($"\"{key}\"");
paramNames.Add($"@{key}"); paramNames.Add($"@{key}");
@@ -171,6 +190,35 @@ namespace QuantEngine.Web.Pages.Admin.Database
return RedirectToPage(new { tableName }); return RedirectToPage(new { tableName });
} }
/// <summary>
/// DB-verified column names for a table, used to validate any identifier (PK column,
/// form field names) before it is interpolated into a SQL string. Table names arriving
/// here must already be whitelist-checked against TableList by the caller.
/// </summary>
private async Task<HashSet<string>> LoadColumnWhitelistAsync(IDbConnection conn, string tableName)
{
var parts = tableName.Split('.');
var schema = parts[0];
var tableOnly = parts[1];
var sql = @"
SELECT column_name
FROM information_schema.columns
WHERE table_schema = @schema AND table_name = @table_only;";
using var cmd = new NpgsqlCommand(sql, (NpgsqlConnection)conn);
cmd.Parameters.AddWithValue("@schema", schema);
cmd.Parameters.AddWithValue("@table_only", tableOnly);
var columns = new HashSet<string>(StringComparer.Ordinal);
using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
columns.Add(reader.GetString(0));
}
return columns;
}
private async Task LoadTableListAsync() private async Task LoadTableListAsync()
{ {
TableList.Clear(); TableList.Clear();
@@ -0,0 +1,6 @@
namespace QuantEngine.Web.Pages.Shared;
public class DeleteConfirmModalViewModel
{
public string Message { get; set; } = string.Empty;
}
@@ -0,0 +1,10 @@
namespace QuantEngine.Web.Pages.Shared;
public class PageHeaderViewModel
{
public string Title { get; set; } = string.Empty;
public string PreTitle { get; set; } = string.Empty;
public bool HasAction { get; set; }
public string ActionText { get; set; } = string.Empty;
public string ActionUrl { get; set; } = string.Empty;
}
@@ -0,0 +1,34 @@
@model QuantEngine.Web.Pages.Shared.DeleteConfirmModalViewModel
<div class="modal modal-blur fade" id="modal-delete-confirm" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
<div class="modal-content">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
<div class="modal-status bg-danger"></div>
<form method="post" asp-page-handler="Delete">
@Html.AntiForgeryToken()
<input type="hidden" name="Id" id="delete-target-id" />
<div class="modal-body text-center py-4">
<i class="ti ti-alert-triangle text-danger fs-1 mb-2"></i>
<h3 class="fw-bold">정말 삭제하시겠습니까?</h3>
<div class="text-muted fs-7" id="delete-target-name">
@(string.IsNullOrEmpty(Model?.Message) ? "선택한 항목이 비활성(Soft Delete) 처리됩니다." : Model.Message)
</div>
</div>
<div class="modal-footer">
<div class="w-100">
<div class="row">
<div class="col">
<button type="button" class="btn w-100 btn-secondary" data-bs-dismiss="modal">취소</button>
</div>
<div class="col">
<button type="submit" class="btn w-100 btn-danger">삭제 실행</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
@@ -0,0 +1,21 @@
@model QuantEngine.Web.Pages.Shared.PageHeaderViewModel
<div class="page-header d-print-none mb-3">
<div class="row align-items-center">
<div class="col">
@if (!string.IsNullOrEmpty(Model.PreTitle))
{
<div class="page-pretitle text-muted text-uppercase fs-7 fw-bold mb-1">@Model.PreTitle</div>
}
<h2 class="page-title fw-bold">@Model.Title</h2>
</div>
@if (Model.HasAction)
{
<div class="col-auto ms-auto d-print-none">
<a href="@Model.ActionUrl" class="btn btn-primary">
@Model.ActionText
</a>
</div>
}
</div>
</div>
@@ -0,0 +1,377 @@
from __future__ import annotations
import math
from datetime import date, timedelta
from typing import Any
# 매도 결정에 동원하는 5개 독립 팩터군. 단일 팩터의 임계값 돌파만으로는 행동을
# 트리거하지 않는다 — 최소 CONFLUENCE_MIN개 팩터군이 동일 방향으로 합의해야
# SELL/ADD 확신도가 성립한다. (기계적 단일 트리거 매도 금지 원칙)
FACTOR_FAMILIES: tuple[str, ...] = (
"macro_pressure",
"fundamental_trajectory",
"short_interest_pressure",
"microstructure_pressure",
"liquidity_rotation_risk",
)
CONFLUENCE_MIN = 3
EVENT_PRE_GUARD_DAYS = 5 # macro_event_synchronizer_v2.event_hold_gate와 동일 — HIGH 이벤트 5일 전
EVENT_POST_GUARD_DAYS = 2 # 이벤트 후 2일 변동성 소화 구간
# 금리국면별 시장 성격: 금리 상승기=실적장세(펀더멘털/수출입 실적이 가격을 주도),
# 금리 보합·하락기=기술장세(수급·미시구조가 가격을 주도). 동일한 5팩터라도
# 국면에 따라 가중치를 달리 줘야 confluence가 의미를 갖는다.
REGIME_FLAT_WEIGHTS: dict[str, float] = {family: 1.0 for family in FACTOR_FAMILIES}
REGIME_WEIGHT_TABLE: dict[str, dict[str, float]] = {
"PERFORMANCE_MARKET": { # 금리 상승기 — 실적/수출입 펀더멘털 가중 상향
"macro_pressure": 1.2,
"fundamental_trajectory": 1.8,
"short_interest_pressure": 1.0,
"microstructure_pressure": 0.5,
"liquidity_rotation_risk": 1.0,
},
"TECHNICAL_MARKET": { # 금리 보합·하락기 — 수급/미시구조 가중 상향
"macro_pressure": 0.8,
"fundamental_trajectory": 0.8,
"short_interest_pressure": 1.3,
"microstructure_pressure": 1.6,
"liquidity_rotation_risk": 1.3,
},
"NEUTRAL": REGIME_FLAT_WEIGHTS,
}
def classify_market_regime(rate_trend: str | None) -> str:
"""금리 추세 문자열(RISING/FLAT/FALLING)을 실적장세/기술장세로 분류.
RISING PERFORMANCE_MARKET(실적장세): 금리 상승기엔 유동성보다 실적/펀더멘털이
가격을 결정. FLAT/FALLING TECHNICAL_MARKET(기술장세): 유동성이 풍부해 수급·
미시구조·테마성 모멘텀이 가격을 주도. 입력 결측 NEUTRAL(가중치 변화 없음).
"""
trend = str(rate_trend or "").upper()
if trend == "RISING":
return "PERFORMANCE_MARKET"
if trend in {"FLAT", "FALLING"}:
return "TECHNICAL_MARKET"
return "NEUTRAL"
def _finite(value: Any) -> bool:
return isinstance(value, (int, float)) and math.isfinite(float(value))
def compute_short_interest_composite(ctx: dict[str, Any]) -> dict[str, Any]:
"""SHORT_INTEREST_RISK_GAUGE_V1.
5요소: 공매도잔고율 변화, 공매도거래비중, 상대수익률(섹터/지수 대비),
거래량 이상, 실적전망. 잔고율 단독으로는 매도 근거가 약함(현대로템형)
잔고율이 낮을 때는 거래비중·상대수익률 가중치를 자동 상향한다.
"""
missing: list[str] = []
short_balance_ratio = ctx.get("short_balance_ratio") # %, 현재 잔고율
short_balance_ratio_chg_20d = ctx.get("short_balance_ratio_chg_20d") # %p, 20일 변화
short_turnover_share = ctx.get("short_turnover_share") # 당일 거래 중 공매도 비중 %
relative_return_20d = ctx.get("relative_return_20d") # 종목수익률 - 섹터(or지수)수익률, %p
volume_ratio_5d = ctx.get("volume_ratio_5d") # 5일평균거래량 대비 비율
earnings_outlook = str(ctx.get("earnings_outlook") or "").upper() # IMPROVING|STABLE|DETERIORATING|UNKNOWN
for name, value in (
("short_balance_ratio", short_balance_ratio),
("short_turnover_share", short_turnover_share),
("relative_return_20d", relative_return_20d),
):
if not _finite(value):
missing.append(name)
if missing:
return {
"short_interest_pressure": None,
"status": "DATA_MISSING",
"missing_inputs": missing,
"note": "잔고율/거래비중/상대수익률 중 결측 — 공매도 합성 점수를 산출하지 않음(추정 금지)",
}
low_balance_regime = float(short_balance_ratio) < 1.0 # 잔고율 1% 미만이면 '낮은 잔고율' 취급(현대로템형)
# 잔고율 추세: 상승=매도근거 강화, 하락=매도근거 약화(혹은 매수근거)
balance_trend_signal = 0.0
if _finite(short_balance_ratio_chg_20d):
balance_trend_signal = max(-1.0, min(1.0, float(short_balance_ratio_chg_20d) / 1.5))
turnover_signal = max(-1.0, min(1.0, (float(short_turnover_share) - 8.0) / 12.0)) # 8% 기준선
relative_return_signal = max(-1.0, min(1.0, -float(relative_return_20d) / 10.0)) # 상대 약세일수록 +
volume_signal = 0.0
if _finite(volume_ratio_5d):
volume_signal = max(-1.0, min(1.0, (float(volume_ratio_5d) - 1.0)))
outlook_signal = {
"IMPROVING": -0.6,
"STABLE": 0.0,
"DETERIORATING": 0.7,
}.get(earnings_outlook, 0.0)
if low_balance_regime:
# 잔고율 자체는 약한 근거 — 거래비중·상대수익률 가중치 상향, 잔고율추세 가중치 하향
weights = {"balance": 0.10, "turnover": 0.30, "relative": 0.30, "volume": 0.10, "outlook": 0.20}
else:
weights = {"balance": 0.30, "turnover": 0.20, "relative": 0.20, "volume": 0.10, "outlook": 0.20}
pressure = (
balance_trend_signal * weights["balance"]
+ turnover_signal * weights["turnover"]
+ relative_return_signal * weights["relative"]
+ volume_signal * weights["volume"]
+ outlook_signal * weights["outlook"]
)
pressure = max(-1.0, min(1.0, pressure))
label = "ELEVATED_SHORT_PRESSURE" if pressure >= 0.5 else "WATCH" if pressure >= 0.2 else \
"SHORT_COVERING_SUPPORTIVE" if pressure <= -0.5 else "NEUTRAL"
return {
"short_interest_pressure": round(pressure, 4),
"status": "OK",
"low_balance_regime": low_balance_regime,
"label": label,
"components": {
"balance_trend_signal": round(balance_trend_signal, 4),
"turnover_signal": round(turnover_signal, 4),
"relative_return_signal": round(relative_return_signal, 4),
"volume_signal": round(volume_signal, 4),
"outlook_signal": outlook_signal,
},
"weights_used": weights,
}
def compute_microstructure_pressure_from_orderbook(orderbook_output1: dict[str, Any]) -> dict[str, Any]:
"""MICROSTRUCTURE_PRESSURE_FROM_ORDERBOOK_V1.
KIS Open API FHKST01010200(주식현재가 호가/예상체결) output1의 10단계 호가 잔량을
-1(매수우위/지지)~+1(매도우위/압력) 계량화. 실측 확인된 필드명(2026-06-21,
005930 라이브 호출): total_askp_rsqn, total_bidp_rsqn(10단계 합계 잔량).
점수는 전략 방향 결정에는 쓰지 않고 confluence가 성립한 이후의 '집행 타이밍'
보조로만 사용한다(spec/exit/qualitative_sell_strategy_v1.yaml:factor_families.
microstructure_pressure 참조).
"""
total_askp = orderbook_output1.get("total_askp_rsqn")
total_bidp = orderbook_output1.get("total_bidp_rsqn")
try:
total_askp = float(total_askp)
total_bidp = float(total_bidp)
except (TypeError, ValueError):
return {"microstructure_pressure": None, "status": "DATA_MISSING"}
denom = total_askp + total_bidp
if denom <= 0:
return {"microstructure_pressure": None, "status": "DATA_MISSING"}
pressure = max(-1.0, min(1.0, (total_askp - total_bidp) / denom))
return {
"microstructure_pressure": round(pressure, 4),
"status": "OK",
"total_askp_rsqn": total_askp,
"total_bidp_rsqn": total_bidp,
}
def _event_review_window(
today: date,
pressure_sign: int,
next_earnings_date: date | None,
next_macro_event_date: date | None,
macro_event_impact: str | None,
earnings_outlook: str,
) -> dict[str, Any]:
"""캘린더 기반 검토 구간 산출 — 임의 날짜 고정이 아니라 실제 이벤트 일정에서 역산."""
candidates: list[tuple[date, str]] = []
if next_earnings_date is not None:
if pressure_sign < 0 and earnings_outlook == "DETERIORATING":
# 실적 악화 전망 + 매도압력 → 실적발표 전 정리(서프라이즈 리스크 회피)
candidates.append((next_earnings_date - timedelta(days=EVENT_PRE_GUARD_DAYS), "PRE_EARNINGS_EXIT_BEFORE_SURPRISE_RISK"))
elif pressure_sign < 0 and earnings_outlook in {"IMPROVING", "STABLE"}:
# 단기 기술적 매도압력이지만 실적전망은 양호 → 발표 직전 매도는 가치훼손, 발표 이후로 연기
candidates.append((next_earnings_date + timedelta(days=EVENT_POST_GUARD_DAYS), "DEFER_TO_POST_EARNINGS_AVOID_PREMATURE_EXIT"))
elif pressure_sign > 0:
# 추가매수/보유 신호 — 발표 변동성 통과 후 확신 재평가
candidates.append((next_earnings_date + timedelta(days=EVENT_POST_GUARD_DAYS), "REASSESS_AFTER_EARNINGS_CONFIRM"))
if next_macro_event_date is not None and str(macro_event_impact or "").upper() in {"HIGH", "VERY_HIGH"}:
if pressure_sign < 0:
candidates.append((next_macro_event_date - timedelta(days=EVENT_PRE_GUARD_DAYS), "PRE_MACRO_EVENT_DERISK"))
else:
candidates.append((next_macro_event_date + timedelta(days=EVENT_POST_GUARD_DAYS), "POST_MACRO_EVENT_CONFIRM"))
if not candidates:
return {
"review_window_start": today.isoformat(),
"review_window_end": (today + timedelta(days=10)).isoformat(),
"window_basis": "NO_SCHEDULED_EVENT_DEFAULT_10D_REVIEW",
}
earliest = min(candidates, key=lambda item: item[0])
window_start = max(today, earliest[0] - timedelta(days=2))
window_end = earliest[0] + timedelta(days=2)
return {
"review_window_start": window_start.isoformat(),
"review_window_end": window_end.isoformat(),
"window_basis": earliest[1],
}
def compute_qualitative_sell_strategy(ctx: dict[str, Any]) -> dict[str, Any]:
"""QUALITATIVE_SELL_STRATEGY_V1.
매크로/실적/펀더멘털/공매도수급/호가미시구조/대내외(IPO·로테이션) 5
독립 팩터군의 합의(confluence)로만 행동을 생성한다. 현금부족 사유는
입력에서 의도적으로 배제(cash_shortfall_excluded=True) 가치보존이
유일한 목적 함수.
"""
today_raw = ctx.get("today")
today = today_raw if isinstance(today_raw, date) else date.today()
factor_values: dict[str, float | None] = {}
missing_factors: list[str] = []
for family in FACTOR_FAMILIES:
value = ctx.get(family)
if _finite(value):
factor_values[family] = max(-1.0, min(1.0, float(value)))
else:
factor_values[family] = None
missing_factors.append(family)
available = {k: v for k, v in factor_values.items() if v is not None}
if len(available) < CONFLUENCE_MIN:
return {
"action": "INSUFFICIENT_DATA_NO_ACTION",
"conviction": "NONE",
"available_factors": list(available.keys()),
"missing_factors": missing_factors,
"rationale": "5개 팩터군 중 confluence 판정에 필요한 최소 데이터가 부족 — 추정으로 행동 생성 금지",
"cash_shortfall_excluded": True,
"mechanical_sell_prohibited": True,
}
# 부호 규약: 모든 팩터군은 +1(매도압력 최대) ~ -1(보유/추가 지지 최대) 동일 스케일.
# short_interest_pressure도 동일 — ELEVATED_SHORT_PRESSURE(+) / SHORT_COVERING_SUPPORTIVE(-).
# confluence 합의 카운트는 국면 가중치와 무관하게 원시 방향성으로만 판정한다
# (가중치는 행동 '강도'에만 영향 — 합의 성립 여부 자체를 왜곡하지 않는다).
sell_agree = [k for k, v in available.items() if v >= 0.30]
hold_add_agree = [k for k, v in available.items() if v <= -0.30]
market_regime = classify_market_regime(ctx.get("rate_trend")) if "market_regime" not in ctx else str(ctx.get("market_regime") or "NEUTRAL").upper()
regime_weights = REGIME_WEIGHT_TABLE.get(market_regime, REGIME_FLAT_WEIGHTS)
weighted_sum = sum(available[k] * regime_weights.get(k, 1.0) for k in available)
weight_total = sum(regime_weights.get(k, 1.0) for k in available)
composite_score = weighted_sum / weight_total if weight_total else 0.0
earnings_outlook = str(ctx.get("earnings_outlook") or "STABLE").upper()
next_earnings_date = ctx.get("next_earnings_date") if isinstance(ctx.get("next_earnings_date"), date) else None
next_macro_event_date = ctx.get("next_macro_event_date") if isinstance(ctx.get("next_macro_event_date"), date) else None
macro_event_impact = ctx.get("macro_event_impact")
if len(sell_agree) >= CONFLUENCE_MIN:
conviction = "HIGH" if len(sell_agree) >= 4 else "MEDIUM"
action = "EXIT_REVIEW_FULL" if composite_score >= 0.6 else "TRIM_REVIEW_PARTIAL"
pressure_sign = -1
rationale = f"매도압력 합의({len(sell_agree)}/{len(available)} 팩터군 매도방향 합치): " + ", ".join(sell_agree)
elif len(hold_add_agree) >= CONFLUENCE_MIN:
conviction = "HIGH" if len(hold_add_agree) >= 4 else "MEDIUM"
action = "HOLD_ADD_CONVICTION"
pressure_sign = 1
rationale = f"보유/추가 근거 합의({len(hold_add_agree)}/{len(available)} 팩터군 지지방향 합치): " + ", ".join(hold_add_agree)
else:
conviction = "LOW"
action = "HOLD_NO_CONFLUENCE"
pressure_sign = 0
rationale = "팩터군 간 합의 미달 — 단일/소수 팩터의 임계값 돌파만으로는 매도 트리거 금지"
window = _event_review_window(
today=today,
pressure_sign=pressure_sign,
next_earnings_date=next_earnings_date,
next_macro_event_date=next_macro_event_date,
macro_event_impact=macro_event_impact,
earnings_outlook=earnings_outlook,
) if pressure_sign != 0 else None
return {
"action": action,
"conviction": conviction,
"market_regime": market_regime,
"composite_score": round(composite_score, 4),
"sell_agreeing_factors": sell_agree,
"hold_add_agreeing_factors": hold_add_agree,
"missing_factors": missing_factors,
"review_window": window,
"rationale": rationale,
"cash_shortfall_excluded": True,
"mechanical_sell_prohibited": True,
}
def compute_satellite_candidate_score(ctx: dict[str, Any]) -> dict[str, Any]:
"""SATELLITE_CANDIDATE_SCORE_V1.
미보유 유니버스 종목을 섹터 수출입 전망(sector_export_trend) + 펀더멘털
추세 + 국면적합도로 평가해 WATCH/BUY_CANDIDATE/AVOID를 산출한다. 보유종목
매도판단(compute_qualitative_sell_strategy) 동일한 부호 규약을 쓰지 않고
별도 -1(약세)~+1(강세) 매력도 스케일을 쓴다 매수후보 평가와 매도판단은
목적함수가 다르므로 동일 점수를 재사용하지 않는다.
"""
sector_export_trend = ctx.get("sector_export_trend") # %, 섹터 수출 YoY/MoM 추세
fundamental_trajectory = ctx.get("fundamental_trajectory") # -1(악화)~+1(개선), 매도엔진과 동일 정의역이나 부호 반대 해석 주의
relative_return_20d = ctx.get("relative_return_20d")
market_regime = str(ctx.get("market_regime") or classify_market_regime(ctx.get("rate_trend"))).upper()
missing = [name for name, value in (
("sector_export_trend", sector_export_trend),
("fundamental_trajectory", fundamental_trajectory),
) if not _finite(value)]
if missing:
return {
"satellite_action": "INSUFFICIENT_DATA_NO_ACTION",
"missing_inputs": missing,
"market_regime": market_regime,
}
export_signal = max(-1.0, min(1.0, float(sector_export_trend) / 10.0))
fundamental_signal = max(-1.0, min(1.0, -float(fundamental_trajectory))) # 매도엔진 부호(+)=악화 -> 매력도는 반전
relative_signal = max(-1.0, min(1.0, float(relative_return_20d) / 10.0)) if _finite(relative_return_20d) else 0.0
if market_regime == "PERFORMANCE_MARKET":
weights = {"export": 0.45, "fundamental": 0.40, "relative": 0.15}
elif market_regime == "TECHNICAL_MARKET":
weights = {"export": 0.20, "fundamental": 0.25, "relative": 0.55}
else:
weights = {"export": 0.34, "fundamental": 0.33, "relative": 0.33}
attractiveness = (
export_signal * weights["export"]
+ fundamental_signal * weights["fundamental"]
+ relative_signal * weights["relative"]
)
attractiveness = max(-1.0, min(1.0, attractiveness))
if attractiveness >= 0.5:
satellite_action = "BUY_CANDIDATE"
elif attractiveness >= 0.2:
satellite_action = "WATCH"
elif attractiveness <= -0.4:
satellite_action = "AVOID"
else:
satellite_action = "NEUTRAL_NO_EDGE"
return {
"satellite_action": satellite_action,
"attractiveness_score": round(attractiveness, 4),
"market_regime": market_regime,
"components": {
"export_signal": round(export_signal, 4),
"fundamental_signal": round(fundamental_signal, 4),
"relative_signal": round(relative_signal, 4),
},
"weights_used": weights,
}
@@ -1,126 +0,0 @@
from __future__ import annotations
import ast
import json
import re
from dataclasses import dataclass
from pathlib import Path
from src.quant_engine.refactor_master_helpers import ROOT, collect_gas_files
FORBIDDEN_TOKENS = ("decision", "sizing", "stop_loss", "take_profit", "risk_score")
ALLOWED_TOKENS = ("collect", "normalize", "export", "display")
_JS_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.S)
_JS_LINE_COMMENT_RE = re.compile(r"//.*?$", re.M)
_JS_STRING_RE = re.compile(
r"""(?x)
(?:
"(?:\\.|[^"\\])*"
| '(?:\\.|[^'\\])*'
| `(?:\\.|[^`\\])*`
)
"""
)
@dataclass
class FunctionRow:
file: str
name: str
line: int
allowed_responsibility: str
matched_tokens: list[str]
def classify(name: str, body: str, file_name: str) -> tuple[str, list[str]]:
cleaned = _JS_BLOCK_COMMENT_RE.sub(" ", body)
cleaned = _JS_LINE_COMMENT_RE.sub(" ", cleaned)
cleaned = _JS_STRING_RE.sub(" ", cleaned)
low = f"{name}\n{cleaned}".lower()
matched_forbidden = [
tok
for tok in FORBIDDEN_TOKENS
if re.search(rf"(?<![A-Za-z0-9_]){re.escape(tok)}(?![A-Za-z0-9_])", low)
]
matched_allowed = [
tok
for tok in ALLOWED_TOKENS
if re.search(rf"(?<![A-Za-z0-9_]){re.escape(tok)}(?![A-Za-z0-9_])", low)
]
if matched_forbidden:
return "forbidden", matched_forbidden
if matched_allowed or file_name == "gas_harness_rows.gs":
return "allowed", matched_allowed or ["harness_rows"]
return "helper", []
def function_bodies(path: Path) -> list[tuple[str, int, str]]:
text = path.read_text(encoding="utf-8", errors="ignore")
lines = text.splitlines()
header_indexes: list[tuple[str, int]] = []
header_re = re.compile(r"^(?:function\s+([A-Za-z0-9_]+)|(?:var|let|const)\s+([A-Za-z0-9_]+)\s*=\s*function\b)")
for idx, line in enumerate(lines):
stripped = line.strip()
m = header_re.match(stripped)
if m:
name = (m.group(1) or m.group(2) or "").strip()
header_indexes.append((name, idx))
results: list[tuple[str, int, str]] = []
for name, start_idx in header_indexes:
brace_depth = 0
end_idx = len(lines)
started = False
for idx in range(start_idx, len(lines)):
scan = lines[idx]
scan = _JS_BLOCK_COMMENT_RE.sub(" ", scan)
scan = _JS_LINE_COMMENT_RE.sub(" ", scan)
scan = _JS_STRING_RE.sub(" ", scan)
brace_depth += scan.count("{")
if scan.count("{"):
started = True
brace_depth -= scan.count("}")
if started and brace_depth <= 0:
end_idx = idx + 1
break
body = "\n".join(lines[start_idx:end_idx])
results.append((name, start_idx + 1, body))
return results
def build_audit_payload() -> dict:
rows: list[FunctionRow] = []
for path in collect_gas_files():
for name, line, body in function_bodies(path):
allowed_responsibility, matched_tokens = classify(name, body, path.name)
rows.append(
FunctionRow(
file=str(path.relative_to(ROOT)),
name=name,
line=line,
allowed_responsibility=allowed_responsibility,
matched_tokens=matched_tokens,
)
)
inventory_coverage_pct = 100.0 if rows else 0.0
forbidden_rows = [row for row in rows if row.allowed_responsibility == "forbidden"]
return {
"formula_id": "GAS_BUSINESS_LOGIC_AUDIT_V1",
"function_inventory_coverage_pct": inventory_coverage_pct,
"function_count": len(rows),
"forbidden_function_count": len(forbidden_rows),
"approved_exceptions": [
"runtime_report_rendering",
"data_collection_helpers",
],
"rows": [row.__dict__ for row in rows],
"gate": "PASS" if inventory_coverage_pct >= 100.0 else "FAIL",
}
def write_audit(out_path: Path) -> dict:
result = build_audit_payload()
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
return result
-4
View File
@@ -1,4 +0,0 @@
{
"status": "passed",
"failedTests": []
}
-1
View File
@@ -1 +0,0 @@
"""Auto-generated package."""
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ABSOLUTE_RISK_STOP_V1."""
def test_absolute_risk_stop_v1_golden_stub_exists() -> None:
assert 'ABSOLUTE_RISK_STOP_V1'
def test_absolute_risk_stop_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ALGORITHM_GUIDANCE_PROOF_V1."""
def test_algorithm_guidance_proof_v1_golden_stub_exists() -> None:
assert 'ALGORITHM_GUIDANCE_PROOF_V1'
def test_algorithm_guidance_proof_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ALPHA_EVALUATION_WINDOW_V1."""
def test_alpha_evaluation_window_v1_golden_stub_exists() -> None:
assert 'ALPHA_EVALUATION_WINDOW_V1'
def test_alpha_evaluation_window_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ALPHA_FEEDBACK_LOOP_V1."""
def test_alpha_feedback_loop_v1_golden_stub_exists() -> None:
assert 'ALPHA_FEEDBACK_LOOP_V1'
def test_alpha_feedback_loop_v1_declares_outputs() -> None:
outputs = [{'field': 'alpha_feedback_json', 'subfields': ['eligible_t20_fail_rate', 'eligible_t60_fail_rate', 'recommended_filter_adjustments', 'cases_analyzed']}]
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ANTI_CHASE_V1."""
def test_anti_chase_v1_golden_stub_exists() -> None:
assert 'ANTI_CHASE_V1'
def test_anti_chase_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ANTI_CHASING_VELOCITY_V1."""
def test_anti_chasing_velocity_v1_golden_stub_exists() -> None:
assert 'ANTI_CHASING_VELOCITY_V1'
def test_anti_chasing_velocity_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ANTI_LATE_ENTRY_GATE_V2."""
def test_anti_late_entry_gate_v2_golden_stub_exists() -> None:
assert 'ANTI_LATE_ENTRY_GATE_V2'
def test_anti_late_entry_gate_v2_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ANTI_WHIPSAW_GATE_V1."""
def test_anti_whipsaw_gate_v1_golden_stub_exists() -> None:
assert 'ANTI_WHIPSAW_GATE_V1'
def test_anti_whipsaw_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ARTIFACT_FRESHNESS_GATE_V1."""
def test_artifact_freshness_gate_v1_golden_stub_exists() -> None:
assert 'ARTIFACT_FRESHNESS_GATE_V1'
def test_artifact_freshness_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for AUDIT_REPLAY_SNAPSHOT_V1."""
def test_audit_replay_snapshot_v1_golden_stub_exists() -> None:
assert 'AUDIT_REPLAY_SNAPSHOT_V1'
def test_audit_replay_snapshot_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for BENCHMARK_RELATIVE_TIMESERIES_V1."""
def test_benchmark_relative_timeseries_v1_golden_stub_exists() -> None:
assert 'BENCHMARK_RELATIVE_TIMESERIES_V1'
def test_benchmark_relative_timeseries_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for BLANK_CELL_AUDIT_V1."""
def test_blank_cell_audit_v1_golden_stub_exists() -> None:
assert 'BLANK_CELL_AUDIT_V1'
def test_blank_cell_audit_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for BREAKEVEN_RATCHET_V1."""
def test_breakeven_ratchet_v1_golden_stub_exists() -> None:
assert 'BREAKEVEN_RATCHET_V1'
def test_breakeven_ratchet_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for BREAKOUT_FAILURE_STOP_V1."""
def test_breakout_failure_stop_v1_golden_stub_exists() -> None:
assert 'BREAKOUT_FAILURE_STOP_V1'
def test_breakout_failure_stop_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for BREAKOUT_QUALITY_GATE_V2."""
def test_breakout_quality_gate_v2_golden_stub_exists() -> None:
assert 'BREAKOUT_QUALITY_GATE_V2'
def test_breakout_quality_gate_v2_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CANONICAL_ARTIFACT_RESOLVER_V1."""
def test_canonical_artifact_resolver_v1_golden_stub_exists() -> None:
assert 'CANONICAL_ARTIFACT_RESOLVER_V1'
def test_canonical_artifact_resolver_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CANONICAL_METRICS_V1."""
def test_canonical_metrics_v1_golden_stub_exists() -> None:
assert 'CANONICAL_METRICS_V1'
def test_canonical_metrics_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CAPITAL_STYLE_ALLOCATION_V1."""
def test_capital_style_allocation_v1_golden_stub_exists() -> None:
assert 'CAPITAL_STYLE_ALLOCATION_V1'
def test_capital_style_allocation_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_CREATION_PURPOSE_LOCK_V1."""
def test_cash_creation_purpose_lock_v1_golden_stub_exists() -> None:
assert 'CASH_CREATION_PURPOSE_LOCK_V1'
def test_cash_creation_purpose_lock_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_FLOOR_V1."""
def test_cash_floor_v1_golden_stub_exists() -> None:
assert 'CASH_FLOOR_V1'
def test_cash_floor_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RAISE_PARETO_EXECUTOR_V2."""
def test_cash_raise_pareto_executor_v2_golden_stub_exists() -> None:
assert 'CASH_RAISE_PARETO_EXECUTOR_V2'
def test_cash_raise_pareto_executor_v2_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RAISE_VALUE_OPTIMIZER_V3."""
def test_cash_raise_value_optimizer_v3_golden_stub_exists() -> None:
assert 'CASH_RAISE_VALUE_OPTIMIZER_V3'
def test_cash_raise_value_optimizer_v3_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RATIOS_V1."""
def test_cash_ratios_v1_golden_stub_exists() -> None:
assert 'CASH_RATIOS_V1'
def test_cash_ratios_v1_declares_outputs() -> None:
outputs = {'settlement_cash_ratio': 'settlement_cash / total_asset * 100', 'total_cash_ratio': 'settlement_cash / total_asset * 100', 'buy_power_cash': 'settlement_cash - reserved_order_amount', 'buy_power_ratio': '(settlement_cash - reserved_order_amount) / total_asset * 100', 'post_trade_total_cash_ratio': '(settlement_cash - planned_buy_amount + sell_cash_proceeds_d2) / total_asset * 100'}
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RECOVERY_OPTIMIZER_V1."""
def test_cash_recovery_optimizer_v1_golden_stub_exists() -> None:
assert 'CASH_RECOVERY_OPTIMIZER_V1'
def test_cash_recovery_optimizer_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RECOVERY_OPTIMIZER_V4."""
def test_cash_recovery_optimizer_v4_golden_stub_exists() -> None:
assert 'CASH_RECOVERY_OPTIMIZER_V4'
def test_cash_recovery_optimizer_v4_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASH_RECOVERY_V1."""
def test_cash_recovery_v1_golden_stub_exists() -> None:
assert 'CASH_RECOVERY_V1'
def test_cash_recovery_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASHFLOW_QUALITY_SIGNAL_V1."""
def test_cashflow_quality_signal_v1_golden_stub_exists() -> None:
assert 'CASHFLOW_QUALITY_SIGNAL_V1'
def test_cashflow_quality_signal_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CASHFLOW_STABILITY_GATE_V1."""
def test_cashflow_stability_gate_v1_golden_stub_exists() -> None:
assert 'CASHFLOW_STABILITY_GATE_V1'
def test_cashflow_stability_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CLA_REGIME_EXIT_CONDITION_V1."""
def test_cla_regime_exit_condition_v1_golden_stub_exists() -> None:
assert 'CLA_REGIME_EXIT_CONDITION_V1'
def test_cla_regime_exit_condition_v1_declares_outputs() -> None:
outputs = [{'field': 'cla_exit_status', 'unit': 'enum [CLA_ACTIVE,CLA_EXIT_WARNING,CLA_EXIT_CONFIRMED]'}, {'field': 'cla_exit_signals_triggered', 'unit': 'list'}, {'field': 'cla_exit_total_weight', 'unit': 'int'}]
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for COMPLETION_GAP_V1."""
def test_completion_gap_v1_golden_stub_exists() -> None:
assert 'COMPLETION_GAP_V1'
def test_completion_gap_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for COMPOSITE_VERDICT_V1."""
def test_composite_verdict_v1_golden_stub_exists() -> None:
assert 'COMPOSITE_VERDICT_V1'
def test_composite_verdict_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for COMPREHENSIVE_PROPOSAL_V1."""
def test_comprehensive_proposal_v1_golden_stub_exists() -> None:
assert 'COMPREHENSIVE_PROPOSAL_V1'
def test_comprehensive_proposal_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CONSECUTIVE_STREAK_V1."""
def test_consecutive_streak_v1_golden_stub_exists() -> None:
assert 'CONSECUTIVE_STREAK_V1'
def test_consecutive_streak_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CONTINUOUS_EVALUATION_DASHBOARD_V1."""
def test_continuous_evaluation_dashboard_v1_golden_stub_exists() -> None:
assert 'CONTINUOUS_EVALUATION_DASHBOARD_V1'
def test_continuous_evaluation_dashboard_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for CROSS_SECTION_CONSISTENCY_V1."""
def test_cross_section_consistency_v1_golden_stub_exists() -> None:
assert 'CROSS_SECTION_CONSISTENCY_V1'
def test_cross_section_consistency_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_INTEGRITY_100_LOCK_V1."""
def test_data_integrity_100_lock_v1_golden_stub_exists() -> None:
assert 'DATA_INTEGRITY_100_LOCK_V1'
def test_data_integrity_100_lock_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_INTEGRITY_100_LOCK_V2."""
def test_data_integrity_100_lock_v2_golden_stub_exists() -> None:
assert 'DATA_INTEGRITY_100_LOCK_V2'
def test_data_integrity_100_lock_v2_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_INTEGRITY_SCORE_V1."""
def test_data_integrity_score_v1_golden_stub_exists() -> None:
assert 'DATA_INTEGRITY_SCORE_V1'
def test_data_integrity_score_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_MATURITY_TRUTH_GATE_V1."""
def test_data_maturity_truth_gate_v1_golden_stub_exists() -> None:
assert 'DATA_MATURITY_TRUTH_GATE_V1'
def test_data_maturity_truth_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_MATURITY_TRUTH_GATE_VALIDATOR_V1."""
def test_data_maturity_truth_gate_validator_v1_golden_stub_exists() -> None:
assert 'DATA_MATURITY_TRUTH_GATE_VALIDATOR_V1'
def test_data_maturity_truth_gate_validator_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_QUALITY_GATE_V2_PY."""
def test_data_quality_gate_v2_py_golden_stub_exists() -> None:
assert 'DATA_QUALITY_GATE_V2_PY'
def test_data_quality_gate_v2_py_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DATA_QUALITY_GATE_V3."""
def test_data_quality_gate_v3_golden_stub_exists() -> None:
assert 'DATA_QUALITY_GATE_V3'
def test_data_quality_gate_v3_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DETERMINISTIC_ROUTING_ENGINE_V1."""
def test_deterministic_routing_engine_v1_golden_stub_exists() -> None:
assert 'DETERMINISTIC_ROUTING_ENGINE_V1'
def test_deterministic_routing_engine_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DISTRIBUTION_SELL_DETECTOR_V1."""
def test_distribution_sell_detector_v1_golden_stub_exists() -> None:
assert 'DISTRIBUTION_SELL_DETECTOR_V1'
def test_distribution_sell_detector_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DIVERGENCE_SCORE_V1."""
def test_divergence_score_v1_golden_stub_exists() -> None:
assert 'DIVERGENCE_SCORE_V1'
def test_divergence_score_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DRAWDOWN_GUARD_V1."""
def test_drawdown_guard_v1_golden_stub_exists() -> None:
assert 'DRAWDOWN_GUARD_V1'
def test_drawdown_guard_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for DYNAMIC_HEAT_GATE_V1."""
def test_dynamic_heat_gate_v1_golden_stub_exists() -> None:
assert 'DYNAMIC_HEAT_GATE_V1'
def test_dynamic_heat_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for EARNINGS_GROWTH_QUALITY_GATE_V1."""
def test_earnings_growth_quality_gate_v1_golden_stub_exists() -> None:
assert 'EARNINGS_GROWTH_QUALITY_GATE_V1'
def test_earnings_growth_quality_gate_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for EARNINGS_QUALITY_SIGNAL_V1."""
def test_earnings_quality_signal_v1_golden_stub_exists() -> None:
assert 'EARNINGS_QUALITY_SIGNAL_V1'
def test_earnings_quality_signal_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for ECP_RISK_SCALE_V1."""
def test_ecp_risk_scale_v1_golden_stub_exists() -> None:
assert 'ECP_RISK_SCALE_V1'
def test_ecp_risk_scale_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs
@@ -1,9 +0,0 @@
"""Auto-generated golden test stub for EJCE_DIVERGENCE_AUDIT_V1."""
def test_ejce_divergence_audit_v1_golden_stub_exists() -> None:
assert 'EJCE_DIVERGENCE_AUDIT_V1'
def test_ejce_divergence_audit_v1_declares_outputs() -> None:
outputs = []
assert isinstance(outputs, list)
assert outputs

Some files were not shown because too many files have changed in this diff Show More