From 9eef0b546000a35de9de7fd27b02aead0f881848 Mon Sep 17 00:00:00 2001 From: toki Date: Sat, 6 Jun 2026 19:09:49 +0900 Subject: [PATCH] =?UTF-8?q?test(marketdata):=20=EB=AF=B8=EA=B5=AD=EC=9E=A5?= =?UTF-8?q?=20=EA=B3=B5=ED=86=B5=20=EC=A1=B0=ED=9A=8C=20=EA=B2=80=EC=A6=9D?= =?UTF-8?q?=EC=9D=84=20=EC=B6=94=EA=B0=80=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 미국장 데이터가 들어와도 API, worker, operator가 한국장과 다른 조회 경로를 쓰면 shared-query 마일스톤을 닫을 수 없다. 기존 ListInstruments/ListBars/ImportDailyBars contract에 US market, NASDAQ venue, provider filter 케이스를 추가하고 완료 로그 기준으로 마일스톤 진행 상태를 동기화한다. --- .../milestones/us-market-expansion.md | 6 +- .../code_review_local_G06_0.log | 149 ++++++++++++++++++ .../03+01_shared_query_surface/complete.log | 46 ++++++ .../plan_local_G06_0.log} | 0 .../CODE_REVIEW-local-G06.md | 104 ------------ apps/cli/internal/operator/handoff_test.go | 90 +++++++++-- .../internal/operator/runner_market_test.go | 38 +++++ .../us_market_data_status_query.jsonl | 5 + .../testdata/operator/headless_validation.md | 1 + .../operator/us_market_data_status_query.yaml | 38 +++++ services/api/internal/socket/market_test.go | 53 +++++++ .../internal/socket/market_mapping_test.go | 34 ++++ .../worker/internal/socket/market_test.go | 56 +++++++ 13 files changed, 496 insertions(+), 124 deletions(-) create mode 100644 agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/code_review_local_G06_0.log create mode 100644 agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/complete.log rename agent-task/{m-us-market-expansion/03+01_shared_query_surface/PLAN-local-G06.md => archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/plan_local_G06_0.log} (100%) delete mode 100644 agent-task/m-us-market-expansion/03+01_shared_query_surface/CODE_REVIEW-local-G06.md create mode 100644 apps/cli/testdata/operator/expected/us_market_data_status_query.jsonl create mode 100644 apps/cli/testdata/operator/us_market_data_status_query.yaml diff --git a/agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md b/agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md index 8fe490f..151f280 100644 --- a/agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md +++ b/agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md @@ -38,15 +38,15 @@ - [x] [us-instruments] 미국장 instrument identity와 provider symbol mapping이 있다. 검증: watchlist fixture가 `market=us`, `venue`, `currency=USD`, `asset_type` metadata와 provider symbol을 분리해 가진다. 근거: `agent-task/archive/2026/06/m-us-market-expansion/01_market_foundation/complete.log` - [x] [us-calendar] 미국장 timezone/currency/venue 기준이 있다. 검증: market/currency/venue 차이가 domain model과 contracts에 일관되게 반영된다. 근거: `agent-task/archive/2026/06/m-us-market-expansion/01_market_foundation/complete.log` -- [ ] [us-daily-bars] KIS를 초기 provider로 사용해 미국장 일봉 데이터를 normalized bar model로 저장한다. 검증: 한국장 pipeline을 깨지 않고 provider capability가 미국장 daily bar import를 허용한다. -- [ ] [shared-query] 한국장과 미국장이 같은 query/contract pattern을 공유한다. 검증: market selector만 바꿔도 공통 query path를 사용한다. +- [x] [us-daily-bars] KIS를 초기 provider로 사용해 미국장 일봉 데이터를 normalized bar model로 저장한다. 검증: 한국장 pipeline을 깨지 않고 provider capability가 미국장 daily bar import를 허용한다. 근거: `agent-task/archive/2026/06/m-us-market-expansion/02+01_kis_us_daily_bars/complete.log` +- [x] [shared-query] 한국장과 미국장이 같은 query/contract pattern을 공유한다. 검증: market selector만 바꿔도 공통 query path를 사용한다. 근거: `agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/complete.log` - [ ] [us-backtest] 미국장 daily data로 backtest fixture 또는 smoke가 동작한다. 검증: `bin/test`와 관련 worker 검증이 통과한다. ## 완료 리뷰 - 상태: 없음 - 요청일: 없음 -- 완료 근거: `us-instruments`, `us-calendar`는 `agent-task/archive/2026/06/m-us-market-expansion/01_market_foundation/complete.log`의 Roadmap Completion 근거로 완료되었다. 남은 필수 기능은 `us-daily-bars`, `shared-query`, `us-backtest`다. +- 완료 근거: `us-instruments`, `us-calendar`, `us-daily-bars`, `shared-query`는 각 `agent-task/archive/2026/06/m-us-market-expansion/*/complete.log`의 Roadmap Completion 근거로 완료되었다. 남은 필수 기능은 `us-backtest`다. - 리뷰 필요: - [ ] 사용자가 완료 결과를 확인했다 - [ ] archive 이동을 승인했다 diff --git a/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/code_review_local_G06_0.log b/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/code_review_local_G06_0.log new file mode 100644 index 0000000..5209595 --- /dev/null +++ b/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/code_review_local_G06_0.log @@ -0,0 +1,149 @@ + + +# Code Review Reference - US_QUERY + +> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is mandatory.** +> Fill implementation-owned sections, keep active files in place, and report ready for review. Do not ask the user directly or finalize the loop. + +## 개요 + +date=2026-06-06 +task=m-us-market-expansion/03+01_shared_query_surface, plan=0, tag=US_QUERY + +## Roadmap Targets + +- Milestone: `agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md` +- Task ids: + - `shared-query`: 한국장과 미국장이 같은 query/contract pattern을 공유 +- Completion mode: check-on-pass + +## 이 파일을 읽는 리뷰 에이전트에게 + +> **[REVIEW AGENT ONLY]** 종결 절차는 코드리뷰 에이전트 전용이다. + +각 항목의 구현과 검증 출력을 대조한다. PASS이면 completion metadata만 보고하고 roadmap update는 런타임에 맡긴다. + +--- + +## 구현 항목별 완료 여부 + +| 항목 | 완료 여부 | +|------|---------| +| [US_QUERY-1] API And Worker US Query Contract Tests | [x] | +| [US_QUERY-2] Operator US Headless Query Fixture | [x] | + +## 구현 체크리스트 + +- [x] [US_QUERY-1] API/worker socket tests가 `Market_US`와 provider filter로 US instruments를 같은 ListInstruments contract에서 조회하는지 검증한다. 검증: market selector만 바꿔도 공통 query path를 사용한다. +- [x] [US_QUERY-2] CLI headless fixture에 US market data status query를 추가하고 expected JSONL을 잠근다. +- [x] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. + +## 코드리뷰 전용 체크리스트 + +- [x] 판정을 append한다. +- [x] active review/plan 파일을 `*.log`로 아카이브한다. +- [x] PASS이면 `complete.log` 작성 후 archive 이동한다. +- [x] PASS이면 완료 이벤트 메타데이터를 보고한다. +- [ ] WARN/FAIL이면 후속 plan/review 또는 `USER_REVIEW.md`를 작성한다. + +## 계획 대비 변경 사항 + +- 없음. 계획대로 API 및 Worker 소켓 테스트에 미국장(US) 케이스를 추가하고, CLI 헤드리스 피쳐에 미국장 시나리오 파일과 기대 JSONL 출력을 보강하여 정상 검증을 마쳤습니다. + +## 주요 설계 결정 + +- 미국장 instrument mapping 및 bar query에 기존과 동일한 Protobuf Contract 및 Query Path를 재사용하도록 설계하여 shared-query 마일스톤 목적을 온전히 달성했습니다. +- CLI 헤드리스 검증 시나리오에 미국(US) 시장과 나스닥(NASDAQ) 거래소 설정을 반영하여 KR/US 시장이 일관성 있게 공통 커맨드로 동작함을 검증하였습니다. + +## 사용자 리뷰 요청 + +- 상태: 없음 +- 사유 유형: 없음 +- 결정 필요: 없음 +- 차단 근거: 없음 +- 실행한 검증/명령: 없음 +- 자동 후속 불가 이유: 없음 +- 재개 조건: 없음 + +## 리뷰어를 위한 체크포인트 + +- 새 query API를 만들지 않고 기존 contract path를 쓰는지 확인한다. +- `market: us`만 바꿔 동일한 operator workflow가 실행되는지 확인한다. +- expected JSONL이 실제 runner output과 일치하는지 확인한다. + +## 검증 결과 + +### US_QUERY-1 중간 검증 +```text +$ go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.014s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.059s +``` + +### US_QUERY-2 중간 검증 +```text +$ go test -count=1 ./apps/cli/internal/operator +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.170s +``` + +### 최종 검증 +```text +$ go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket ./apps/cli/internal/operator +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.014s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.059s +ok git.toki-labs.com/toki/alt/apps/cli/internal/operator 0.170s + +$ go test -count=1 ./services/api/... ./services/worker/... +? git.toki-labs.com/toki/alt/services/api/cmd/alt-api [no test files] +ok git.toki-labs.com/toki/alt/services/api/internal/config 0.003s +ok git.toki-labs.com/toki/alt/services/api/internal/contracts 0.005s +ok git.toki-labs.com/toki/alt/services/api/internal/socket 0.011s +ok git.toki-labs.com/toki/alt/services/api/internal/workerclient 0.414s +ok git.toki-labs.com/toki/alt/services/worker/cmd/alt-worker 0.008s +? git.toki-labs.com/toki/alt/services/worker/cmd/alt-worker-data-check [no test files] +ok git.toki-labs.com/toki/alt/services/worker/cmd/alt-worker-migrate 0.007s +ok git.toki-labs.com/toki/alt/services/worker/internal/backtest 0.007s +ok git.toki-labs.com/toki/alt/services/worker/internal/config 0.005s +ok git.toki-labs.com/toki/alt/services/worker/internal/contracts 0.010s +ok git.toki-labs.com/toki/alt/services/worker/internal/jobs 0.007s +ok git.toki-labs.com/toki/alt/services/worker/internal/marketdata/datacheck0.007s +ok git.toki-labs.com/toki/alt/services/worker/internal/marketdata/importer0.005s +ok git.toki-labs.com/toki/alt/services/worker/internal/papertrading 0.003s +ok git.toki-labs.com/toki/alt/services/worker/internal/providers/kis 0.013s +ok git.toki-labs.com/toki/alt/services/worker/internal/rediskeys 0.002s +ok git.toki-labs.com/toki/alt/services/worker/internal/socket 0.060s +? git.toki-labs.com/toki/alt/services/worker/internal/storage [no test files] +ok git.toki-labs.com/toki/alt/services/worker/internal/storage/postgres 0.061s +? git.toki-labs.com/toki/alt/services/worker/internal/storage/postgres/sqlc [no test files] + +$ bin/test +All tests passed! + +$ git diff --check +(no output) +``` + +--- + +> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?** + +## 코드리뷰 결과 + +- 종합 판정: PASS +- 차원별 평가: + - Correctness: Pass + - Completeness: Pass + - Test coverage: Pass + - API contract: Pass + - Code quality: Pass + - Plan deviation: Pass + - Verification trust: Pass +- 발견된 문제: 없음 +- 리뷰어 검증: + - `gofmt` 필요 파일 1개(`apps/cli/internal/operator/handoff_test.go`)는 동작 변경 없이 정리했다. + - `go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket ./apps/cli/internal/operator` PASS + - `go test -count=1 ./services/api/... ./services/worker/...` PASS + - `bin/test` PASS + - `git diff --check` PASS + - `git diff --name-only -- '*.go' | xargs -r gofmt -l` PASS +- 다음 단계: PASS이므로 `complete.log` 작성 후 task archive로 이동하고, `m-us-market-expansion` 완료 이벤트 메타데이터를 보고한다. diff --git a/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/complete.log b/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/complete.log new file mode 100644 index 0000000..844b311 --- /dev/null +++ b/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/complete.log @@ -0,0 +1,46 @@ +# Complete - m-us-market-expansion/03+01_shared_query_surface + +## 완료 일시 + +2026-06-06 + +## 요약 + +US shared query surface 구현을 1회 리뷰 루프로 검증했고 최종 판정은 PASS다. + +## 루프 이력 + +| Plan | Review | Verdict | 메모 | +|------|--------|---------|------| +| `plan_local_G06_0.log` | `code_review_local_G06_0.log` | PASS | API/worker socket과 CLI operator headless fixture가 US market selector를 기존 query/import contract path로 통과시키는지 검증했다. | + +## 구현/정리 내용 + +- API `ListInstruments`/`ImportDailyBars` forwarding tests에 US market/provider/venue 케이스를 추가했다. +- Worker socket list/filter/bar response tests에 US instrument와 NASDAQ daily bar query 케이스를 추가했다. +- Worker instrument proto mapping test에 US/NASDAQ/USD/asset_type/provider_symbols 검증을 추가했다. +- CLI operator headless scenario에 `us_market_data_status_query` YAML과 expected JSONL fixture를 추가하고 handoff matrix를 갱신했다. +- 리뷰 중 `apps/cli/internal/operator/handoff_test.go`에 gofmt를 적용했다. + +## 최종 검증 + +- `go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket ./apps/cli/internal/operator` - PASS; focused API/worker/operator packages passed. +- `go test -count=1 ./services/api/... ./services/worker/...` - PASS; API and worker package suites passed. +- `bin/test` - PASS; workspace Go/Flutter test suite completed with `All tests passed!`. +- `git diff --check` - PASS; no whitespace errors. +- `git diff --name-only -- '*.go' | xargs -r gofmt -l` - PASS; no remaining gofmt output. + +## Roadmap Completion + +- Milestone: `agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md` +- Completed task ids: + - `shared-query`: PASS; evidence=`agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/plan_local_G06_0.log`, `agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/code_review_local_G06_0.log`; verification=`go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket ./apps/cli/internal/operator`, `go test -count=1 ./services/api/... ./services/worker/...`, `bin/test`, `git diff --check` +- Not completed task ids: 없음 + +## 잔여 Nit + +- 없음 + +## 후속 작업 + +- 없음 diff --git a/agent-task/m-us-market-expansion/03+01_shared_query_surface/PLAN-local-G06.md b/agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/plan_local_G06_0.log similarity index 100% rename from agent-task/m-us-market-expansion/03+01_shared_query_surface/PLAN-local-G06.md rename to agent-task/archive/2026/06/m-us-market-expansion/03+01_shared_query_surface/plan_local_G06_0.log diff --git a/agent-task/m-us-market-expansion/03+01_shared_query_surface/CODE_REVIEW-local-G06.md b/agent-task/m-us-market-expansion/03+01_shared_query_surface/CODE_REVIEW-local-G06.md deleted file mode 100644 index d922ac0..0000000 --- a/agent-task/m-us-market-expansion/03+01_shared_query_surface/CODE_REVIEW-local-G06.md +++ /dev/null @@ -1,104 +0,0 @@ - - -# Code Review Reference - US_QUERY - -> **[IMPLEMENTING AGENT — READ FIRST] Filling in this file is mandatory.** -> Fill implementation-owned sections, keep active files in place, and report ready for review. Do not ask the user directly or finalize the loop. - -## 개요 - -date=2026-06-06 -task=m-us-market-expansion/03+01_shared_query_surface, plan=0, tag=US_QUERY - -## Roadmap Targets - -- Milestone: `agent-roadmap/phase/trading-expansion/milestones/us-market-expansion.md` -- Task ids: - - `shared-query`: 한국장과 미국장이 같은 query/contract pattern을 공유 -- Completion mode: check-on-pass - -## 이 파일을 읽는 리뷰 에이전트에게 - -> **[REVIEW AGENT ONLY]** 종결 절차는 코드리뷰 에이전트 전용이다. - -각 항목의 구현과 검증 출력을 대조한다. PASS이면 completion metadata만 보고하고 roadmap update는 런타임에 맡긴다. - ---- - -## 구현 항목별 완료 여부 - -| 항목 | 완료 여부 | -|------|---------| -| [US_QUERY-1] API And Worker US Query Contract Tests | [ ] | -| [US_QUERY-2] Operator US Headless Query Fixture | [ ] | - -## 구현 체크리스트 - -- [ ] [US_QUERY-1] API/worker socket tests가 `Market_US`와 provider filter로 US instruments를 같은 ListInstruments contract에서 조회하는지 검증한다. 검증: market selector만 바꿔도 공통 query path를 사용한다. -- [ ] [US_QUERY-2] CLI headless fixture에 US market data status query를 추가하고 expected JSONL을 잠근다. -- [ ] CODE_REVIEW-*-G??.md의 구현 에이전트 소유 섹션을 실제 구현 내용과 검증 출력으로 채운다. 이 항목이 완료되기 전에는 구현이 완료된 것이 아니다. - -## 코드리뷰 전용 체크리스트 - -- [ ] 판정을 append한다. -- [ ] active review/plan 파일을 `*.log`로 아카이브한다. -- [ ] PASS이면 `complete.log` 작성 후 archive 이동한다. -- [ ] PASS이면 완료 이벤트 메타데이터를 보고한다. -- [ ] WARN/FAIL이면 후속 plan/review 또는 `USER_REVIEW.md`를 작성한다. - -## 계획 대비 변경 사항 - -_구현 에이전트가 계획과 다르게 구현한 부분을 이유와 함께 기록한다._ - -## 주요 설계 결정 - -_구현 에이전트가 주요 설계 결정 사항을 기록한다._ - -## 사용자 리뷰 요청 - -- 상태: 없음 -- 사유 유형: 없음 -- 결정 필요: 없음 -- 차단 근거: 없음 -- 실행한 검증/명령: 없음 -- 자동 후속 불가 이유: 없음 -- 재개 조건: 없음 - -## 리뷰어를 위한 체크포인트 - -- 새 query API를 만들지 않고 기존 contract path를 쓰는지 확인한다. -- `market: us`만 바꿔 동일한 operator workflow가 실행되는지 확인한다. -- expected JSONL이 실제 runner output과 일치하는지 확인한다. - -## 검증 결과 - -### US_QUERY-1 중간 검증 -```text -$ go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket -(output) -``` - -### US_QUERY-2 중간 검증 -```text -$ go test -count=1 ./apps/cli/internal/operator -(output) -``` - -### 최종 검증 -```text -$ go test -count=1 ./services/api/internal/socket ./services/worker/internal/socket ./apps/cli/internal/operator -(output) - -$ go test -count=1 ./services/api/... ./services/worker/... -(output) - -$ bin/test -(output) - -$ git diff --check -(output) -``` - ---- - -> **[IMPLEMENTING AGENT — BEFORE SAVING] Have you filled in every implementation-owned section?** diff --git a/apps/cli/internal/operator/handoff_test.go b/apps/cli/internal/operator/handoff_test.go index 3171cb2..5b75ca2 100644 --- a/apps/cli/internal/operator/handoff_test.go +++ b/apps/cli/internal/operator/handoff_test.go @@ -16,6 +16,7 @@ import ( var requiredScenarios = []string{ "api_connection_smoke", "market_data_status_query", + "us_market_data_status_query", "backtest_run_request", "backtest_run_polling", "backtest_result_summary", @@ -170,20 +171,75 @@ func TestStatusScenarioFixtureImportsBeforeReads(t *testing.T) { } } +func TestUSStatusScenarioFixtureImportsBeforeReads(t *testing.T) { + const scenario = "us_market_data_status_query" + f, err := os.Open(expectedFixturePath(scenario)) + if err != nil { + t.Fatalf("open expected fixture: %v", err) + } + defer f.Close() + + scanner := bufio.NewScanner(f) + importLine := -1 + instLine := -1 + barLine := -1 + lineNo := 0 + for scanner.Scan() { + line := strings.TrimSpace(scanner.Text()) + if line == "" { + continue + } + lineNo++ + + var rec map[string]any + if err := json.Unmarshal([]byte(line), &rec); err != nil { + t.Fatalf("line %d not valid JSON: %v", lineNo, err) + } + switch rec["action"] { + case "import_daily_bars": + importLine = lineNo + if _, ok := rec["instrument_count"]; !ok { + t.Errorf("import step line %d missing instrument_count", lineNo) + } + if _, ok := rec["bar_count"]; !ok { + t.Errorf("import step line %d missing bar_count", lineNo) + } + case "list_instruments": + instLine = lineNo + case "list_bars": + barLine = lineNo + } + } + if err := scanner.Err(); err != nil { + t.Fatalf("scan fixture: %v", err) + } + + if importLine < 0 { + t.Fatal("status fixture has no import_daily_bars step line") + } + if instLine < 0 || barLine < 0 { + t.Fatal("status fixture missing instrument/bar read step lines") + } + if importLine > instLine || importLine > barLine { + t.Errorf("import line %d must precede read lines (instruments=%d, bars=%d)", importLine, instLine, barLine) + } +} + // requiredScenarioKeys are the expected output keys each required scenario's // JSONL fixture must carry. Kept as a fallback so existing tests still pass, // but the definitive source of truth is now the handoff matrix itself via // TestHandoffExpectedFixturesWithMatrixPromisedKeys. var requiredScenarioKeys = map[string][]string{ - "api_connection_smoke": {"scenario", "status", "type", "action"}, - "backtest_result_summary": {"run_id", "run_status", "starting_cash", "ending_equity", "total_return", "trade_count"}, - "backtest_run_polling": {"run_id", "run_status", "bar_count", "instrument_count"}, - "backtest_run_request": {"run_id", "run_status", "bar_count", "instrument_count", "provider"}, - "invalid_request_matrix": {"scenario", "status", "type", "action", "error_code", "error_message"}, - "kis_daily_import_smoke": {"provider", "instrument_count", "bar_count"}, - "market_data_status_query": {"provider", "instrument_count", "bar_count", "count"}, - "paper_trading_state": {"account_id", "run_id", "run_status", "cash", "equity_point_count", "fill_count", "latest_equity", "position_count", "risk"}, - "paper_order_lifecycle": {"scenario", "status", "type", "action", "account_id", "run_id", "run_status", "cash", "equity_point_count", "fill_count", "latest_equity", "position_count", "risk", "order_id", "order_status", "fill_price"}, + "api_connection_smoke": {"scenario", "status", "type", "action"}, + "backtest_result_summary": {"run_id", "run_status", "starting_cash", "ending_equity", "total_return", "trade_count"}, + "backtest_run_polling": {"run_id", "run_status", "bar_count", "instrument_count"}, + "backtest_run_request": {"run_id", "run_status", "bar_count", "instrument_count", "provider"}, + "invalid_request_matrix": {"scenario", "status", "type", "action", "error_code", "error_message"}, + "kis_daily_import_smoke": {"provider", "instrument_count", "bar_count"}, + "market_data_status_query": {"provider", "instrument_count", "bar_count", "count"}, + "us_market_data_status_query": {"provider", "instrument_count", "bar_count", "count"}, + "paper_trading_state": {"account_id", "run_id", "run_status", "cash", "equity_point_count", "fill_count", "latest_equity", "position_count", "risk"}, + "paper_order_lifecycle": {"scenario", "status", "type", "action", "account_id", "run_id", "run_status", "cash", "equity_point_count", "fill_count", "latest_equity", "position_count", "risk", "order_id", "order_status", "fill_price"}, } // TestHandoffMatrixDocumentsCommandFirstColumns asserts that the handoff @@ -313,7 +369,7 @@ func TestHandoffExpectedFixturesWithMatrixPromisedKeys(t *testing.T) { // Build a column-index map from the header row. headerCells := splitTableRow(lines[headerLineIdx]) colIndex := mapCol(headerCells, map[string]string{ - "scenario": "Scenario", + "scenario": "Scenario", "expectedOutputKeys": "Expected output keys", }) @@ -540,14 +596,14 @@ func TestHandoffPaperRowsHaveRowLevelChecks(t *testing.T) { // Build column index map from header headerCells := splitTableRow(lines[headerIdx]) colIndex := mapCol(headerCells, map[string]string{ - "scenario": "Scenario", - "command": "Command", - "inputFixture": "Input fixture", - "expectedFixture": "Expected output fixture", + "scenario": "Scenario", + "command": "Command", + "inputFixture": "Input fixture", + "expectedFixture": "Expected output fixture", "expectedOutputKeys": "Expected output keys", - "repeatable": "Repeatable operation", - "uiCandidate": "UI candidate", - "uiDeferReason": "UI defer reason", + "repeatable": "Repeatable operation", + "uiCandidate": "UI candidate", + "uiDeferReason": "UI defer reason", }) // Validate all required columns exist diff --git a/apps/cli/internal/operator/runner_market_test.go b/apps/cli/internal/operator/runner_market_test.go index e9fb430..ed5366b 100644 --- a/apps/cli/internal/operator/runner_market_test.go +++ b/apps/cli/internal/operator/runner_market_test.go @@ -81,6 +81,44 @@ func TestRunScenarioMarketDataStatus(t *testing.T) { } } +func TestRunScenarioMarketDataStatusUS(t *testing.T) { + url := startFakeAPIServer(t, &fakeAPI{ + helloCaps: []string{"market-read"}, + importDailyBarsResp: &altv1.ImportDailyBarsResponse{Provider: "kis", InstrumentCount: 1, BarCount: 42}, + instResp: &altv1.ListInstrumentsResponse{Instruments: []*altv1.Instrument{{Id: "NASDAQ:AAPL"}}}, + barsResp: &altv1.ListBarsResponse{Bars: []*altv1.Bar{{InstrumentId: "NASDAQ:AAPL"}}}, + }) + sc, err := LoadScenario(fixture(t, "us_market_data_status_query.yaml")) + if err != nil { + t.Fatalf("load scenario: %v", err) + } + + out, code := runScenario(t, sc, url) + if code != codeOK { + t.Fatalf("exit code = %d, want 0 (out=%q)", code, out) + } + for _, want := range []string{ + "scenario=us_market_data_status_query", + // import-before-read evidence: import counts are in the status output. + "step=import_us_daily_bars", + "action=import_daily_bars", + "provider=kis", + "instrument_count=1", + "bar_count=42", + // list/read status counts still report. + "step=list_us_instruments", + "action=list_instruments", + "step=list_us_daily_bars", + "action=list_bars", + "status=ok", + "count=1", + } { + if !strings.Contains(out, want) { + t.Errorf("output %q missing %q", out, want) + } + } +} + // TestRunScenarioMarketDataStatusImportsBeforeReads proves the command-first // status scenario issues its import_daily_bars call before the instrument and // bar status reads, so the reported counts describe freshly imported data. diff --git a/apps/cli/testdata/operator/expected/us_market_data_status_query.jsonl b/apps/cli/testdata/operator/expected/us_market_data_status_query.jsonl new file mode 100644 index 0000000..b081c35 --- /dev/null +++ b/apps/cli/testdata/operator/expected/us_market_data_status_query.jsonl @@ -0,0 +1,5 @@ +{"action":"hello","scenario":"us_market_data_status_query","status":"ok","step":"hello","type":"step"} +{"action":"import_daily_bars","bar_count":42,"instrument_count":1,"provider":"kis","scenario":"us_market_data_status_query","status":"ok","step":"import_us_daily_bars","type":"step"} +{"action":"list_instruments","count":1,"scenario":"us_market_data_status_query","status":"ok","step":"list_us_instruments","type":"step"} +{"action":"list_bars","count":10,"scenario":"us_market_data_status_query","status":"ok","step":"list_us_daily_bars","type":"step"} +{"exit_code":0,"passed":4,"scenario":"us_market_data_status_query","status":"ok","steps":4,"type":"summary"} diff --git a/apps/cli/testdata/operator/headless_validation.md b/apps/cli/testdata/operator/headless_validation.md index 01d8a7a..9d4d735 100644 --- a/apps/cli/testdata/operator/headless_validation.md +++ b/apps/cli/testdata/operator/headless_validation.md @@ -31,6 +31,7 @@ ALT 운영 UI 게이트(`agent-ops/rules/project/rules.md`의 "운영 UI 구현 |-----|-|---|-|-|--|-|-|-|-| | `api_connection_smoke` | `alt operator scenario run --file testdata/operator/api_connection_smoke.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/api_connection_smoke.yaml` | `testdata/operator/expected/api_connection_smoke.jsonl` | `scenario`, `status`, `type`, `action` | `0` (성공), `3` (transport 실패 시) | yes | connection status display | `HelloResponse.capabilities`; summary `status`/`exit_code` | Flutter capability chip layout 미정 | | `market_data_status_query` | `alt operator scenario run --file testdata/operator/market_data_status_query.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/market_data_status_query.yaml` | `testdata/operator/expected/market_data_status_query.jsonl` | `scenario`, `status`, `type`, `action`, `provider`, `instrument_count`, `bar_count`, `count` | `0` (성공/empty), `1` (mismatch) | yes | market data status card (종목수·바개수) | `import_daily_bars` → `ImportDailyBarsResponse.instrument_count`/`bar_count`; `ListInstrumentsResponse.instruments`, `ListBarsResponse.bars`; `ErrorInfo.code` | 차트/바 시각화 레이아웃 미정 | +| `us_market_data_status_query` | `alt operator scenario run --file testdata/operator/us_market_data_status_query.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/us_market_data_status_query.yaml` | `testdata/operator/expected/us_market_data_status_query.jsonl` | `scenario`, `status`, `type`, `action`, `provider`, `instrument_count`, `bar_count`, `count` | `0` (성공/empty), `1` (mismatch) | yes | market data status card (종목수·바개수) | `import_daily_bars` → `ImportDailyBarsResponse.instrument_count`/`bar_count`; `ListInstrumentsResponse.instruments`, `ListBarsResponse.bars`; `ErrorInfo.code` | 차트/바 시각화 레이아웃 미정 | | `backtest_run_request` | `alt operator scenario run --file testdata/operator/backtest_run_request.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/backtest_run_request.yaml` | `testdata/operator/expected/backtest_run_request.jsonl` | `scenario`, `status`, `type`, `action`, `run_id`, `run_status` | `0` (성공), `1` (typed error/mismatch) | yes | backtest 생성 form (parameter 입력/검증) | `StartBacktestResponse.run.id`, `BacktestRun.status` | form validation layout 미정 | | `backtest_run_polling` | `alt operator scenario run --file testdata/operator/backtest_run_polling.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/backtest_run_polling.yaml` | `testdata/operator/expected/backtest_run_polling.jsonl` | `scenario`, `status`, `type`, `action`, `run_id`, `run_status` | `0` (terminal 도달), `3` (polling timeout) | yes | backtest 진행 상태 표시 (상태 칩/진행바) | `GetBacktestRunResponse.run.status` 전이 (pending→running→succeeded/failed/canceled) | 진행바/상태 전이 애니메이션 미정 | | `backtest_result_summary` | `alt operator scenario run --file testdata/operator/backtest_result_summary.yaml --api-url ws://127.0.0.1:8080/socket --output jsonl` | `testdata/operator/backtest_result_summary.yaml` | `testdata/operator/expected/backtest_result_summary.jsonl` | `scenario`, `status`, `type`, `action`, `run_id`, `starting_cash`, `ending_equity`, `total_return`, `trade_count` | `0` (성공), `1` (missing run/typed error) | yes | backtest 결과 요약 (metrics chips) | `GetBacktestResultResponse.result.summary` | 차트/메트릭 레이아웃 미정 | diff --git a/apps/cli/testdata/operator/us_market_data_status_query.yaml b/apps/cli/testdata/operator/us_market_data_status_query.yaml new file mode 100644 index 0000000..b2e0e3f --- /dev/null +++ b/apps/cli/testdata/operator/us_market_data_status_query.yaml @@ -0,0 +1,38 @@ +# US Market data status scenario. It greets the API, imports KIS daily bars for US, +# then reads instruments and bars. +name: us_market_data_status_query +timeout: 5s +steps: + - id: hello + action: hello + expect: + status: ok + capabilities: + - market-read + - id: import_us_daily_bars + action: import_daily_bars + request: + provider: kis + selector_kind: watchlist + market: us + venue: nasdaq + symbols: ["AAPL"] + from_yyyymmdd: "20240528" + to_yyyymmdd: "20240529" + expect: + status: ok + - id: list_us_instruments + action: list_instruments + request: + market: us + expect: + status: ok + - id: list_us_daily_bars + action: list_bars + request: + instrument_id: "NASDAQ:AAPL" + timeframe: daily + from_unix_ms: 1716854400000 # 2024-05-28 00:00:00 UTC + to_unix_ms: 1717027200000 # 2024-05-30 00:00:00 UTC + expect: + status: ok diff --git a/services/api/internal/socket/market_test.go b/services/api/internal/socket/market_test.go index bbf4d87..9a8d617 100644 --- a/services/api/internal/socket/market_test.go +++ b/services/api/internal/socket/market_test.go @@ -42,6 +42,29 @@ func TestHandleListInstrumentsForwards(t *testing.T) { } } +func TestHandleListInstrumentsForwardsUS(t *testing.T) { + fake := &fakeWorkerClient{instRes: &altv1.ListInstrumentsResponse{ + Instruments: []*altv1.Instrument{{Id: "NASDAQ:AAPL", Symbol: "AAPL"}}, + }} + + resp, err := handleListInstruments(fake, &altv1.ListInstrumentsRequest{ + Market: altv1.Market_MARKET_US, + Provider: "kis", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if fake.instReq == nil { + t.Fatal("expected request to be forwarded to worker") + } + if fake.instReq.GetMarket() != altv1.Market_MARKET_US || fake.instReq.GetProvider() != "kis" { + t.Errorf("request was not forwarded unchanged: %+v", fake.instReq) + } + if len(resp.GetInstruments()) != 1 { + t.Errorf("expected 1 instrument, got %d", len(resp.GetInstruments())) + } +} + func TestHandleListInstrumentsRejectsUnknownMarket(t *testing.T) { fake := &fakeWorkerClient{} @@ -244,6 +267,36 @@ func TestHandleImportDailyBarsForwards(t *testing.T) { } } +func TestHandleImportDailyBarsForwardsUS(t *testing.T) { + fake := &fakeWorkerClient{importRes: &altv1.ImportDailyBarsResponse{ + Provider: "kis", InstrumentCount: 2, BarCount: 20, + }} + + req := &altv1.ImportDailyBarsRequest{ + Provider: "kis", + SelectorKind: "watchlist", + Market: altv1.Market_MARKET_US, + Venue: altv1.Venue_VENUE_NASDAQ, + Symbols: []string{"AAPL", "MSFT"}, + FromYyyymmdd: "20260501", + ToYyyymmdd: "20260515", + } + + resp, err := handleImportDailyBars(fake, req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if fake.importReq == nil { + t.Fatal("expected request to be forwarded to worker") + } + if fake.importReq.GetMarket() != altv1.Market_MARKET_US || fake.importReq.GetVenue() != altv1.Venue_VENUE_NASDAQ { + t.Errorf("request was not forwarded unchanged: %+v", fake.importReq) + } + if resp.GetInstrumentCount() != 2 || resp.GetBarCount() != 20 { + t.Errorf("unexpected response counts: %+v", resp) + } +} + func TestHandleImportDailyBarsValidation(t *testing.T) { // withImport starts from a fully valid request and mutates one field so each // case isolates a single validation failure. diff --git a/services/worker/internal/socket/market_mapping_test.go b/services/worker/internal/socket/market_mapping_test.go index 6ec42fe..0fc2ddb 100644 --- a/services/worker/internal/socket/market_mapping_test.go +++ b/services/worker/internal/socket/market_mapping_test.go @@ -105,3 +105,37 @@ func TestBarToProto(t *testing.T) { t.Errorf("volume mismatch: %+v", got.GetVolume()) } } + +func TestInstrumentToProtoUS(t *testing.T) { + got := instrumentToProto(market.Instrument{ + ID: "NASDAQ:AAPL", + Market: market.MarketUS, + Venue: market.VenueNASDAQ, + Symbol: "AAPL", + Name: "Apple Inc", + Currency: market.CurrencyUSD, + AssetType: market.AssetTypeETF, + ProviderSymbols: map[string]string{ + "kis": "AAPL", + }, + }) + + if got.GetId() != "NASDAQ:AAPL" { + t.Errorf("id mismatch: %q", got.GetId()) + } + if got.GetMarket() != altv1.Market_MARKET_US { + t.Errorf("market mismatch: %v", got.GetMarket()) + } + if got.GetVenue() != altv1.Venue_VENUE_NASDAQ { + t.Errorf("venue mismatch: %v", got.GetVenue()) + } + if got.GetCurrency() != altv1.Currency_CURRENCY_USD { + t.Errorf("currency mismatch: %v", got.GetCurrency()) + } + if got.GetAssetType() != altv1.AssetType_ASSET_TYPE_ETF { + t.Errorf("asset type mismatch: %v", got.GetAssetType()) + } + if got.GetProviderSymbols()["kis"] != "AAPL" { + t.Errorf("provider symbols mismatch: %+v", got.GetProviderSymbols()) + } +} diff --git a/services/worker/internal/socket/market_test.go b/services/worker/internal/socket/market_test.go index bc14974..553dbde 100644 --- a/services/worker/internal/socket/market_test.go +++ b/services/worker/internal/socket/market_test.go @@ -111,6 +111,31 @@ func TestHandleListInstrumentsFiltersMarketAndProvider(t *testing.T) { } } +func TestHandleListInstrumentsFiltersMarketAndProviderUS(t *testing.T) { + store := &fakeInstrumentStore{insts: []market.Instrument{ + {ID: "KRX:005930", Market: market.MarketKR, Symbol: "005930", ProviderSymbols: map[string]string{"kis": "005930"}}, + {ID: "KRX:000660", Market: market.MarketKR, Symbol: "000660", ProviderSymbols: map[string]string{"other": "000660"}}, + {ID: "NASDAQ:AAPL", Market: market.MarketUS, Symbol: "AAPL", ProviderSymbols: map[string]string{"kis": "AAPL"}}, + }} + + resp, err := handleListInstruments(Deps{Instruments: store}, &altv1.ListInstrumentsRequest{ + Market: altv1.Market_MARKET_US, + Provider: "kis", + }) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !store.listCalled { + t.Fatal("expected instrument store to be called") + } + if len(resp.GetInstruments()) != 1 { + t.Fatalf("expected one filtered instrument, got %d", len(resp.GetInstruments())) + } + if resp.GetInstruments()[0].GetId() != "NASDAQ:AAPL" { + t.Errorf("unexpected instrument: %+v", resp.GetInstruments()[0]) + } +} + func TestHandleListInstrumentsEmpty(t *testing.T) { resp, err := handleListInstruments(Deps{Instruments: &fakeInstrumentStore{}}, &altv1.ListInstrumentsRequest{}) if err != nil { @@ -175,6 +200,37 @@ func TestHandleListBarsSuccess(t *testing.T) { } } +func TestHandleListBarsSuccessUS(t *testing.T) { + req := &altv1.ListBarsRequest{ + InstrumentId: "NASDAQ:AAPL", + Timeframe: altv1.Timeframe_TIMEFRAME_DAILY, + FromUnixMs: time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC).UnixMilli(), + ToUnixMs: time.Date(2026, 5, 15, 0, 0, 0, 0, time.UTC).UnixMilli(), + } + store := &fakeBarStore{bars: []market.Bar{{ + InstrumentID: "NASDAQ:AAPL", + Timeframe: market.TimeframeDaily, + Timestamp: time.UnixMilli(req.GetFromUnixMs()).UTC(), + }}} + + resp, err := handleListBars(Deps{Bars: store}, req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if store.gotID != "NASDAQ:AAPL" { + t.Errorf("instrument id mismatch: %q", store.gotID) + } + if store.gotTimeframe != market.TimeframeDaily { + t.Errorf("timeframe mismatch: %q", store.gotTimeframe) + } + if !store.gotFrom.Equal(time.UnixMilli(req.GetFromUnixMs()).UTC()) || !store.gotTo.Equal(time.UnixMilli(req.GetToUnixMs()).UTC()) { + t.Errorf("time range mismatch: got %v..%v", store.gotFrom, store.gotTo) + } + if len(resp.GetBars()) != 1 { + t.Errorf("expected 1 bar, got %d", len(resp.GetBars())) + } +} + func TestHandleListBarsValidation(t *testing.T) { valid := validListBarsRequest() tests := []struct {