feat(kernel): add macro-micro multi-turn AI flow with trace#1404
Draft
nn87200 wants to merge 31 commits intoNoFxAiOS:devfrom
Draft
feat(kernel): add macro-micro multi-turn AI flow with trace#1404nn87200 wants to merge 31 commits intoNoFxAiOS:devfrom
nn87200 wants to merge 31 commits intoNoFxAiOS:devfrom
Conversation
- Add EnableMacroMicroFlow, MacroDeepDiveLimit to strategy config - Add kernel macro phase (BuildMacroBrief, GetMacroDecision, symbols_for_deep_dive) - Add GetFullDecisionMacroMicroWithTrace for multi-turn flow with step trace - Wire macro-micro flow into API (preview-prompt, test-run), backtest, debate - Add replay_only vs macro-micro incompatibility check - Add DecisionStepTrace for UI display of macro/deep-dive/position-check steps - Add MacroDeepDivePromptEditor, multi-step preview and test run UI - Add tests for macro parsing, backtest replay check, API preview shapes, store config
- Fallback used hard-coded 5 symbols, could exceed maxDeepDives - Add fallbackCap = min(5, maxDeepDives) when maxDeepDives > 0 - Add final truncation to maxDeepDives before returning - Add TestRestrictDeepDiveSymbolsToContext_FallbackRespectsMaxDeepDives
- Fix AuthContext malformed register type (parse error) - Fix duplicate 'active' key in translations (rename to strategyActiveSuffix) - Fix TraderConfigModal strategy option label to use strategy.name - Fix strategy-translations.ts first line comment - Fix DecisionCard unused cycleNumber (rename to _cycleNumber) - Add StrategyStudioMacroMicro.test.ts for prompt/test response shapes
…ions - Add Steps column to decision_records (store) - Use GetFullDecisionMacroMicroWithTrace when macro-micro enabled - Populate and persist record.Steps for UI multi-turn display - Add PostgreSQL migration for steps column
- Filter excluded symbols from SymbolsForDeepDive in ValidateAndMergeMacroOutput - Skip excluded symbols when filling from context in restrictDeepDiveSymbolsToContext - Position symbols kept even if excluded (for hold/close decisions) - Add TestValidateAndMergeMacroOutput_ExcludedCoinsFiltered
…chema - Introduce MacroSymbolEntry with symbol, bias, risk, conviction per symbol - Update macro prompts to request per-symbol metadata (bullish/bearish/neutral) - Support both new format (objects) and legacy (string array) in JSON parse - Pass per-symbol metadata to deep-dive prompts for richer context - Add SymbolStrings/NewMacroSymbolsFromStrings helpers for debate engine - Update debate engine to use new schema
…rames - Update logic to fall back to the first valid timeframe if the primary timeframe is not specified or fails normalization. - Log a warning message when the primary timeframe is invalid or unsupported, providing better debugging information.
- Add StopReason to ClaudeClient response structure for better error handling. - Log warnings for truncated responses based on stop and finish reasons, suggesting users to adjust AI_MAX_TOKENS. - Update parsing logic to accommodate new response fields in both ClaudeClient and Client.
…ngle-turn interactions - Modify rendering logic for system and user input prompts to only display when there are no multi-turn steps present. - Enhance clarity in comments to indicate the conditional nature of prompt visibility.
…rames - Update logic to fall back to the first valid timeframe if the primary timeframe is not specified or fails normalization. - Log a warning message when the primary timeframe is invalid or unsupported, providing better debugging information.
- Add StopReason to ClaudeClient response structure for better error handling. - Log warnings for truncated responses based on stop and finish reasons, suggesting users to adjust AI_MAX_TOKENS. - Update parsing logic to accommodate new response fields in both ClaudeClient and Client.
…ngle-turn interactions - Modify rendering logic for system and user input prompts to only display when there are no multi-turn steps present. - Enhance clarity in comments to indicate the conditional nature of prompt visibility.
…nfig checks - Add checks for nil series data in DataFeed to prevent runtime errors. - Ensure strategy config is not nil before proceeding with macro-micro flows in GetFullDecision functions. - Improve error messaging for better debugging in case of missing configurations.
Author
…flow - Add explicit prompt instructions for reasoning on hold/wait - Add extractReasoningFallback when model omits reasoning - Add appendHoldWaitFrom to preserve hold/wait through sizing step - Apply fallback in deep-dive, position-check, and GetSymbolDeepDive
- Set record.CycleNumber from callCount so UI shows correct cycle - Use pos.OpenTime for UpdateTime (entry time for holding duration) - Add Entry time UTC timestamp to macro position brief
…uration to positions - Use cycleNumber+1 instead of callCount for ctx.CallCount in trader prompt (matches record cycle number in UI) - Add EntryTime to store.PositionSnapshot and backtest snapshotPositions - Add precomputed Holding duration and prompt instruction in macro brief (Entry time - Time at top; do not use Runtime)
…time and current open positions - Replace "Draft decisions" section with "Current open positions" that lists each position's details including entry time, quantity, value, and PnL. - Ensure clarity in the prompt by providing a structured overview of open positions before presenting draft decisions.
- Resolve TraderConfigModal: use activeTag (upstream rename from strategyActiveSuffix) - Resolve AuthContext: single-line register return type (upstream) - Resolve translations: activeTag in en/zh/id
- Macro: return raw response from GetMacroDecision for deep-dive context - Deep-dive: include macro AI assessment in user prompt; return raw response for position-check - Position check: include deep-dive responses for open-position symbols in user prompt - Sizing: already receives all merged decisions (no change) - Debate: update GetMacroDecision call sites for 3-value return
- Resolve api/strategy.go: add minimax case from dev, keep single SetAPIKey after switch
…etAPIKey calls - Updated getAIClientForUserModel to set API keys for all providers within their respective cases, removing the redundant call after the switch statement. This enhances code clarity and maintainability.
…isk parameters - Added MinRiskRewardRatio and MinPositionSize to decision validation functions to improve risk management. - Updated user prompts to reflect new margin constraints and detailed explanations for risk-reward ratios, enhancing clarity for users. - Adjusted related functions to accommodate the new parameters, ensuring comprehensive decision-making guidance.
…sizing margin constraint)
…trading decisions - Replaced the previous decision validation method with a new function to filter invalid open_long/open_short decisions, downgrading them to "wait" if they fail risk/reward or size criteria. - Introduced a new function to merge stop loss and take profit values from pre-adjusted decisions into adjusted decisions, ensuring critical parameters are retained. - Updated macro brief generation to use a consistent parameter for OI and NetFlow summaries, improving clarity in reporting. - Adjusted tests to align with the new validation parameters, ensuring comprehensive coverage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.

📝 Description
Adds macro-micro multi-turn AI flow: macro → deep-dives (per symbol) → position check. Supports preview, test run, live trading, backtest, and debate. Single-turn flow unchanged. UI shows per-step prompts when multi-turn is enabled.
🎯 Type of Change
🔗 Related Issues
📋 Changes Made
stepsfor macro-micro; test run runs full flow with traceGetFullDecisionMacroMicroWithTrace, per-symbol bias/risk/conviction in macro outputreplay_onlyincompatible with macro-micro; symbolSeries nil checks🧪 Testing
Test Environment
Manual Testing
Test Results
go test ./...(kernel schema tests may fail pre-existing)go build -o nofxnpm run build🔒 Security Considerations
⚡ Performance Impact
✅ Checklist
Code Quality
go build)go fmtDocumentation
Git
devbranch📚 Additional Notes
Tested on Linux and macOS with Hyperliquid exchange and Gemini/Grok AI providers. Single-turn flow unchanged and backward compatible.