Performs autonomous deep-dive analysis with the Evaluator-Optimizer pattern. Whereas normal stock-skills answer with a single agent invocation, DeepThink autonomously continues the evaluate→improve loop until it converges。
When to use
- "What happens to the PF if Iran reaches a ceasefire?" → Scenario branching + PF impact calculation
- "Propose reinvestment destinations" → Candidate selection + RSI check + scenario validation + PF target matching
- "PF design looking 6 months ahead" → Macro scenarios × sector rotation × currency allocation
Do not use it when normal stock-skills are sufficient.Decisions involving multiple uncertainties use it for.
Harness (mandatory rules)
The following may not be omitted or changed.
⚠️ MUST: Step 2b で GPT / Gemini / Grok + Claude自身 の4者を必ず実行。省略不可。
⚠️ MUST: 不足リストの各項目に「何を → どのLLM/ツールで → なぜ」を付与する。
⚠️ MUST: 収��条件を満たすまで自律的にループを続ける。毎回の承認待ちは不要。
⚠️ MUST: ハーネス上限到達時のみ停止し、ユーザー承認を求める。
Execution flow
Step 0: Start notification + execution plan + wait for approval
Notify the user of the following:
🧠 DeepThinkingモードで分析します
深度: [shallow / medium / deep](max N agents, M LLM calls)
📋 実行プラン:
Step 1: lesson ロード → [テーマに応じた初回分析内容]([使用エージェント])
Step 2: 評価 + 4-Swarm並列レビュー(2層モデル: インフラ固定 + 推論動的割当)
Step 3: 不足があれば追加調査([想定される追加調査内容])
→ 収束するまで Step 2-3 を自律ループ
Step 5: 統合レポート
続けますか? [このまま実行 / プラン修正 / キャンセル]
⚠️ MUST (KIK-735): Before starting Step 1, always pass the preflight gate.
from tools.preflight import run_preflight
result = run_preflight(domain="pf") # PF系テーマ。market/sector/stock も可
if not result["passed"]:
# violations をユーザーに提示し abort
raise SystemExit(f"Preflight failed: {result['violations']}")
This makes it possible to block at the code level unreferenced cash_balance.json / conviction violations / invalid lot_size (prevention of recurrence of the erroneous recommendation incident in the 2026-04-27 PF thorough review).
The execution plan is auto-generated from the theme (zero-shot). Typical examples:
| Theme | Step 1 | Assumed Step 3 |
|---|---|---|
| "Consider reinvestment destinations with the PF" | PF status + market conditions with HC + Researcher | Candidate RSI check, scenario branching |
| "What is the impact of an Iran ceasefire?" | Geopolitical research with Researcher | Sensitivity calculation by PF holding |
| "PF design 6 months later" | Macro research with HC + Researcher | Sector rotation × currency allocation |
Depth selection guide:
- shallow: One additional investigation. Filling minor information gaps (max 3 agents, 5 LLM calls, recommended output ~1500 characters)
- medium: 2-3 evaluate→improve loops. Standard deep dive (max 6 agents, 12 LLM calls, recommended output ~2500 characters)
- deep: Up to 5 loops. Thorough analysis (max 10 agents, 20 LLM calls, recommended output ~4000 characters)
⚠️ Only Step 0 waits for an explicit response from the user. Step 1 onward is an autonomous loop.
- "Execute as is" → go to Step 1
- "Revise the plan" → reflect the user's instructions and present the plan again
- "Cancel" → stop DeepThink and return to normal mode
Available tools
config/tools.yaml Refer to. The function names, roles, and when to use each of all tools are defined.
⚠️ MUST: For themes involving reinvestment, swapping, or candidate selection,screen_stocks() produce candidates in a data-driven way. You must not select manually from the AI's knowledge base.
Step 1: Initial analysis
⚠️ MUST (KIK-738): Load all lessons, then filter_relevant_lessons() extract only those related to the theme.
Reading everything raw leads to formalization (the true root cause of the 2026-04-27 / 2026-04-28 incidents). Explicitly narrow down to only the lessons related to the theme, and reference their content in all subsequent steps.
python3 -c "
import sys; sys.path.insert(0, '.')
from tools.notes import load_notes
from src.data.lesson_enforcer import filter_relevant_lessons
# 1. Lesson 全件 load → ユーザー意図に関連するもののみ抽出(KIK-738 hook)
all_lessons = load_notes(note_type='lesson')
user_input = '<USER_PROMPT_HERE>' # ユーザーの今回の指示文
relevant_lessons = filter_relevant_lessons(user_input, all_lessons)
print(f'=== Lessons {len(relevant_lessons)}/{len(all_lessons)} relevant ===')
for n in relevant_lessons:
print(f'[{n.get(\"date\",\"\")}] trigger={n.get(\"trigger\",\"(none)\")[:60]}')
print(f' expected_action: {n.get(\"expected_action\",\"(none)\")[:100]}')
# 関連 0 件の場合の fallback 戦略:
# (a) 該当 lesson の trigger フィールドが未バックフィル → 直近 10 件で代用
# (b) ユーザー入力が真に新規パターン (どの trigger とも一致しない)
# どちらの場合も直近 10 件にフォールバック。バックフィル完了後 (KIK-738 Phase 2)
# 関連 0 件は (b) を意味するようになる。
if not relevant_lessons:
print('[fallback] no trigger-match → recent 10 of', len(all_lessons))
relevant_lessons = all_lessons[-10:]
# 2. 対象銘柄の thesis/observation(KIK-695)
import csv
with open('data/portfolio.csv') as f:
symbols = [row['symbol'] for row in csv.DictReader(f)]
print(f'\n=== 戦略メモ ===')
for sym in symbols:
notes = load_notes(symbol=sym)
thesis = [n for n in notes if n.get('type') in ('thesis', 'observation')]
if thesis:
print(f'{sym}: {len(thesis)}件')
for n in thesis[:2]:
print(f' [{n.get(\"type\")}] {n.get(\"content\",\"\")[:150]}')
"
relevant_lessons in all subsequent steps. In Step 5's verify_lesson_cited,
this same listis passed to the citation verification (consistency guarantee).
Next, launch the stock-skills agents (Screener / Analyst / Health Checker / Researcher / Strategist). For available agents, see stock-skills routing.yaml .
Step 2: Evaluation (self-evaluation + 3-LLM parallel review + counterargument → replan)
The value of DeepThink is showing the thought process of "why that conclusion was reached."
2a. Self-evaluation
Self-evaluate the results of the initial analysis from the following perspectives:
| Perspective | Check content |
|---|---|
| Information sufficiency | Is the necessary data available? (RSI? Earnings date? Sentiment?) |
| Scenario | Are multiple scenarios considered? (optimistic/pessimistic/neutral) |
| PF consistency | Is it checked against the user's PF composition and targets? |
| Counterargument | Is there a Devil's Advocate perspective? |
| lesson | Does it contradict past lessons? (Refer to the lessons loaded in Step 1) |
2b. 4-Swarm parallel review (⚠️ All 4 are mandatory. Cannot be omitted)
Two-layer model: a Swarm composed of an infrastructure layer (fixed) + an inference layer (dynamic).
The orchestrator launches GPT / Gemini / Grok in parallel, and Claude itself also participates directly in the analysis at the orchestrator layer.
Infrastructure layer (fixed) — capabilities that are physically irreplaceable
| LLM | Fixed role | Reason |
|---|---|---|
| Grok | X/real-time market data acquisition | X Firehose is impossible for other LLMs (hard constraint) |
| Gemini | Google search + large-context reading | Google Search Grounding is impossible for other LLMs (hard constraint) |
Inference layer (dynamic) — assigned to the 4 according to the theme
| Role | Content |
|---|---|
| Devil's Advocate | Counterargument, risk identification, oversight detection |
| Scenario Analyst | Scenario branching, sensitivity analysis, long-term inference |
| Lesson Auditor | Lesson consistency, detection of contradictions with past learning |
| Portfolio Aligner | PF consistency, target matching, currency/region allocation |
Aptitude matrix (used for assignment decisions)
| Role | GPT | Gemini | Grok | Claude |
|---|---|---|---|---|
| Devil's Advocate | Optimal | Weak (too neutral) | Fair | Acceptable |
| Scenario Analyst | Optimal | Strong (long-form inference) | Superficial | Acceptable |
| Lesson Auditor | Acceptable | Optimal(long context) | Acceptable | Strong |
| Portfolio Aligner | Possible | Possible | Possible | Optimal |
⚠️ Confirm hard constraints first, then assign the remaining reasoning roles based on soft constraints (suitability).
Assignment examples by theme
地政学リスク:
Grok = [固定] X市場反応 + [動的] Devil's Advocate
Gemini = [固定] Google検索 + [動的] Scenario Analyst
GPT = [動的] Lesson Auditor
Claude = [動的] Portfolio Aligner
決算分析:
Grok = [固定] X決算反応 + [動的] (補助)
Gemini = [固定] 決算データ検証 + [動的] Lesson Auditor
GPT = [動的] Scenario Analyst
Claude = [動的] Devil's Advocate
PF再設計:
Grok = [固定] X市場評価 + [動的] Sentiment補強
Gemini = [固定] Google検索 + [動的] Scenario Analyst
GPT = [動的] Devil's Advocate
Claude = [動的] Portfolio Aligner
How to invoke
| LLM | How to invoke |
|---|---|
| GPT | call_llm('gpt', 'gpt-5.4', prompt, reasoning='high') |
| Gemini | call_llm('gemini', 'gemini-3-flash-preview', prompt, web_search=True) or call_llm('gemini', 'gemini-3.1-pro-preview', prompt) |
| Grok | tools/grok.py の search_x_sentiment() / search_market() or call_llm('grok', 'grok-4.20-0309-reasoning', prompt) |
| Claude | Execute directly in the orchestrator layer (no Agent launch required) |
2c. Counterargument → Re-plan
Based on the counterarguments from external review, revise or strengthen do:
📊 DeepThink Step 2 完了(Agents: X/Y, LLM calls: A/B)
初回結論: [初回分析の結論]
Swarm 割当: [テーマ名]
GPT = [固定: なし] + [動的: 割当された推論役割]
Gemini = [固定: Google検索] + [動的: 割当された推論役割]
Grok = [固定: X市場データ] + [動的: 割当された推論役割]
Claude = [動的: 割当された推論役割]
反証:
[Devil's Advocate担当LLM]: [反証ポイント]
[Scenario Analyst担当LLM]: [シナリオ分岐]
[Lesson Auditor担当LLM]: [lesson整合性]
[Portfolio Aligner担当LLM]: [PF整合性]
統合結論:
[4者の指摘を踏まえ、オーケストレーターとして統合的に判断した結論]
[「〜は妥当だが、〜の指摘を踏まえて〜に修正する」等]
再プラン:
初回: [修正前の提案]
修正: [修正後の提案]
理由: [どの指摘がどう影響したか]
⚠️ MUST: In the integrated conclusion, explicitly state "how each LLM's points were reflected in the judgment." Do not end with just a list of points.
Evaluation results: Create a gap list (integrate self-evaluation + points from external review).
Convergence conditions(when all of the following are met → proceed to Step 5):
- All 5 evaluation perspectives completed
- No new gaps detected
Termination conditions(if any apply → present the current results + request user approval):
- max_iterations reached
- max_llm_calls reached
- max_wall_time_minutes reached
Step 3: Improvement (Optimizer) — Autonomous execution
Based on the gap list, launch additional agents/tools autonomously .
⚠️ MUST: For each gap item, specify "what → with which LLM/tool → why."
不足: 「Xセンチメント未取得」
→ 何を: UL のX上の投資家評価
→ どのLLM: Grok search_x_sentiment("UL", "Unilever")
→ なぜ: 候補の市場評価を定性的に補完
不足: 「イベントシナリオ未検討」
→ 何を: BOJ/FOMC最新予想
→ どのLLM: Gemini(web_search=True) で検索+推論
→ なぜ: 来週のイベントが候補の短期値動きに影響
不足: 「RSI未確認」
→ 何を: 候補銘柄のRSI(14)
→ どのツール: yahoo_finance.get_price_history + code interpreter
→ なぜ: 過熱圏での購入を回避(lesson参照)
Utilization of multiple LLMs(config/llm_capabilities.yaml (see):
| Use case | Preferred LLM | Reason |
|---|---|---|
| Fact gathering (Google search) | Gemini(web_search=True) | Google Search Grounding (hard constraint) |
| X Sentiment / Real-time | Grok(tools/grok.py) | X Firehose access (hard constraint) |
| Counterargument/risk analysis | GPT(reasoning='high') | Critical thinking/deep reasoning (soft constraint: optimal) |
| Lesson matching/long-text analysis | Gemini-Pro | 1M context (soft constraint: optimal) |
| PF consistency/integrated judgment | Claude (self) | PF context retention/orchestration |
| Thorough investigation (industry coverage) | Gemini Deep Research | Autonomous traversal of 80-160 sources + citations (KIK-731) |
| Multiple stocks/themes in parallel | Grok bulk_x / bulk_web | X firehose parallel/breaking news parallel (KIK-732) |
⚠️ Fix hard constraints (physically impossible) first, then assign reasoning roles based on soft constraints (strengths and weaknesses).
Deep Research / Bulk Search Trigger (KIK-731 / KIK-732)
When the user says "deeply」「thoroughly」「DR で」「settle in", or if the analysis target spans >5 stocks / >3 themes, propose the following in Step 3:
🔍 Deep Research を起動できます
・gemini.deep_research: Web 徹底調査(80-160 sources、推定 $2.5、5-10分)
→ 業界全体像・規制動向・SEC等
・grok.bulk_x_search: X並列センチメント(推定 $0.5-2.5、~30秒)
→ 投資家センチメント・$cashtag・速報
実行しますか? [y/skip]
User y . After completion, record in the Layer 4 footer:
💰 cost=$X.XX | 📚 sources=N | ⏱ duration=Xs
config/tools.yaml の provider / when / strength / not_for でDistinguish use cases:
- Web coverage →
gemini.deep_research(Google Search Grounding) - In-X data →
grok.bulk_x_search(X firehose exclusive) - Breaking news parallel →
grok.bulk_web_search
Hard constraints: deepthink_limits.yaml の tool_limits Sections (DR 10 times/month/$30, bulk 20 times/month/$10, combined $50).
DEEPTHINK_DR_ENABLED=off DR stops immediately.
Step 4: Checkpoint (report only — not awaiting approval)
Give the user an interim report of the improvement results.After reporting, if there are deficiencies, autonomously return to Step 2.
Strictly follow the format below. Do not omit or change anything.
📊 DeepThink Step N/M 完了(Agents: X/Y, LLM calls: A/B)
中間結果:
- [発見1]
- [発見2]
- [発見3]
不足: [残りの不足リスト or "なし(収束)"]
→ 自律続行: [次にやること] / 収束: Step 5 へ
The user Only when you want to stop intervene. If nothing is said, continue the autonomous loop. Stop only when the user says "stop" or "change direction".
Step 5: Integrated Report
⚠️ MUST (KIK-735): If it includes buy/sell, trim, or sell proposals, re-verify with preflight immediately before Step 5.
from tools.preflight import run_preflight
proposed = [("trim", "NVDA", 3), ("sell", "AMZN", 10)] # 例
result = run_preflight(domain="pf", proposed_actions=proposed)
if not result["passed"]:
# conviction 違反 / lot_size 不正 → 推奨を出力前に修正
raise SystemExit(f"Preflight failed at Step 5: {result['violations']}")
⚠️ MUST (KIK-738): Verify that the relevant_lessons extracted in Step 1 isquoted verbatimin the final proposal text.
Zero citations is a typical pattern of "lesson becoming a mere formality" (2026-04-27 retraction log / 2026-04-28 META recommendation mistake). Before outputting Step 5, always execute the following, and if the lesson is not cited,rewrite:
from src.data.lesson_enforcer import verify_lesson_cited
final_proposal_text = "<エグゼクティブサマリー + Swarm 統合 + 詳細 の本文>"
ok, missing_lesson_ids = verify_lesson_cited(final_proposal_text, relevant_lessons)
if not ok:
# missing_lesson_ids の lesson から expected_action / key_kpis を抜き出して、
# エグゼクティブサマリー本文に組み込んで再生成。
raise SystemExit(
f"Step 5 lesson citation failed: {missing_lesson_ids} are not cited in proposal. "
"提案テキストに該当 lesson の expected_action/key_kpis を逐語引用してから再出力すること。"
)
In addition,if Deep Research / bulk_search was executed, cross-check whether the DR's "rejected" ticker list has been mixed into the final proposal:
import re
# DR レポート本文 (Step 3 で取得した text) から不採用銘柄を動的抽出。
# 規則: 「見送り」「不採用」「除外」「除く」「リジェクト」を含むセクション内の
# ティッカー風トークン (大文字 2-5 文字 or 4桁.T/.Tの日本株コード) を拾う。
def _extract_dr_rejected(dr_text: str) -> list[str]:
if not dr_text:
return []
pattern = r"(?:見送り|不採用|除外|除く|リジェクト|reject)[^\n]{0,400}"
rejected: set[str] = set()
for match in re.finditer(pattern, dr_text):
sect = match.group(0)
for sym in re.findall(r"\b([A-Z]{2,5}|\d{4}\.T)\b", sect):
rejected.add(sym)
return sorted(rejected)
dr_text = "<Step 3 で取得した DR 本文 (出力テキスト全体)>"
dr_rejected = _extract_dr_rejected(dr_text) # 例: ["META", "VST", "TSM"]
for sym in dr_rejected:
# plan に登場するが「DR 不採用」「DR rejected」のような明示的な逆論証も同時に
# 含まれていなければ abort
if sym in final_proposal_text and not re.search(
rf"{sym}.{{0,80}}(不採用|rejected|見送り)", final_proposal_text
):
raise SystemExit(
f"DR cross-check failed: '{sym}' is in DR rejected list but is "
"referenced in the proposal without explicit rejection rationale. "
"DR で不採用判定された銘柄を組み入れるなら、その逆論拠を明示すること。"
)
_extract_dr_rejected() is a best-effort extraction that depends on the DR report format.
If DR changes to a new format, extend the regular expression. For tests, there are
tests/data/test_lesson_enforcer.py::TestStep5HookScenarios matching patterns in
⚠️ MUST (KIK-739): Immediately before outputting the proposal, generate Layer 5 (Cited Sources) and append it to the end of the body.
With "visualization of the notes relied upon + freshness markers," prevent old information from becoming stale garbage (response to the issues discovered in the 2026-04-28 session: "lessons are not cited" and "ATH approach is missed").
from src.data.citation_formatter import format_cited_sources
# verify で実際に引用済みと判定された lessons を citation 候補に
cited_lessons = [l for l in relevant_lessons if l.get("id") not in missing_lesson_ids]
# 対象銘柄の thesis (Step 1 でロード済) のうち、提案文中に symbol が登場するものを cited に
cited_theses = [
t for t in all_theses
if (t.get("symbol") or "") and t["symbol"] in final_proposal_text
]
# 各引用ノートが提案のどこに使われたか 1 行でメモ。
# key は note['id'] (実際の保存形式: e.g. 'note_2026-04-24_portfolio_a1b2c3d4')
used_for_map = {
cited_lessons[0]["id"]: "Cash 15-20% 判定",
cited_lessons[1]["id"]: "売却対象除外",
# ... 各 cited_lessons / cited_theses から id を引いてマッピング
}
citation_block = format_cited_sources(
cited_lessons, cited_theses, used_for_map=used_for_map,
)
final_proposal_text = final_proposal_text.rstrip() + "\n\n" + citation_block
format_cited_sources freshness marker rules:
permanenttag → 🟢 (always fresh, permanent rule)seasonal(or no tag) → 0-30 days 🟢 / 31-90 days 🟡 / 91 days+ 🔴expired→ automatically excluded from output- conviction_override in thesis → 🔒 (ignore freshness)
Zero citations is a typical case of lesson becoming a mere formality (the pattern in the 2026-04-27 retraction log) — since verify_lesson_cited above aborts, by the time you reach here there is always at least 1 citation.
Output in a 3-part structure with the executive summary first (summary, integration of discussion, details).
Strictly follow the format below. Do not omit or change anything.
■ エグゼクティブサマリー
[結論を3-5行で。推奨アクション + 根拠の要点 + 主要な数値]
■ Swarm 議論の統合
[4者の指摘を踏まえた統合的な判断理由]
- [LLM-A]は「〜」と指摘 → [採用/却下/部分採用]した理由
- [LLM-B]は「〜」と分析 → [結論にどう反映したか]
- [LLM-C]は「〜」を報告 → [判断にどう影響したか]
- Claude(自身)は「〜」と評価
→ これらを総合し、[最終的な判断根拠]
■ 詳細
シナリオ分析:
[楽観/中立/悲観の確率と影響]
ポートフォリオ影響:
[具体的な数値変化]
根拠データ:
[使用した指標・ソース]
推奨アクション:
[具体的なアクションリスト(「何もしない」を含む)]
⚠️ MUST: Make it granular enough to judge from the executive summary alone. The details are the basis for "why you judged that way." ⚠️ MUST: In the integration of the Swarm discussion, present each LLM's points along with a judgment of "adopt/reject/partially adopt." Do not end with just a list of points.
Harness constraints
deepthink_limits.yaml to prevent runaway:
- When the upper limit is reached: stop the loop → present the current results → User approval is required to continue
- Progress is displayed at each step: “Agents 4/6, LLM calls 8/12”
Progress display format
Follow this format strictly. Do not omit or change anything.
At step start:
🔍 DeepThink Step N: [ステップ名]
[実行中のLLM/ツール名] で [何をしているか]...
At step completion:
✅ DeepThink Step N 完了
発見: [主要な発見を1-2行]
次のステップ: [次にやること]
References
- Harness constraints: deepthink_limits.yaml
- LLM selection: llm_capabilities.yaml
- Normal mode: stock-skills SKILL.md