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
This commit is contained in:
2026-05-13 23:07:24 +00:00
parent f0a6caa178
commit e6b6a8715b
45 changed files with 2688 additions and 167 deletions
+44 -5
View File
@@ -4,8 +4,8 @@
- Baseline Seed: .stagepilot/bootstrap/baseline.yaml
- Status: confirmed
- Owner: repository-maintainers
- Last Updated (KST): 2026-05-11 00:00
- Source Discovery / Batch: bootstrap-baseline, bat-001, bat-006, bat-008
- Last Updated (KST): 2026-05-13 00:00
- Source Discovery / Batch: bootstrap-baseline, bat-001, bat-006, bat-008, bat-010
## Project Summary
- PortfolioHub exposes portfolio management and trading ledger workflows through a FastAPI service and a companion CLI.
@@ -29,7 +29,8 @@
- Portfolio :: owned investment portfolio with balances, strategy references, tags, comments, and ledger history
- User :: authenticated principal that owns portfolios and receives client or service tokens
- AuthToken :: issued client or service token with permission and optional runtime_id
- Daemon :: stable logical identity for a trading daemon process; registered per user; bound to service tokens and assigned to assets
- AuthToken :: issued client or service token with permission, runtime_id, and optional daemon_id binding
- BrokerCredential :: encrypted broker API credentials per user-broker pair
- LedgerTrade :: idempotent trade execution record keyed by (asset_id, order_id, execution_id)
@@ -49,6 +50,7 @@
- active_strategy_id :: text|null :: currently selected strategy-set reference
- cash_balance :: double precision :: current cash snapshot after the latest ledger event
- asset_quantity :: double precision :: current holdings snapshot after the latest ledger event
- managed_by_daemon_id :: text|null :: soft reference to daemons.id; controls daemon-scoped API access; NULL = unassigned (fail-closed for ledger writes and asset listing); added by migration 20260513_0016
### Uniqueness Constraints
@@ -57,6 +59,7 @@
### Relationships
- User :: owner_user_id links a portfolio to its owning user when ownership is assigned
- Daemon :: managed_by_daemon_id links a portfolio to exactly one daemon; NULL means unassigned
- StrategySet :: active_strategy_id and avabile_strategies connect reusable strategy definitions
- LedgerEntry, PortfolioComment, PortfolioTag :: child records are keyed by portfolio_id (UUID)
@@ -108,7 +111,8 @@
- token_source :: text :: "db" for persisted tokens; "env" for environment-injected tokens
- permission :: text :: read, trade-write, or admin
- service_name :: text|null :: logical name for service tokens (unique within token_type="service")
- runtime_id :: text|null :: opaque runtime identifier assigned at service-token issuance; unique (partial index on non-NULL values); added by migration 20260502_0014
- runtime_id :: text|null :: per-token opaque runtime identifier; regenerated on every rotate; added by migration 20260502_0014
- daemon_id :: text|null :: soft reference to daemons.id; stable across rotates (rotate invariant); NULL = legacy/unbound token (fail-closed for daemon-scoped endpoints); added by migration 20260513_0016
- expires_at :: timestamptz|null :: token expiry; null for non-expiring tokens
- created_at :: timestamptz :: issuance timestamp
@@ -119,9 +123,43 @@
### State Rules
- Service tokens with runtime_id are the only tokens accepted by v1 API endpoints; GET /v1/user_info returns HTTP 404 if runtime_id is None.
- Service tokens are the only tokens accepted by v1 API endpoints.
- runtime_id is per-token and changes on every rotate; daemon_id is stable across rotates (daemon_id invariant).
- daemon_id=NULL tokens are fail-closed on GET /v1/assets and POST /v1/assets/{asset_id}/ledger/trades (HTTP 403); GET /v1/user_info returns 200 + `daemon_id: null` as diagnostic.
- Token permission gates both HTTP API guards and CLI mutation capabilities.
## Entity: `Daemon`
- Purpose: represent a stable logical identity for a trading daemon process; registered per user; bound to service tokens at issuance; assigned to assets
- Source of Truth: daemons table (added by migration 20260513_0016)
- Lifecycle: created by operator via `pfhub daemon create` -> optionally updated -> deactivated
### Key Fields
- id :: text :: server-generated UUID primary key; stable logical identity across service-token rotates
- owner_user_id :: text :: owning user reference (part of composite unique constraint)
- daemon_slug :: text :: operator-assigned short identifier; unique per owner_user_id
- display_name :: text|null :: human-readable label for the daemon
- is_active :: boolean :: if false, service-token issuance for this daemon is rejected; default true
- created_at :: timestamptz :: registration timestamp
- updated_at :: timestamptz :: last update timestamp
### Uniqueness Constraints
- uq_daemons_owner_slug :: UNIQUE (owner_user_id, daemon_slug) :: one slug per user
### Relationships
- User :: owner_user_id links a daemon to its owning user
- AuthToken :: auth_tokens.daemon_id binds a service token to this daemon (1 token : 1 daemon)
- Portfolio :: portfolios.managed_by_daemon_id assigns an asset to this daemon (1 asset : 1 daemon)
### State Rules
- A daemon must exist and be active before a service token can be bound to it at issuance.
- Deactivating a daemon (is_active=false) blocks new token issuance but does not revoke existing tokens.
- daemon_slug is immutable after creation; only display_name and is_active can be updated.
## Entity: `BrokerCredential`
- Purpose: store Fernet-encrypted broker API credentials per user-broker pair for the trex-basic integration
@@ -204,6 +242,7 @@
## Change Log
- 2026-05-13 KST: bat-010 — REQ-009/023/028: added Entity: Daemon; added portfolios.managed_by_daemon_id; added auth_tokens.daemon_id; updated AuthToken State Rules (runtime_id vs daemon_id distinction, fail-closed policy); updated Portfolio Relationships; updated Model Summary.
- 2026-05-11 KST: bat-008 — REQ-011 AC-2: added portfolios.market column; added Entity: AuthToken (runtime_id field); added Entity: BrokerCredential; added Entity: LedgerTrade; updated Model Summary.
- 2026-05-11 KST: bat-006 — portfolios.portfolio_id changed to server-generated UUID PK; name column added with UNIQUE (owner_user_id, name) constraint; uq_portfolios_owner_name constraint documented; state rules updated.
- 2026-04-30 KST: Bootstrap baseline created from repository observation for initial StagePilot adoption.