Commit Graph
236 Commits
Author SHA1 Message Date
genichin 3a6adc98c9 Merge pull request #15 from fourblocks2020/feat/req-041-wac-buy-fee-capitalize
fix(REQ-041): WAC cost basis에 매수 수수료 편입 (dcy-035 연동)
2026-06-26 20:52:12 +09:00
genichinandClaude Sonnet 4.6 d224d716f6 fix(holdings): /holdings/cost-basis WAC row에 fee_amount 편입 (QC보정)
get_holdings_cost_basis 핸들러의 row dict에 fee_amount 누락으로
/holdings/cost-basis의 cost_basis_per_unit이 매수 수수료 미편입값을
반환하던 버그 수정. /pnl/realized 핸들러와 동일하게 e.fee_amount 포함.
테스트: buy fee>0 케이스(1000.5 단언) + fee=0 회귀 케이스 추가.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-26 20:34:03 +09:00
genichinandClaude Sonnet 4.6 73414817e0 fix(pnl): 매수 수수료를 WAC cost basis에 편입 (REQ-041 CHG-20260626-01)
WAC 공식에 buy row의 fee_amount를 분자에 포함해 실현 PnL이 당일 net과 정확히 일치하도록 수정.
calculate_realized_pnl + calculate_current_wac 양 함수 동일 적용.
신규 단위 테스트 9개(TestBuyFeeInCostBasis 5 + TestCurrentWacBuyFeeInCostBasis 4) 추가.
change-req: REQ-041 AC-9/AC-10 추가, REQ-040/REQ-043 Notes 갱신, index 갱신.
전체 456 passed / 0 failed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-26 20:34:03 +09:00
genichinandClaude Sonnet 4.6 bd8ff1bf45 docs(gov): BAT-018/REQ-043 거버넌스 마감 — Implemented + release-candidate 전환
- REQ-043: Approved → Implemented (BAT-018 PR #14 squash d93c0bc, 팀장 QC PASS, origin/main 머지)
- BAT-018: in-progress → release-candidate (배포 별도 — 미배포)
- dcy-008 생성된 REQ 참조에 Implemented 반영
- srs/index.md Requirement Register 및 Recent Change Log Summary 갱신 (최신 5건)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-26 15:52:44 +09:00
genichinandClaude Opus 4.8 d93c0bcaf5 feat(holdings): REQ-043 현재 보유 평단(WAC) read — GET /v1/portfolios/{id}/holdings/cost-basis (BAT-018, PR #14)
dcy-008(confirmed)/REQ-043(Approved)/BAT-018. trex-core dcy-034 FR-7 cold-start seed 의존. AC 11/11, QC PASS. worktree+PR 워크플로 첫 파일럿.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-26 00:07:43 +09:00
genichinandClaude Opus 4.8 8f9865bd8a docs(rel-002): capture M1 release feedback — feedback-captured, smoke 8/9 PASS (1 non-blocking)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-22 14:34:55 +09:00
genichinandClaude Opus 4.8 b1c34068e5 docs: batch 상태 released 동기화(REL-001/002) + README 현행화(거래내역/실현PnL API)
batch drift 정합 — REL-001(BAT-001~016)·REL-002(BAT-017) released에 맞춰
batches/index 및 개별 index 상태를 release-candidate→released 동기화(17건).
README: bootstrap 문구 제거, dcy-007 엔드포인트(GET /trades·/pnl/realized) 추가,
planned-next 현행화. 코드 무변경.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-22 09:51:13 +09:00
genichinandClaude Opus 4.8 16746008cc docs(rel-002): released 전환 — M1 배포 evidence 귀속 (trex-op 2026-06-19)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-19 17:59:36 +09:00
genichinandClaude Opus 4.8 d89f137929 docs(rel-002): M1 신규 릴리즈 — BAT-017 거래내역+실현PnL API (confirm-release)
REQ-039~042 Implemented. Freeze 커밋 bd34450.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-19 16:57:29 +09:00
genichinandClaude Opus 4.8 bd34450ee9 feat(pnl): trade history + realized PnL API (WAC) — BAT-017, REQ-039~042 Implemented
- GET /v1/portfolios/{id}/trades and GET /v1/portfolios/{id}/pnl/realized endpoints
- Weighted Average Cost (WAC) realized PnL calculation in app/domain/pnl.py
- cost_basis and data_completeness_warning returned in pnl API response
- Test coverage: 50 passed (WAC 20 + trades 12 + pnl 18), full 427 passed regression ✓
- WAC validated against 199,300 unit e2e test cases
- DB migration: none required
- QC: qc-reviewer PASS-WITH-NOTES; team lead confirm-batch-verification → release-candidate
- Remaining non-blocking: symbol filter edge case testing, HTTP_422 deprecation

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-18 16:45:01 +09:00
genichinandClaude Opus 4.8 f37ef87c8c docs(dcy-007): draft + approve REQ-039~042 (trade history + realized PnL API)
dcy-007 분해 완료: 체결내역 조회(REQ-039, GET /trades), 실현 PnL 집계(REQ-040, GET /pnl/realized with WAC), WAC 산출 로직(REQ-041, service/domain 격리), 테스트 커버리지(REQ-042).

팀장 confirm-req 완료:
- 4건 모두 Proposed → Approved (dcy-007 결정·발견사항 반영, R-1 경고필드 포함, blocker 없음)
- M1(6/22) fast-track, 단일 batch 예정
- docs/srs/index.md: Next ID REQ-043, Register 4건 Approved, Change Log 갱신
- docs/discovery/dcy-007: 생성된 REQ 참조 업데이트

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-18 16:07:33 +09:00
genichinandClaude Opus 4.8 b3186f14a0 docs(dcy-007): confirm-discovery — daily trade history + realized PnL API
일일 거래내역(GET /trades) + 실현 PnL(GET /pnl/realized) 조회 API.
운영 모니터링 목적으로 issue #11에서 제기된 필요성.
사장님 결정: OQ-1 실현 PnL=weighted average cost(WAC),
OQ-2 전체 portfolio 집계=Out of Scope.
상태 confirmed, Ready for REQ Drafting: true.
M1(6/22) fast-track 대상.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-18 15:58:54 +09:00
63e4ceffac docs: REL-001 라이브 스모크 evidence 귀속 (trex-op 2026-06-16) (#13)
- [x] ④ legacy buy Deprecation 헤더: HTTP 200 + deprecation:true 확인
- [x] ⑤ ledger/trades 신규: HTTP 201 + cash_balance_after(-63296.1) + asset_quantity_after(1.0)
- [x] ⑥ idempotency duplicate: HTTP 200 + status=duplicate + ledger_entry_id 42 재반환
- [blocked] ③ 태그 mutation: v1_tags token_source guard로 차단, DB bootstrap 미설정
  → Feedback Handoff Discovery Input 이관

Co-authored-by: trex-dev-b <trex-dev-b@trex-team.internal>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 16:41:49 +09:00
de05728edf docs: REL-001 draft→released 정합 (배포 사실 귀속, 검증 처리) (#12)
- Status: draft → released
- Deployment Facts: 코드 6b812b6 + 문서 50beba3, 2026-06-14 13:09 KST, trex-op
- Alembic 마이그레이션: 로그 미보존, health db_enabled:true + 엔드포인트 200으로 적용 확인
- 검증 ①: trex-core cross-repo pending (dev-a/trex-core REL-008 확인 대기)
- 검증 ②: BAT-016 staging dry-run moot (prod 2일+ 가동 성공)
- 검증 ③④⑤⑥: 라이브 스모크 절차 정의 (trex-op 실행 대기)
- Startup/Request Log: 미보존, post-release feedback Discovery Input 이관
- releases/index.md: draft → released

Co-authored-by: trex-dev-b <trex-dev-b@trex-team.internal>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-16 16:27:03 +09:00
genichinandClaude Opus 4.8 50beba3ff6 docs: fold issue #9 user_info hotfix into REL-001 scope + 2026-06-06 smoke
- Add issue #9 hotfix (GET /v1/user_info 500 on missing broker_credentials) to
  REL-001 Included scope + Revision (6b812b6 as integrated main HEAD).
- Add post-deploy smoke item for /v1/user_info 200 + daemon_id (local verified).
- Record 2026-06-06 local verification: ledger_trades absent / portfolio_ledger
  consolidated schema, legacy buy/sell OpenAPI deprecated, full suite 377 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 17:51:30 +09:00
genichinandClaude Opus 4.8 6b812b6035 fix: GET /v1/user_info 500 on missing broker_credentials table (issue #9)
trex-core reported GET /v1/user_info returning 500 for valid service/daemon
tokens (whoami → daemon_id), degrading the daemon and holding new trades. The
reported hypothesis (service-token None deref) was a misdiagnosis. Root cause:

  app/api/v1_user_info.py: credentials = repo.list_broker_credentials(...)
  psycopg.errors.UndefinedTable: relation "broker_credentials" does not exist

The broker_credentials table was missing and the handler only caught
AttributeError, so the DB error propagated to a bare 500.

Two fixes:
1. Handler now degrades gracefully when broker-credential lookup fails — returns
   empty brokers and still serves daemon_id/user_id/permission, which do not
   depend on broker credentials. This is what trex-core's whoami needs.
2. ensure_schema() now also CREATE TABLE broker_credentials (same shape as
   migration 20260502_0014). ensure_schema-bootstrapped DBs were missing it,
   since previously only the alembic path created it.

Added tests/test_v1.py regression: broker-credential lookup raising a DB error
must yield HTTP 200 with daemon_id, not 500. Verified against the real DB
(was 500 → now 200 + daemon_id). Full suite 377 passed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-06 10:17:30 +09:00
genichin b774e40678 docs: consolidate REL-001 scope across BAT-001~016
- fold BAT-015 and BAT-016 into REL-001 release scope
- mark split REL-002 and REL-003 plans as superseded in discovery docs
- update release and batch indexes to match the unified release plan
- expand REL-001 rollout, rollback, verification, and evidence notes
2026-06-05 22:49:10 +09:00
genichinandClaude Opus 4.8 2a19b7f058 fix: ledger write idempotency for TimescaleDB hypertable (BAT-016 rework)
BAT-016's initial implementation passed only against mocked repositories and
broke on a real database. Two defects fixed:

1. insert_ledger_trade used `ON CONFLICT (portfolio_id, order_id, execution_id)
   WHERE order_id IS NOT NULL` but portfolio_ledger is a TimescaleDB hypertable,
   which cannot have that partial unique index (must include the partitioning
   column recorded_at). The statement errored against Postgres. Replaced with
   application-level idempotency: SELECT-before-insert inside the existing
   `SELECT ... FOR UPDATE` portfolio row lock, which serializes concurrent
   same-portfolio writes (race-safe). Duplicate returns current authoritative
   portfolio state (dcy-006 OQ-4 b).

2. `with self._connect() as conn:` closes the shared psycopg3 connection on exit,
   leaving the reused repository connection unusable. Switched to
   `with conn.transaction():` (commits without closing).

Added tests/test_ledger_consolidation_integration.py — real-Postgres integration
tests (new / duplicate / negative-balance) that close the mock-only verification
gap. Full suite: 376 passed.

SDLC: REQ-036/037 CHG-20260605-03 reconcile OQ-7 (ii) (DB partial unique →
application-level idempotency) since the hypertable makes the DB constraint
infeasible. REQ-036/037/038 → Implemented; BAT-016 → release-candidate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-05 22:11:17 +09:00
genichin 44f2102d26 feat: consolidate ledger trade writes into portfolio_ledger
- add ledger consolidation migration and remove ledger_trades usage
- return portfolio state after v1 ledger trade writes
- deprecate legacy buy/sell endpoints with deprecation headers
- add BAT-016, DCY-006, and REQ-036~038 documentation
- update repository models and tests for unified ledger entries
2026-06-05 20:55:24 +09:00
genichin 2470c0a00c feat: apply rel-001 feedback cleanup 2026-06-05 13:57:46 +09:00
genichinandClaude Opus 4.7 84de34c301 feat: REQ-028 add display_name to GET /v1/portfolios response
- Portfolio domain model + PortfolioItem schema에 display_name 필드 추가
- _SELECT_PORTFOLIO에 a.display_name JOIN 보강, _portfolio_to_item 매퍼 전달
- REQ-028 CHG-20260601-01/02: Implemented → Approved → Implemented
  - AC-13 신설 (display_name == joined assets.display_name)
- BAT-009 verification.md: AC-13 매핑 + augmentation history 누적
- REL-001 verification checklist 재실행 evidence 갱신 (368 PASSED, 로컬 smoke 5건 통과)
- tests/test_v1.py: dead 중복 GET /v1/assets 섹션 제거 (두 번째 동명 정의가 첫 번째를 override하던 잔재)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-01 14:00:59 +00:00
genichin 136ae16885 feat: add portfolio item symbol to v1 responses 2026-05-24 13:09:37 +09:00
genichinandClaude Opus 4.7 3a78e5c138 fix: reveal plaintext service token on issue/rotate (HOTFIX-001)
- render_service_token_result no longer masks the token field; plaintext
  tokens are SHA-256 hashed in DB and irrecoverable once lost, so issue/
  rotate must reveal them once at issuance (matches interface-contract.md)
- Remove now-unused _mask_payload helper; keep mask_token_text for the
  auxiliary masked_token identifier line
- Add one-time reveal warning to issue/rotate table output
- 3 regression tests: JSON plaintext assertion, render unit test, table warning
- Hotfix Exception Path record: docs/hotfixes/hotfix-001
- Total tests: 369 -> 371 passed

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 17:36:05 +09:00
genichinandClaude Opus 4.7 58899b1a94 feat: REQ-005 assets table tag apply/remove SQL alignment (BAT-013)
- REQ-005 CHG-20260521-02 follow-up: clarify AC-1/AC-5 to target assets table
- Add append_asset_tag_id/remove_asset_tag_id on PostgresPortfolioRepository
- Replace internal calls in apply_asset_tag/remove_asset_tag routes (HTTP contract unchanged)
- 7 new regression tests: method existence, SQL target table, error branches, idempotency guard
- Update existing AC-1/AC-5 assertions to verify new methods + portfolios methods uncalled
- Documentation: runtime-flows.md flow body + change log; rel-001 includes BAT-013
- REQ-005 transition: Approved → Implemented (CHG-20260521-03) via BAT-013 verification
- Total tests: 362 → 369 passed

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 00:04:33 +09:00
genichinandClaude Opus 4.7 9038f41010 feat: REQ-002/REQ-010 implementation — assets.tag_ids column + GET /v1/assets admin catalog (BAT-012)
- REQ-002 scope redefinition: portfolios.tag_ids → assets.tag_ids UUID[] column with GIN index
- REQ-010 augmentation: GET /v1/assets redesigned as admin catalog endpoint (admin-only, no token_type branching)
- Asset tagging infrastructure: tag_ids column, archived flag synthesis for inactive tags, list_assets N+1 optimization
- DB migration 20260521_0023: assets.tag_ids UUID[] NOT NULL DEFAULT '{}', idx_assets_tag_ids_gin
- Test suite: 17 new test cases for assets.tag_ids + GET /v1/assets AC-9~12 (362 tests total)
- Documentation: runtime flows, release baseline, batch verification all updated
- BAT-012 added to REL-001 Included Batch and marked release-candidate

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-21 23:37:08 +09:00
genichin d01039e98f Merge branch 'main' of https://github.com/fourblocks2020/portfolio-hub
# Conflicts:
#	migrations/versions/20260519_0021_portfolio_tags_data_migration.py
#	migrations/versions/20260520_0022_service_token_unique_index_fix.py
2026-05-21 13:28:56 +00:00
genichin c4f8718872 fix: respect root_path in FastAPI docs 2026-05-21 21:45:39 +09:00
genichin 600963158e 마이그레이션 버그 수정 2026-05-21 12:06:59 +00:00
genichinandClaude Sonnet 4.6 6add0ade29 feat: REQ-001~018 Implemented 전환, REQ-010 GET /v1/assets admin catalog 재정의, REL-001 draft
- confirm-req-implemented: REQ-001~018 (17건, REQ-013 제외) Approved → Implemented
  - BAT-001(REQ-009/011/014), BAT-002(REQ-010/012/015), BAT-003(REQ-001/002/003/006)
  - BAT-004(REQ-004/005), BAT-005(REQ-007/008), BAT-006(REQ-016/017/018)
  - CHG-20260521-01 entry 각 REQ에 추가; SRS index Recent Change Log 갱신

- REQ-010 CHG-20260521-02: GET /v1/assets admin catalog 전용 재정의
  - 기존 token_type 분기 portfolio 조회 코드 제거, admin permission + list_assets() 호출로 대체
  - AssetCatalogListResponse 스키마 추가 (items/total)
  - REQ-010 Status: Implemented → Approved (재검증 필요)
  - 테스트 343건 전체 통과: service/user token 403, admin token 200 + catalog schema 검증

- migration 보강: portfolios_asset_migration market 컬럼 부재 fallback,
  portfolio_tags 빈 테이블 early-return, service_token index fix autocommit_block 정리

- docs/releases/rel-001: REL-001 draft 추가 (BAT-001~011 포함)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 10:17:39 +00:00
genichinandClaude Sonnet 4.6 4bf6b554a7 feat: v1 portfolio mutation, sub-resources, ledger path migration (BAT-008~011)
dcy-003/004 기반 v1 API surface 완성 및 BAT-008~011 구현·검증 완료:

- BAT-008 (REQ-019~021,024): 토큰 surface baseline 문서 갱신
- BAT-009 (REQ-025~028): POST/PATCH/DELETE/GET /v1/portfolios CRUD 신설
  - _require_write_token, _get_portfolio_or_404, soft delete, daemon-scoped list
- BAT-010 (REQ-030~032): portfolio tag/comment 서브 라우트 신설 + baseline 갱신
  - GET/POST/DELETE /v1/portfolios/{id}/tags
  - POST/GET/PATCH/DELETE /v1/portfolios/{id}/comments
- BAT-011 (REQ-029): ledger path migration
  - POST /v1/assets/{asset_id}/ledger/trades → /v1/portfolios/{portfolio_id}/ledger/trades
  - v1_ledger.py 제거, disabled 차단(409) 추가
  - test_v1.py / test_daemon_assignment.py 구 path 갱신
- 신규 tests: test_v1_portfolios_crud.py, test_v1_portfolios_list.py,
  test_v1_portfolios_tags_comments.py, test_v1_portfolios_ledger.py
- 전체 suite: 340 passed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 07:25:39 +00:00
genichinandClaude Sonnet 4.6 c815ce39b6 feat: dcy-003/004 토큰 surface 개편 및 daemon lifecycle 정책 구현 (BAT-006/007)
BAT-006 (REQ-016/017/018):
- client token 발급 경로 제거 (issue_client_token, POST /auth/tokens, 관련 스키마/테스트)
- service-token rotate unique index revoked_at IS NULL 조건 추가 (Alembic CONCURRENTLY 마이그레이션)
- POST /auth/service-tokens body daemon_id forward 누락 보정 (1-line fix)

BAT-007 (REQ-022/023):
- daemon deactivate 시 바인딩 service token 자동 revoke (CLI --force 옵션 + revoke_tokens_by_daemon_id)
- NULL daemon_id legacy token 진단 CLI (migrate-null-daemon --dry-run)

거버넌스 문서: dcy-003/004 Discovery, REQ-016~023/025~032 신규, BAT-006/007 전체 산출물

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-21 01:03:39 +00:00
genichinandClaude Sonnet 4.6 d4b841bc37 feat: 태그 HTTP API(BAT-004) 및 pfhub tag CLI + baseline 문서 갱신(BAT-005)
BAT-004 (REQ-004, REQ-005):
- app/api/v1_tags.py: POST /v1/tags, GET /v1/tags, PATCH /v1/tags/{id}/deactivate
- app/api/v1_portfolios.py: POST/DELETE /v1/portfolios/{id}/tags
- app/api/v1_assets.py: POST/DELETE /v1/assets/{id}/tags 엔드포인트 추가
- app/schemas/v1.py: TagItem, TagCreateRequest, TagListResponse, TagApplyRequest/Response 추가
- app/repositories/portfolio_repository.py, postgres.py: append/remove_portfolio_tag_id 추가
- app/main.py: v1_portfolios_router, v1_tags_router 등록
- tests/test_tags_http_api.py: 22개 HTTP API 테스트

BAT-005 (REQ-007, REQ-008):
- app/cli/commands/tag.py: pfhub tag create/list/deactivate/apply/remove 7개 커맨드 신규
- app/cli/main.py: tag_app 등록
- app/cli/commands/portfolio.py: pfhub portfolio tag add/list/remove 완전 제거(breaking change)
- app/cli/core/utils.py: print_tag_table + list[Tag] render 분기 추가
- tests/test_tags_cli.py: REQ-007 AC-1~9 커버 24개 CLI 테스트 신규
- tests/test_cli.py: 제거된 portfolio tag 테스트 2개 삭제
- docs/data-model.md, interface-contract.md, project-structure.md, runtime-flows.md: 태그 모델 baseline 갱신(REQ-008)
- docs/batches/: BAT-004, BAT-005 전체 산출물(release-candidate)

247 passed

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 01:16:13 +00:00
genichin 158929b2d9 feat: asset catalog API, 태그 DB 기초, 마이그레이션 3건 및 도메인/테스트 갱신 (2026-05-19) 2026-05-19 22:15:55 +00:00
genichin e2226e28b6 feat: implement asset catalog database foundation (BAT-001, REQ-009/011/014)
Asset Catalog Model Implementation (BAT-001):
- Introduce assets table with UUID PK, symbol UNIQUE, markets TEXT[] array
- Define MarketCode enum (KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITHUMB)
- Add Asset domain model with catalog properties
- Implement asset CRUD protocols in portfolio_repository
- Add PostgreSQL asset CRUD operations with GIN index on markets

Portfolio Model Refactoring (REQ-011):
- Add portfolios.asset_id UUID FK to assets(asset_id) ON DELETE RESTRICT
- Remove portfolios.symbol and portfolios.market columns
- Update Portfolio domain model to reference asset_id instead of symbol/market
- Refactor all portfolio queries to JOIN assets catalog
- Update all repository methods to use asset references

Data Migration (REQ-014):
- Create 20260519_0017 Alembic revision for assets table creation
- Create 20260519_0018 Alembic revision for atomic data migration:
  * Extract unique symbol combinations from portfolios
  * Aggregate markets using ARRAY_AGG(DISTINCT market)
  * Populate assets catalog with extracted data
  * Update portfolios.asset_id to reference new assets
  * Remove legacy symbol/market columns in single transaction
- Implement migration with rollback support

Requirements Approved (REQ-001~008):
- REQ-001~008 transitioned from Proposed to Approved
- Complete tag model requirement set with implementation readiness

New Requirements Approved (REQ-009~015):
- REQ-009: assets table schema (approved, included in BAT-001)
- REQ-010: admin asset catalog CRUD (approved, future BAT-002)
- REQ-011: portfolios asset_id FK (approved, included in BAT-001)
- REQ-012: portfolio create catalog validation (approved, future BAT-002)
- REQ-013: GET /v1/assets token branching (approved, future BAT-002)
- REQ-014: portfolios data migration (approved, included in BAT-001)
- REQ-015: asset catalog baseline docs (approved)

Code Changes:
- app/domain/models.py: Add Asset model, MarketCode enum, Portfolio asset_id FK
- app/repositories/portfolio_repository.py: Define asset CRUD protocol
- app/repositories/postgres.py: Implement asset operations with full CRUD
- app/api/v1_assets.py: Remove symbol/market direct references
- app/cli/commands/portfolio.py: Update portfolio commands for asset references
- app/schemas/portfolio.py: Update portfolio schema with asset_id
- All portfolio operations throughout codebase: Use asset references

Testing:
- Add test_asset_catalog.py for asset CRUD operations
- Verify REQ-009 AC-1~5 (asset catalog creation, lookup, uniqueness)
- Verify REQ-011 AC-1~5 (FK constraint, portfolio asset reference)
- Verify REQ-014 AC-1~6 (migration atomicity, data correctness, rollback)
- Update existing tests for asset model usage

Documentation:
- Create BAT-001 batch documents (planning, design, implementation, verification)
- Update dcy-001 with implementation details and confirmed architecture
- Add 8 new requirement documents (REQ-009~015)
- Update docs/discovery/index.md with batch entry

Impact:
- Database: assets catalog table, portfolios refactored to reference assets
- Migration: 2 new Alembic revisions (0017 assets, 0018 portfolio migration)
- API: Symbol/market now accessed through asset references
- CLI: Portfolio commands require asset reference pattern
- All existing portfolio data preserved and correctly migrated
2026-05-19 15:59:20 +00:00
genichin 1082f041a1 chore: restructure SRS for asset catalog and tag model redesign (dcy-001/002, REQ-001~008)
Architecture Redesign (May 19, 2026):
- Separate admin-managed asset catalog from user portfolios
- Eliminate portfolio as asset definition; clarify portfolio as user position
- Introduce new asset_catalog + portfolio structure

Discovery Documents:
- dcy-001: asset-catalog-and-user-portfolio-model — admin asset management and user portfolio separation
- dcy-002: tag-ownership-and-applicability-policy — tag model implementation strategy

New Requirements (REQ-001~008):
- REQ-001: tags master table introduction (Data, Proposed)
- REQ-002: assets.tag_ids UUID[] column addition (Data, Proposed)
- REQ-003: portfolios.tag_ids and portfolio_tags removal (Data, Proposed)
- REQ-004: tags master HTTP API (Interface, Proposed)
- REQ-005: tag apply/remove HTTP API (Interface, Proposed)
- REQ-006: portfolio_tags data migration (Migration, Proposed)
- REQ-007: pfhub tag CLI commands (Interface, Proposed)
- REQ-008: tag model baseline docs update (Documentation, Proposed)

Cleanup:
- Remove archived SRS documents (REQ-001~029 old structure)
- Remove archived batch documentation (BAT-001~010)
- Remove archived discovery documents (dcy-001~006 old structure)
- Remove archived release documentation (REL-001~006)

Data Model Updates:
- Add Deployment category to SRS structure
- Add Data category for new data model requirements
- Update app/cli/core/utils.py for new tag handling

Documentation:
- Create new SRS index with consolidated requirement structure
- Update docs/discovery/index.md with new discovery references
- Migrate from requirement-centric to domain-model-centric organization

Rationale:
- Existing single-portfolio model lacks admin catalog governance
- New asset catalog enables central management of tradeable symbols
- Tag system supports user-driven asset organization and discovery
- Cleaner separation of concerns between admin operations and user trading
2026-05-19 13:54:25 +00:00
genichinandClaude Sonnet 4.6 47c4f9bfde docs: record governance changes for REQ-008/017/023 defect fixes and add REQ-029
- REQ-017 CHG-20260518-01: document get_portfolio_by_name_and_user postgres
  defect fix; status Implemented preserved
- REQ-008 CHG-20260518-01: document insert_ledger_trade postgres defect fix
  (HTTP 500 on ledger write-back); status Approved, re-verification required
- REQ-023 CHG-20260518-01: add AC-5 (portfolio update --daemon-id CLI) and
  AC-6 (portfolio list daemon-id display); expand Impacted Area
- REQ-029: new Interface REQ for portfolio list borderless output format;
  status Approved, minor-change fast path
- SRS index: register REQ-029, advance Next ID to REQ-030, update Recent
  Change Log Summary

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 04:05:58 +00:00
genichinandClaude Sonnet 4.6 b155eeff7d fix: add missing postgres implementations for get_portfolio_by_name_and_user and insert_ledger_trade
- add get_portfolio_by_name_and_user to PortfolioRepository protocol and
  PostgresPortfolioRepository; resolves AttributeError on all CLI name+user
  resolution paths (REQ-017)
- add insert_ledger_trade to PortfolioRepository protocol and
  PostgresPortfolioRepository; resolves HTTP 500 on POST
  /v1/assets/{asset_id}/ledger/trades (REQ-008)
- add _row_to_ledger_trade static helper; uses INSERT ... ON CONFLICT DO
  NOTHING RETURNING to return (LedgerTrade, created: bool)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 04:05:48 +00:00
genichin b9e3bddb34 feat: add portfolio daemon assignment and improve list rendering
- Add --daemon-id option to portfolio update command for daemon assignment
- Update managed_by_daemon_id field in portfolio updates
- Refactor print_portfolio_table() to print_portfolio_list() for better readability
- Display daemon_id in portfolio list output when assigned
- Show portfolio tags and managed daemon information in CLI list view
- Add daemon_id support to portfolio repository and service layers
- Update schemas to include managed_by_daemon_id field in responses
2026-05-15 08:27:14 +00:00
genichin d194873616 feat: implement broker credential repository with upsert and list operations
- Add BrokerCredential to domain models and repositories
- Implement upsert_broker_credential() for credential storage and rotation
- Implement list_broker_credentials() for credential retrieval
- Implement delete_broker_credential() for credential removal
- Add broker_credentials table schema with (user_id, broker) composite key
- Implement credential version tracking and last_rotated_at timestamps
- Add FakeRepo support for broker credential CRUD operations
- Add comprehensive test coverage for broker credential lifecycle
2026-05-14 07:56:37 +00:00
genichin f4663f202e feat: add daemon CLI rendering functions and tests
- Add print_daemon_table() function to display daemon list in rich table format
- Add print_daemon_detail() function to display individual daemon information
- Update render_output() to support daemon rendering with json/table formats
- Add test for daemon create and list CLI commands with output validation
- Integrate daemon output rendering into CLI workflow
2026-05-14 06:38:21 +00:00
genichin 3bb3ff547d feat: extend daemon model with daemon status tracking and list support
- Add daemon status tracking with state and metrics (idle, running, error)
- Implement pfhub daemon list CLI command for viewing registered daemons
- Extend auth schema and service for daemon lifecycle management
- Add postgres repository queries for daemon state persistence
- Expand test coverage for daemon registry and status transitions
- Update rel-006 release document with daemon model verification results
- Support daemon graceful shutdown and error recovery patterns
2026-05-14 06:29:52 +00:00
genichin e6b6a8715b feat: implement daemon model with registry and single-asset assignment (BAT-010, REQ-023/028)
Core Implementation (BAT-010):
- Add daemon registry schema and CRUD operations (req-023)
- Implement single-daemon asset assignment constraint (one asset per daemon)
- Add daemon_id field to service_token for daemon identification
- Add daemon.py CLI module for daemon management commands
- Add 20260513_0016_daemon_model.py migration for daemon tables

API Changes:
- GET /v1/assets: include daemon_id in AssetResponse
- POST /v1/assets/{asset_id}/ledger/trades: require daemon token binding
- GET /v1/user_info: include daemon metadata
- Enhanced service-token rotate to preserve daemon bindings

CLI Commands:
- pfhub daemon register --name <name> --runtime-id <runtime-id>
- pfhub daemon list
- pfhub daemon get <daemon-id>
- pfhub daemon revoke <daemon-id>

Requirements (REQ-023, REQ-028):
- REQ-023: Daemon Registry and Service Token Daemon Binding (Interface, Approved)
  * AC-1: daemon CRUD operations
  * AC-2: service token daemon binding for POST /v1/assets/{asset_id}/ledger/trades
  * AC-3: single daemon per asset (exact-one assignment model)
- REQ-028: README.md Daemon Provisioning Runbook update (Documentation, Approved)

Documentation:
- Add dcy-006 Discovery for daemon-id and single-daemon asset assignment
- Update README.md with Daemon Provisioning Runbook section
- Add BAT-010 batch documentation with planning, implementation, verification
- Update rel-006 release document (daemon model implementation)
- Update data-model.md with daemon and daemon_asset_assignment tables
- Update interface-contract.md with daemon registry APIs
- Update runtime-flows.md with daemon lifecycle flows

Breaking Changes:
- REQ-005~009, REQ-011~012 status reverted to Approved due to revised contract
  * daemon_id field addition and exact-one asset assignment requirement
  * Existing Implemented evidence invalidated by contract revision
  * BAT-001/002/008 re-verification required

Testing:
- Add test_daemon_registry.py for daemon CRUD operations
- Add test_daemon_assignment.py for single-asset assignment constraints
- Update test_auth.py, test_cli.py, test_v1.py for daemon support
- Verify daemon token binding in trade endpoint authorization

Impact:
- Database: 2 new tables (daemons, daemon_asset_assignments)
- Migration: 20260513_0016 creates daemon model schema
- CLI: 4 new daemon subcommands
- API: daemon_id propagation through v1 endpoints
- Verification: BAT-001/002/008 re-verification gates next release
2026-05-13 23:07:24 +00:00
genichin f0a6caa178 feat: implement v1 consumer API endpoints with runtime_id support (REQ-004~010)
- Generate runtime_id for service-token issuance (CLI and API)
- Implement GET /v1/assets endpoint with asset view and strategy_params
- Implement GET /v1/user_info endpoint with trading_enabled and broker credentials
- Implement POST /v1/assets/{asset_id}/ledger/trades with idempotency support
- Update auth service to support runtime_id tracking and credential encryption
- Add comprehensive test coverage for v1 endpoints (dcy-002 implementation)
- Update postgres repository for ledger and broker credential queries
- Ensure all tests pass for feature validation
2026-05-13 07:13:03 +00:00
genichin 3255d096f1 refactor: simplify data model by removing unused fields and constraints
- Remove runtime_id from AuthToken model
- Remove market field from Portfolio model
- Remove BrokerCredential and LedgerTrade unused models
- Remove unique constraint on (owner_user_id, name)
- Simplify postgres repository schema and queries
- Clean up auth_service implementation
- Update test suite for simplified model
2026-05-13 06:48:26 +00:00
genichin 03bc3dcd8f docs: add rel-005 production operator runbook and credential matrix (REQ-020~022)
Release: REL-005_20260512 — Production Operator Runbook and Credential Matrix

Requirements Approved (REQ-020~022):
- REQ-020: production admin bootstrap and steady-state operator access runbook (Deployment)
- REQ-021: release credential matrix and token provenance procedures (Documentation)
- REQ-022: operator log access and release evidence recording procedures (Documentation)

Batch: BAT-009
- Enhance README.md Production Operator Runbook section with:
  - Deployment secret custodian role labels
  - Release approver and production operator role definitions
  - Credential matrix table (public/read/trade-write/admin permission levels)
  - Canonical smoke environment specifications
  - HTTP status code interpretation (401/403/404)
  - Release evidence recording fields

Documentation Updates:
- Add README.md Section 2: deployment roles and responsibilities
- Add README.md Section 3: 4-tier credential matrix with token usage patterns
- Enhance README.md Section 6: smoke test procedures and evidence capture
- Add bootstrap/steady-state/break-glass 3-tier access pathway clarification
- Create REQ-020 Deployment runbook document
- Create REQ-021 credential matrix procedures document
- Create REQ-022 operator log access procedures document

Discovery & Release:
- Update dcy-005 with operator access requirements analysis
- Create rel-005 with docs-only profile and deployment notes
- Update docs/batches/index.md with BAT-009 entry
- Update docs/srs/index.md with REQ-020~022 entries and change log
2026-05-12 23:19:48 +00:00
genichin 7bcf5cbb2b docs: update CLI documentation to use username instead of user-id
CLI Changes:
- Update user.get command to accept username parameter instead of user-id
- Update user.update command signature in documentation
- Update user.delete command signature in documentation

Implementation Consistency:
- Align README.md CLI examples with app/cli/commands/user.py implementation
- Clarify username-based user identification across all user management commands
- Update test expectations to match username-based interface

Documentation:
- README.md: Replace <user-id> with <username> in all user command examples
- Ensure consistency across user create, get, update, delete commands
2026-05-12 12:26:06 +00:00
genichin 4fa770e771 docs: add rel-003, rel-004 releases and update CLI user scoping implementation
Release: REL-003_20260512 — CLI user scoping and local DB ops runbook

Requirements & Batches:
- BAT-003 (REQ-013): portfolio list --user required enforcement with owner filtering
- BAT-004 (REQ-014): portfolio create --user required enforcement with owner assignment
- BAT-007 (REQ-001/002/003): local DB validation runbook and baseline docs update

CLI Enhancements:
- Update user.py: add username-based user lookup (get_by_username)
- Add UserDetailResponse schema with service token listing
- Update list_service_tokens API in user_service.py
- Enhance user detail display with service token information
- Add service_token_count and service_token_names to user responses

Testing:
- Add comprehensive test coverage in test_cli.py for user commands
- Validate username-based lookup functionality

Release: REL-004_20260512 — Portfolio UUID migration and API UUID switch

Requirements & Batches:
- BAT-006 (REQ-016/017/018): portfolio UUID migration complete
- BAT-008 (REQ-019): baseline documentation update for UUID migration

Breaking Changes (REL-003):
- portfolio list requires --user <username> parameter
- portfolio create requires --user <username> parameter

Documentation:
- Create rel-003 and rel-004 release documents with rollout and rollback plans
- Update docs/releases/index.md with new releases
- Update README.md with CLI user scoping clarification
- Sync all release verification checklists and deployment notes
2026-05-12 12:13:38 +00:00
genichin 2e1298a978 fix: enforce trade-write permission check on v1 ledger trade endpoint
Security Fix:
- Update v1_ledger.py to require trade_write permission instead of read
- Fix authentication dependency from require_read to require_trade_write
- Ensure trade operations cannot be performed with read-only service tokens

Test Coverage:
- Add test_v1_ledger_trade_requires_trade_write_permission() to verify permission boundary
- Confirm read-only tokens are rejected with 403 Forbidden status
- Validate repository methods are not called on permission failure

Documentation:
- Add new Discovery dcy-005 for production admin bootstrap and operator access
- Update docs/discovery/index.md with dcy-005 entry
- Update release rel-001 with additional verification notes and issue references
2026-05-11 14:17:27 +00:00
genichin d20d784452 docs: add rel-002 release and transition REQ-011, REQ-012, REQ-015 to Implemented
Release: rel-002_20260511_operator-cli-tooling-and-baseline-docs-sync

Requirements Completed:
- REQ-011: baseline docs update for trex-basic contract (BAT-008 verification passed)
- REQ-012: service-token rotate CLI command (BAT-002 verification passed)
- REQ-015: broker credential CLI command group (BAT-005 verification passed)

Release Contents:
- Operator CLI tooling with service-token rotate and broker credential management
- Baseline documentation synchronized with trex-basic interface contract
- Complete v1 API and portfolio ownership model documentation

Documentation Updates:
- Create rel-002 release document with included batches and deployment notes
- Update docs/releases/index.md with release entry
- Add implementation evidence to REQ-011, REQ-012, REQ-015
- Update SRS index with Implemented status transitions and change log
2026-05-11 12:13:29 +00:00
genichin a5b5e7a93c fix: resolve SRS conflicts from batch verification analysis (CONFLICT-1~4)
Conflict Resolutions:
- CONFLICT-1 (High): Fix REQ-006 ownership scope — implement owner_user_id filtering
  * Change app/api/v1_assets.py: owner_user_id=None → owner_user_id=auth.user_id
  * Update docs/runtime-flows.md to reflect service-token owner-scoped portfolio filtering
  * Add regression test in tests/test_v1.py for ownership boundary

- CONFLICT-2 (Medium): Transition REQ-001/002/003 to Implemented
  * REQ-001: local-db-validation-scenarios (via confirm-req-implemented bat-007)
  * REQ-002: alembic-runtime-schema-ownership (via confirm-req-implemented bat-007)
  * REQ-003: local-db-operations-runbook-and-baseline-updates (via confirm-req-implemented bat-007)
  * Update docs/srs/index.md with status transitions

- CONFLICT-3 (Low): Document REQ-012 rotate lifecycle
  * Add rotate lifecycle notes to REQ-012 (change-req req-012)
  * Clarify runtime_id change behavior and trex-basic reconnection requirements

- CONFLICT-4 (Low): Clarify REQ-005 AC-2 endpoint path
  * Change REQ-005 AC-2: 'POST /auth/tokens or equivalent' → 'POST /auth/service-tokens'
  * Update docs/srs/index.md change log with change-req entries

Documentation Updates:
- Update BAT-001 verification status with conflict resolution evidence
- Update release rel-001 with verified status confirmation
- Add change log entries for all conflict resolutions with dates and references

Testing:
- Add ownership boundary test to test_v1.py
- Verify filter works with auth.user_id context
2026-05-11 11:57:21 +00:00