POST /v1/portfolios now forwards a non-null managed_by_daemon_id into
create persistence, and both create and PATCH apply the same daemon
validation contract (UUID format -> 422, missing/foreign -> 404,
inactive -> 409, admin target-owner basis). Daemon validation locks the
daemon row FOR SHARE inside the portfolio write transaction so
validation and write form one atomic decision boundary.
Adds domain errors, repository protocol/signature updates, API/PostgreSQL
tests (POST->GET persistence, no partial state on failure, assignment vs
deactivation race), and contract/data-model documentation.
Add reversal-aware grouped manual-ledger aggregates to portfolio list responses and align the single-portfolio return summary with the same semantics.\n\nRefs #23
Adds 4 additive fields to GET /v1/portfolios (and single-portfolio) response:
- active_strategy_id (str|null): portfolios.active_strategy_id raw value
- strategy_name (str|null): strategy_sets.name via LEFT JOIN
- strategy_params (dict): strategy_sets.config JSON parsed; {} on missing/invalid
- markets (list[str]): assets.markets; [] on missing/empty
_SELECT_PORTFOLIO extended with LEFT JOIN strategy_sets; _row_to_portfolio
parses new columns (row[19-21]) with JSON error isolation (WARNING log, no 500).
_portfolio_to_item maps all 4 new fields. Existing 16 fields unchanged.
N+1 prevented: single SQL JOIN for both list and single-item paths.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
update_daemon_owner()에서 owner UPDATE + credential DELETE를 단일
conn.transaction() 블록으로 묶어 원자성 보장. 실패 시 두 연산 모두
롤백되므로 "새 owner + 이전 credential 잔류" leak 상태(dcy-011 OQ-3)
가 불가능해짐. 실행 순서도 DELETE-first(안전 순서)로 고정.
단위 테스트 3종 추가:
- DELETE-before-UPDATE 실행 순서 검증
- UPDATE 실패 시 rollback(commit 미호출) 검증
- 단일 transaction() 블록 안에서 두 연산 실행 검증
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
Add three approved requirements documents for dcy-011:
- REQ-052: User-owned credential management API (Interface)
- REQ-053: Admin daemon CRUD API (Interface)
- REQ-054: Credential management security with write-only constraint (Non-Functional)
Update discovery document to reference generated requirements and update index with new REQ IDs and Change Log.
Scope: Self-service credential management + admin daemon CRUD + security-isolated API for portfolio-hub.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
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
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
- 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
- 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>
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>
- 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
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>
- 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>
- 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>
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>
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