"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(skills): add investor lenses as stackable overlays
Haozhe Wu701808322300
diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 3dc98ddf8..10cd5464b 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -1,7 +1,7 @@---name: vibe-tradingversion: 0.1.13-description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 88 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 24 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).+description: Professional finance research toolkit — backtesting (9 engines + benchmark comparison panel), factor analysis, Alpha Zoo (462 pre-built alphas across qlib158/alpha101/gtja191/academic/fundamental), options pricing, 89 finance skills, 30 multi-agent swarm teams, Trade Journal analyzer, and Shadow Account (extract → backtest → render) across 24 market-data sources (tushare, yfinance, okx, binance, akshare, baostock, tencent, mootdx, ccxt, futu, mt5, local, eastmoney, sina, stooq, yahoo, pykrx, india_broker, qveris, longbridge, plus optional-key finnhub/alphavantage/tiingo/fmp).dependencies:python: ">=3.11"pip:@@ -23,7 +23,7 @@ mcp:# Vibe-Trading-Professional finance research toolkit with AI-powered backtesting (9 engines), multi-agent teams, 88 specialized skills, the **Alpha Zoo** (462 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.+Professional finance research toolkit with AI-powered backtesting (9 engines), multi-agent teams, 89 specialized skills, the **Alpha Zoo** (462 pre-built quantitative alphas across qlib158 / alpha101 / gtja191 / academic / fundamental with one-line CLI benchmarking), and the Shadow Account loop — extract your implicit trading rules from a journal, backtest them across A股/港股/美股/crypto, then see where they would have served you better.## Setup@@ -53,7 +53,7 @@ Add to your agent's MCP config:### API Key Requirements-Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (462 pre-built alphas), and all 88 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.+Core research MCP tools work with zero API keys for HK/US/crypto. After `pip install`, backtesting, market data, factor analysis, options pricing, chart patterns, web search, document reading, trade journal analysis, shadow-account extraction/backtest/report, the Alpha Zoo (462 pre-built alphas), and all 89 skills are ready to use. IBKR tools require a local TWS / IB Gateway session; `run_swarm` requires an LLM key.| Feature | Key needed | When ||---------|-----------|------|@@ -134,7 +134,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.| Tool | Description | API Key ||------|-------------|---------|-| `list_skills` | List all 88 finance skills | None |+| `list_skills` | List all 89 finance skills | None || `load_skill` | Load full skill documentation | None || `start_research_goal` | Create an auditable research goal | None || `get_research_goal` | Read the current research goal | None |@@ -198,7 +198,7 @@ Use `load_skill(name)` to access full methodology docs with code templates.pip install vibe-trading-ai```-That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 88 skills immediately.+That's it — no API keys needed for HK/US/crypto markets. Start using `backtest`, `get_market_data`, `analyze_options`, `analyze_trade_journal`, `extract_shadow_strategy`, `web_search`, the **Alpha Zoo** (`vibe-trading alpha bench --zoo gtja191 --universe csi300 --period 2018-2025`), and all 89 skills immediately.## Loading Tools from External MCP Serversdiff --git a/agent/src/skills/investor-lenses/SKILL.md b/agent/src/skills/investor-lenses/SKILL.mdnew file mode 100644index 000000000..85bb86d52--- /dev/null+++ b/agent/src/skills/investor-lenses/SKILL.md@@ -0,0 +1,141 @@+---+name: investor-lenses+description: Named investor reasoning frameworks packaged as reusable analytical lenses — 12 lenses (deep value, quality franchise, inversion, scuttlebutt growth, GARP, cycle positioning, debt cycle, forensic short, cost drag, right-business, weak-system contrarian, three questions) that stack on top of evidence already gathered, each with ordered priority signals, hard disqualifiers, and documented failure modes.+category: analysis+---++# Investor Lenses++## What a lens is++A lens is a **reasoning procedure**: a fixed, ordered set of questions plus explicit+veto rules, distilled from one investor's publicly published methodology. It is+applied *after* the evidence exists — it does not gather data and does not care+where the data came from.++The value of a lens is that it is **opinionated and therefore falsifiable**. A lens+tells you, before you look at the answer, which signals it ranks first and which+facts make it walk away. Two lenses disagreeing on the same evidence is the+product, not a bug: the disagreement localizes exactly which assumption the+decision rests on.++## What a lens is NOT++- **Not investment advice.** Every lens output is an analytical exercise.+- **Not the named person's opinion.** Each lens is a reconstruction, in our own+ words, of a methodology that investor has described publicly. It is not written+ by them, not endorsed by them, and may diverge from what they would say today.+- **Not a universal truth test.** A lens verdict is conditional on the lens.+ "Fails the Graham lens" and "bad investment" are different statements.+- **Not a ranking of masters.** No lens is more correct than another; each has a+ domain where it is sharp and a domain where it is reliably wrong.++## The five-step run++1. **Freeze the evidence.** Write down what is known *before* choosing the lens —+ financials, prices, disclosures, timelines. A lens applied to evidence collected+ after the lens was chosen is circular.+2. **Choose by the situation, never by the answer you want.** Use the selection+ table below. If you are picking the lens because you already know its verdict,+ stop.+3. **Walk the priority signals in order.** Each lens orders its signals for a+ reason. Do not jump to the signal you have the best data on.+4. **Hit a hard disqualifier → stop and report the veto.** Disqualifiers are not+ weighted against positives. They end the run under that lens.+5. **Run the misuse check, then emit under the output contract.** Every lens file+ lists the regimes where it fails. State explicitly whether the current case sits+ in one of them.++## Lens index++| Lens | Style | Sharpest on | Blindest on | File |+| --- | --- | --- | --- | --- |+| Statistical deep value (Graham) | Value / balance sheet | Cheap, boring, asset-heavy, wide-basket | Asset-light compounders; single names | [graham-deep-value](investor-lenses/references/graham-deep-value.md) |+| Quality franchise (Buffett) | Quality / durability | Durable consumer & toll-road economics | Fast-changing tech; deep cyclicals | [buffett-quality-franchise](investor-lenses/references/buffett-quality-franchise.md) |+| Inversion (Munger) | Risk / pre-mortem | Finding the way this dies | Sizing an opportunity; timing | [munger-inversion](investor-lenses/references/munger-inversion.md) |+| Scuttlebutt growth (Fisher) | Growth / qualitative | Product & channel truth vs. reported numbers | Anything you cannot reach people about | [fisher-scuttlebutt](investor-lenses/references/fisher-scuttlebutt.md) |+| GARP by category (Lynch) | Growth at a price | Mid-cap earnings compounding; retail-visible businesses | Financials; commodity cyclicals | [lynch-garp](investor-lenses/references/lynch-garp.md) |+| Cycle positioning (Marks) | Contrarian / risk-first | Where we are in the greed–fear cycle | Single-company fundamentals | [marks-cycle-position](investor-lenses/references/marks-cycle-position.md) |+| Debt cycle & uncorrelated bets (Dalio) | Macro / allocation | Rates, currency, liquidity regime; portfolio shape | Stock picking | [dalio-debt-cycle](investor-lenses/references/dalio-debt-cycle.md) |+| Forensic short (Chanos) | Short / accounting | Accounting distortion, value traps, structural decline | Longs; anything you must be right about *soon* | [chanos-forensic-short](investor-lenses/references/chanos-forensic-short.md) |+| Cost drag & mean reversion (Bogle) | Allocation / cost | Whether the *activity itself* is worth its cost | Individual security selection | [bogle-cost-drag](investor-lenses/references/bogle-cost-drag.md) |+| Right business, right people (Duan Yongping / 段永平) | Quality / concentration | Founder-led A-share, HK and US-listed China names | Diversified baskets; turnarounds | [duan-right-business](investor-lenses/references/duan-right-business.md) |+| Weak-system contrarian (Feng Liu / 冯柳) | Contrarian / positioning | A-share names beaten down by known bad news | Momentum regimes; names with unresolved fraud risk | [fengliu-weak-system](investor-lenses/references/fengliu-weak-system.md) |+| Three questions (Qiu Guolu / 邱国鹭) | Value / industry structure | A-share and HK industry structure and pricing power | Early-stage, structure-not-yet-formed industries | [qiuguolu-three-questions](investor-lenses/references/qiuguolu-three-questions.md) |++## Choosing a lens++| Situation | Start with | Then stack |+| --- | --- | --- |+| "Is this cheap enough?" on an asset-heavy or out-of-favour name | Graham | Munger, Qiu Guolu |+| "Is this a great business?" on a stable franchise | Buffett | Duan Yongping, Munger |+| "The story is wonderful, is it real?" | Fisher | Chanos, Munger |+| "It's grown 5 years, is the multiple sane?" | Lynch | Buffett, Qiu Guolu |+| "Is the market euphoric or despairing right now?" | Marks | Dalio |+| "What does the rates / currency / liquidity regime do to this?" | Dalio | Marks |+| "The accounting smells" | Chanos | Munger, Fisher |+| "Should we be picking at all, or just allocating?" | Bogle | Marks |+| A-share name down 50% on known bad news | Feng Liu | Chanos, Qiu Guolu |+| A-share / HK industry with consolidating competitive structure | Qiu Guolu | Buffett, Duan Yongping |+| Founder-controlled company, governance is the swing factor | Duan Yongping | Munger, Chanos |++## Stacking protocol++Stacking is where lenses earn most of their value, but only under discipline.++- **Two or three lenses. Never more.** Beyond three the output degenerates into a+ survey and the disagreements stop being legible.+- **Choose lenses that can actually disagree.** Buffett + Duan Yongping mostly+ agree by construction; that stack is decoration. Buffett + Chanos, or Feng Liu ++ Munger, produce real tension.+- **Run each lens independently before comparing.** Do not let lens 2 read lens 1's+ verdict. Cross-contaminated lenses collapse into one lens.+- **Classify every disagreement** into exactly one root cause:+ - *Horizon* — same facts, different holding period (10-year certainty vs. next+ two quarters).+ - *Caliber* — the two lenses are measuring different quantities (owner earnings+ vs. reported net income; EV vs. market cap).+ - *Risk preference* — same expected value, different tolerance for the left tail.+ - *Information* — one lens needs a fact nobody has. Say which fact.+- **Never average the verdicts.** A 2-to-1 split among lenses is not evidence of+ anything; lenses are not voters and they are not independent samples. Report the+ split and its root cause instead.+- **Report the losing lens's strongest point verbatim.** If it cannot be stated+ fairly, the stack was not run honestly.++## Anti-patterns++- **Lens shopping** — running lenses until one agrees with the pre-existing+ conclusion, then reporting only that one. If a lens is run, it is reported.+- **Lens as authority** — "Buffett would buy this" is a claim about a person and is+ unsupportable. "Under a quality-franchise lens, this passes the moat test and+ fails the price test" is a claim about a procedure and is checkable.+- **Biography instead of procedure** — quoting temperament, anecdotes or life story+ in place of walking the signal list.+- **Silent disqualifier** — noticing a hard veto and continuing to score anyway+ because the rest of the picture is attractive.+- **Lens applied out of market** — a US-designed lens dropped onto an A-share name+ without adjusting for what the disclosure regime actually reveals. Each lens file+ carries a market-fit note; read it.+- **Retrofitting the evidence** — going back to collect exactly the data the chosen+ lens rewards, after choosing the lens.++## Output contract (binding on every lens)++Any output produced under this skill must contain, in this order:++1. **Lens name and one-line statement of what it optimizes for.**+2. **Verdict, explicitly framework-conditional** — phrased "under this framework,+ …", never as a flat assertion about the security.+3. **The ordered signal walk** — each priority signal, the evidence found, and+ whether it passed. Missing evidence is written as *missing*, never inferred.+4. **Disqualifier check** — every hard veto listed and marked triggered / not+ triggered / unknown.+5. **Misuse check** — whether the current case sits in a regime where this lens is+ documented to fail.+6. **Falsifiers** — the two or three observations that would flip the verdict, each+ concrete enough that someone could go check it.+7. **Confidence with its limiting factor** — "medium, limited by the absence of+ segment-level disclosure", not a bare number.+8. **The standing disclaimer**: this is an analytical framework, not investment+ advice, and the verdict is conditional on the framework used.diff --git a/agent/src/skills/investor-lenses/references/bogle-cost-drag.md b/agent/src/skills/investor-lenses/references/bogle-cost-drag.mdnew file mode 100644index 000000000..a8a9b1a60--- /dev/null+++ b/agent/src/skills/investor-lenses/references/bogle-cost-drag.md@@ -0,0 +1,114 @@+---+name: bogle-cost-drag+lens: Cost Drag and Mean Reversion+attributed_to: John Bogle+style: allocation+markets: Any market; the lens is about the activity and its costs, not about a security+description: Subtract every cost from the gross return before judging any strategy, assume returns revert toward their long-run drivers, and ask whether the activity beats the passive alternative after all frictions.+---++# Cost Drag Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Keeping the return that the underlying asset actually produces. Its one structural+claim is that costs are certain and compounding while excess return is uncertain+and mean-reverting, so the cost side deserves the first and most precise+examination. It is the lens that asks whether the *whole exercise* is worth doing.++## Market-fit note++- Cost structures differ sharply by market and must be enumerated locally: A-share+ stamp duty on sales, exchange and settlement fees, and the bid-ask on small caps;+ HK stamp duty on both sides plus trading and settlement levies; US commission-free+ equity trading where the cost has moved into spread and order routing; crypto+ taker fees, funding and slippage that can dwarf everything else.+- Turnover is the multiplier on all of it. A strategy's cost is a function of how+ often it trades, not of its headline fee.++## Priority signals (walk in this order)++1. **Enumerate every cost, not just the visible one.**+ - explicit: management fee, performance fee, custody, commission+ - transaction: bid-ask spread, market impact, exchange and clearing fees+ - statutory: stamp duty, transaction tax, withholding on dividends+ - hidden: cash drag, turnover-induced tax realization, borrow cost, financing+ spread on leverage, currency conversion+2. **Convert cost to an annual drag** using actual turnover. Gross return minus the+ annualized all-in drag is the only number worth comparing.+3. **Name the passive benchmark** the activity must beat: the cheapest reachable+ broad exposure to the same risk. Every comparison in this lens is against that+ alternative, net of its own costs.+4. **Compound the drag over the holding horizon.** A drag that looks trivial per+ year is not trivial over a decade; state the terminal-value difference, not the+ annual one.+5. **Discount past outperformance toward the mean.** Assume a large part of any+ historical excess return is unrepeatable. Ask what would remain if the excess+ halved — is the activity still worth its cost?+6. **Decompose the return into its sources.** For equities: dividend yield, earnings+ growth, and change in valuation multiple. The multiple-change component is the+ speculative part and should not be extrapolated.+7. **Behavioural cost.** Estimate the gap between the strategy's time-weighted+ return and the investor's likely money-weighted return. Strategies that invite+ trading at the wrong moments carry a real cost that never appears in a fee table.++## Disqualifiers (hard vetoes)++- **Gross returns compared to a net benchmark**, or costs quoted as a headline fee+ with turnover-driven costs omitted.+- **No passive alternative named.** Without the alternative there is no test.+- **Excess return extrapolated at its historical rate** with no mean-reversion+ haircut applied.+- **Return attributed mostly to multiple expansion** and then projected forward.+- **All-in drag exceeding the plausible excess return** — under this lens that is a+ decisive no, independent of how attractive the strategy looks.++## Scoring rubric++| Item | Value |+| --- | --- |+| Gross expected return | stated |+| All-in annual drag (turnover-adjusted) | stated |+| Net expected return | gross − drag |+| Passive alternative, net | stated |+| Net advantage | difference |+| Net advantage after halving the excess | difference |++If the last row is not positive, the lens returns no.++## Typical misuse++- **Used to evaluate a single security.** It has nothing to say about whether a+ company is good; it evaluates activities, strategies and vehicles.+- **Read as "indexing always wins".** The lens is an arithmetic test. In markets or+ segments with high dispersion and low-cost access to skill, the test can pass.+ Run the arithmetic; do not assume the conclusion.+- **Cost minimization at the expense of exposure correctness.** The cheapest vehicle+ tracking the wrong exposure is worse than a costlier one tracking the right+ exposure. Fix the exposure first, then minimize its cost.+- **Ignoring capacity and liquidity.** A cheap fund in an illiquid segment pays its+ cost through tracking error and spread instead of through the fee line.+- **Applied to genuinely uncorrelated return streams as if they were substitutes.**+ A hedge that reduces portfolio risk can be worth a negative expected return; this+ lens's arithmetic does not price that and will reject it wrongly.++## Falsifiers++- The measured all-in drag comes in materially below the estimate after a full year+ of real turnover → the cost model was wrong and the verdict must be recomputed.+- The excess return persists at full magnitude across an independent later period,+ with the same process → the mean-reversion haircut was too severe for this case.+- The passive alternative fails to track its own exposure → the benchmark was not+ actually reachable and the comparison is void.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+cost-drag framework, …", show the full cost enumeration with turnover, name the+passive alternative, and report both the net advantage and the net advantage after+halving the assumed excess. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/buffett-quality-franchise.md b/agent/src/skills/investor-lenses/references/buffett-quality-franchise.mdnew file mode 100644index 000000000..f2a16cb7a--- /dev/null+++ b/agent/src/skills/investor-lenses/references/buffett-quality-franchise.md@@ -0,0 +1,120 @@+---+name: buffett-quality-franchise+lens: Quality Franchise+attributed_to: Warren Buffett+style: quality+markets: US, HK and A-share large caps with long operating histories; requires a decade of comparable financials+description: Judge whether a business has a durable economic franchise, whether its true owner earnings are real cash, and only then whether the price leaves a margin of safety.+---++# Quality Franchise Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Owning a business whose competitive position is still intact in ten years, bought+at a price where an average outcome is acceptable. Durability is ranked above+growth rate, and both are ranked above cheapness.++## Market-fit note++- Needs ten years of comparable financials. A company with three years of history+ cannot be assessed under this lens, whatever its quality.+- In A-shares and HK, the moat question is often really a *policy* question:+ licences, pricing approval, distribution control. Name the source of the moat+ precisely rather than calling it "brand".+- State-influenced pricing (utilities, telecoms, healthcare procurement) caps+ franchise economics regardless of market share — treat administered pricing as a+ ceiling on the moat, not a moat.++## Priority signals (walk in this order)++1. **Explainability.** Can the business model be stated in two sentences, including+ who pays, for what, and why they cannot easily stop? If not, the lens stops here+ — this is the circle-of-competence gate, and it is a gate, not a score.+2. **Source of the moat, named specifically.** Exactly one of: switching cost,+ network effect, intangible asset (brand or licence), cost advantage, or efficient+ scale in a small market. "Good management" and "first mover" are not moats.+3. **Moat evidence in the numbers.** Ten-year gross margin stability, pricing taken+ above input inflation, ROIC persistently above cost of capital, market share+ stable or rising *without* rising sales-and-marketing intensity. A moat that does+ not show up in margins or returns is a story.+4. **Moat direction.** Widening, flat, or narrowing — with the specific evidence.+ A narrowing moat at a low multiple is the classic trap this lens is meant to+ avoid.+5. **Owner earnings, not reported earnings.** Net income, plus depreciation and+ amortization, minus the capital expenditure genuinely required to hold the+ current competitive position. Separate maintenance capex from growth capex+ explicitly; if the split cannot be estimated, say so and widen the value range.+6. **Capital allocation record.** What management did with a decade of retained+ earnings: incremental return on retained capital, acquisition track record,+ buybacks executed above or below intrinsic value, dilution history.+7. **Price against a value range.** Value the owner-earnings stream under+ conservative, base and optimistic assumptions. The margin of safety is the+ discount to the *conservative* case, not the base case.++## Disqualifiers (hard vetoes)++- **Business not explainable in two sentences** — outside the circle of competence.+- **Moat cannot be named as a specific mechanism**, or the named mechanism is+ contradicted by margin and share trends.+- **Owner earnings persistently below reported net income** across a full cycle:+ the earnings are accounting, not cash.+- **Capital-intensive growth that does not raise returns** — capex rising, ROIC+ flat or falling. Growth here destroys value.+- **Management demonstrably not shareholder-aligned** — serial dilution at+ depressed prices, related-party transfers, repeated restatements.+- **Only the optimistic case clears the price.** No margin of safety means no+ position under this lens, regardless of business quality.++## Scoring rubric++| Gate | Pass condition |+| --- | --- |+| Understandable | Two-sentence model, stated |+| Moat named | One specific mechanism, with margin/share/ROIC corroboration |+| Moat direction | Not narrowing |+| Owner earnings | Positive, cash-backed, ≥ reported net income across the cycle |+| Capital allocation | Incremental ROIC on retained earnings above cost of capital |+| Price | Discount to the conservative-case value, stated in % |++Any gate failing ends the run. There is no compensating high score.++## Typical misuse++- **Applied to fast-changing technology.** The ten-year durability question cannot+ be answered where the competitive basis resets every product cycle; the lens will+ either refuse everything or manufacture false confidence.+- **Applied to deep cyclicals.** Peak-cycle earnings look like franchise economics.+ Trough-cycle earnings look like moat erosion. Use a cycle lens to set the+ normalized earnings level first.+- **Moat asserted from market share alone.** Share bought with promotion spending+ is the opposite of a moat; check whether margins held while share rose.+- **Quality used to excuse any price.** "Wonderful business" is a reason to accept+ a fair price, not an unbounded one. If the multiple assumes decades of the current+ growth rate, the durability judgement is doing work it cannot support.+- **Maintenance capex guessed conveniently.** Understating it turns almost any+ capital-intensive business into a cash machine. If it is a guess, the valuation+ range must widen accordingly.+- **Retroactive moat.** Explaining historical returns by inventing a moat after the+ fact. The mechanism must predict something, not just describe the past.++## Falsifiers++- Gross margin compresses for two consecutive years while volumes hold → pricing+ power is gone, and the moat premise fails regardless of share.+- A new entrant reaches meaningful share without matching the incumbent's cost base+ → the cost advantage was scale-dependent and is now contestable.+- Incremental ROIC on the last five years of retained earnings falls below cost of+ capital → the compounding assumption in the valuation is void.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+quality-franchise framework, …", name the moat mechanism explicitly, and give the+maintenance-vs-growth capex split you assumed. This is analysis, not investment+advice.diff --git a/agent/src/skills/investor-lenses/references/chanos-forensic-short.md b/agent/src/skills/investor-lenses/references/chanos-forensic-short.mdnew file mode 100644index 000000000..d0cc1ee8f--- /dev/null+++ b/agent/src/skills/investor-lenses/references/chanos-forensic-short.md@@ -0,0 +1,123 @@+---+name: chanos-forensic-short+lens: Forensic Short+attributed_to: Jim Chanos+style: short+markets: Any market with mandatory periodic filings; hardest where filings are sparse or borrow is unavailable+description: Look for businesses whose reported economics diverge from their cash economics, whose model is structurally impaired, or whose accounting choices are doing the work — and treat borrow, timing and crowding as first-class parts of the judgement.+---++# Forensic Short Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework. It describes an analytical procedure; it is not a recommendation to+> take any position, and short exposure carries unbounded loss.++## What this lens optimizes for++Detecting the gap between what a business reports and what it actually earns in+cash, and separating "expensive" from "impaired". Its most useful output is often+applied to a *long* candidate as a quality screen, not to short anything.++## Market-fit note++- Depends on filing quality. US filings support the full procedure; A-share and HK+ disclosure supports much of it but with fewer segment and related-party details,+ and audit-quality dispersion is wider.+- Structural constraints matter and are part of the analysis, not an afterthought:+ in A-shares securities lending is limited and mechanically constrained; in HK+ borrow exists but can be recalled; single-name shorting may be restricted or+ impossible. A thesis that cannot be expressed is still useful as a *warning*, and+ must be labelled as such.++## Priority signals (walk in this order)++1. **Cash versus accrual divergence.** Cumulative operating cash flow versus+ cumulative net income over three to five years. Persistent divergence is the+ single highest-yield signal in this lens.+2. **Where the divergence lives.** Receivable days, inventory days, payable days,+ deferred and unbilled revenue, capitalized costs (development, customer+ acquisition, interest), and changes in useful-life or depreciation assumptions.+ Name the line item.+3. **Revenue recognition mechanics.** Gross versus net presentation, timing of+ recognition, channel versus end-customer sell-through, bill-and-hold, vendor+ financing of customers, and any revenue that depends on a related party.+4. **Structural impairment of the business model.** Is the end market being+ substituted away? Are unit economics negative at scale and only survivable while+ external capital is cheap? Is the business regulated into a shrinking box?+5. **Serial acquisition as an earnings engine.** Roll-ups that grow reported+ earnings through purchase accounting, restructuring charges treated as+ non-recurring every year, and organic growth that is never disclosed separately.+6. **Financing dependence.** Does the business require continuous external capital?+ Map the maturity wall, covenant headroom, and what happens to the model if+ financing cost rises by several hundred basis points.+7. **Incentives and governance.** Compensation tied to non-GAAP measures the+ company itself defines, auditor changes, CFO turnover, late filings, material+ weaknesses, unusual related-party dealings.+8. **Only now: valuation.** Expensive is not a thesis. Valuation determines the+ size of the potential gap, never its existence.+9. **Expressibility and crowding.** Borrow availability and cost, days-to-cover,+ short interest as a share of float, index and passive ownership, and whether the+ company can issue equity into strength. A correct thesis in a crowded, costly,+ recallable position can still lose entirely.++## Disqualifiers (hard vetoes)++- **"It's overvalued" as the entire case.** Multiple compression alone is not a+ forensic thesis and has no timing anchor.+- **No identified mechanism** — a bad smell with no specific line item, no specific+ policy choice, and no specific cash-versus-accrual gap.+- **The catalyst is unbounded in time** while the cost of carry is real: borrow+ cost, dividends, and the possibility of recall.+- **Unbounded upside risk with no defined exit** — the loss profile is asymmetric+ against the holder, and this lens treats an undefined exit as a veto.+- **Position not expressible in the relevant market** — must be re-labelled as a+ long-side warning rather than a short thesis.++## Scoring rubric++| Layer | Question | Weight |+| --- | --- | --- |+| Accounting | Is reported profit backed by cash? | Necessary |+| Structural | Is the business model impaired, not just mature? | Necessary |+| Financing | Does it need capital it may not get? | Strengthening |+| Governance | Do incentives reward the distortion? | Strengthening |+| Valuation | How large is the gap if it closes? | Sizing only |+| Expressibility | Can the view be held long enough to be right? | Gate |++Both "necessary" layers must be present. Valuation never substitutes for either.++## Typical misuse++- **Applied to a merely mature business.** Slow growth is not impairment; the lens+ will manufacture a thesis out of ordinary decline if allowed.+- **Accounting conservatism read as fraud.** Aggressive is not fraudulent, and+ policy differences across jurisdictions produce false positives.+- **Ignoring the borrow and the crowd.** Being right after being forced out is+ indistinguishable from being wrong.+- **Confirmation cascade.** Once a short thesis is formed, every data point reads as+ supporting it. Require a written falsifier list before any further evidence is+ gathered.+- **Used on a long book without translation.** As a long-side screen it should+ produce "avoid" or "reduce confidence", not a mirror-image conviction.+- **Publishing the thesis as fact.** Forensic findings are hypotheses about+ accounting choices; state them as such, with the exact filing reference.++## Falsifiers++- Operating cash flow converges to net income over the following year with no+ change in accounting policy → the central divergence signal retires.+- The receivable or inventory build reverses into cash without a write-down → the+ quality concern was a working-capital timing effect.+- The company funds itself through a full cycle without dilution or covenant relief+ → the financing-dependence layer fails.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+forensic-short framework, …", cite the specific line item and filing period for+every accounting claim, keep valuation strictly in the sizing section, and state+explicitly whether the view is expressible or is a long-side warning only. This is+analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/dalio-debt-cycle.md b/agent/src/skills/investor-lenses/references/dalio-debt-cycle.mdnew file mode 100644index 000000000..65fc39961--- /dev/null+++ b/agent/src/skills/investor-lenses/references/dalio-debt-cycle.md@@ -0,0 +1,120 @@+---+name: dalio-debt-cycle+lens: Debt Cycle and Uncorrelated Bets+attributed_to: Ray Dalio+style: macro+markets: Country and asset-class level; applied to portfolio shape rather than to individual securities+description: Locate the economy on the short- and long-term debt cycles, derive which asset classes the resulting policy regime favours, and build the portfolio from bets that are genuinely uncorrelated.+---++# Debt Cycle Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Portfolio survivability across regimes. It treats the economy as a mechanism driven+by credit creation and policy response, asks which regime that mechanism is+currently in, and then builds exposure so that no single regime outcome dominates+the result. It is an allocation lens, not a selection lens.++## Market-fit note++- Requires country-level data: debt-to-GDP, debt service burden, policy rate versus+ nominal growth, currency reserves, external debt share, capacity utilization.+- For China, the credit impulse, local-government financing behaviour, property+ sector credit and the state's policy reaction function are the operative+ variables; the "central bank raises rates until it breaks" template of developed+ markets translates poorly.+- For dollarized or reserve-currency economies, the currency and reserve-status+ questions behave differently from those for economies with external debt.++## Priority signals (walk in this order)++1. **Short-term cycle position.** Output gap and capacity utilization, unemployment+ versus its structural level, inflation direction, real policy rate versus real+ growth, credit growth versus nominal GDP growth. Place the economy in: early+ expansion / late expansion / tightening / contraction / reflation.+2. **Long-term debt cycle position.** Total debt to GDP and its trajectory, debt+ service as a share of income, whether debt growth still produces proportional+ output growth, and how much conventional policy room remains (distance to the+ lower bound; central bank balance sheet size).+3. **Which deleveraging path is running**, if any: austerity, default and+ restructuring, monetization, or wealth transfer. Each has a different signature+ for currency, bonds and real assets, and they usually run together in a mix —+ identify the mix, not a single label.+4. **Derive asset-class implications from the regime, mechanically.** Rising growth+ versus expectations favours equities and credit; rising inflation versus+ expectations favours inflation-linked bonds and commodities; falling growth+ favours nominal bonds; monetized deleveraging pressures the currency and favours+ real assets. Write the mapping explicitly instead of jumping to a conclusion.+5. **Currency as the release valve.** In a debt problem denominated in the home+ currency, the currency usually absorbs the adjustment. Ask what the local-currency+ result and the hard-currency result each look like — they can differ in sign.+6. **Build from uncorrelated bets.** Count the number of return streams whose+ drivers are genuinely different, not the number of line items. Correlations+ measured in calm periods understate what happens in stress; test the pairwise+ relationships in the last two crisis windows, not the full-sample average.+7. **Balance across regimes.** State how the portfolio performs in each of the four+ growth/inflation quadrants. If one quadrant is catastrophic, the portfolio+ embodies a forecast, whether or not one was intended.++## Disqualifiers (hard vetoes)++- **A regime call with no mechanism.** "Inflation is coming" without the credit,+ capacity and policy chain that produces it is a prediction, not a lens output.+- **Diversification counted by instrument rather than by driver.** Ten equity+ exposures across sectors and geographies are close to one bet in a stress window.+- **A portfolio with a catastrophic quadrant** presented as balanced.+- **Correlation assumptions taken from a calm-period full-sample average** with no+ stress-window check.+- **Applied to pick a single stock.** Out of scope. The lens has nothing to say+ about company-level competitive position.++## Scoring rubric++| Output | Required content |+| --- | --- |+| Short-cycle placement | Named phase + the five indicators that place it |+| Long-cycle placement | Debt/GDP trajectory, debt service burden, policy room remaining |+| Deleveraging mix | Which of the four paths, in what proportion |+| Asset-class map | Explicit regime → asset mapping, written before the conclusion |+| Diversification count | Number of distinct *drivers*, with stress-window correlations |+| Quadrant table | Portfolio outcome in each growth/inflation quadrant |++## Typical misuse++- **Template applied without local translation.** The developed-market credit cycle+ template misreads economies where credit allocation is administratively directed+ and policy reacts on a different function.+- **Regime read converted into a market-timing trade.** Regimes are identified late+ and change slowly; the appropriate output is exposure shape, not entry timing.+- **Historical analogy as evidence.** "This looks like 1937" is a hypothesis+ generator. The mechanism has to be re-derived from current data, or the analogy is+ doing the work.+- **Risk-parity mechanics assumed to be the lens.** Leveraging low-volatility assets+ is one implementation with its own failure mode — a correlated rise in real rates+ hurts every leg simultaneously. The lens is the regime analysis, not the leverage+ recipe.+- **Confusing macro correctness with profit.** Being right about the regime and+ wrong about what is already priced is a loss. Stack a cycle-positioning lens to+ check what the market has already embedded.++## Falsifiers++- Credit growth accelerates while debt service burden falls → the late-long-cycle+ read is wrong; policy room is larger than assumed.+- Two of the "uncorrelated" return streams move together through a stress window →+ the diversification count was fictional and the portfolio shape must be rebuilt.+- Currency strengthens through a monetized deleveraging → the release-valve+ assumption fails and the hard-currency mapping is void.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+debt-cycle framework, …", show the short- and long-cycle placement with the+indicators that produced it, and give the four-quadrant table. This is analysis,+not investment advice.diff --git a/agent/src/skills/investor-lenses/references/duan-right-business.md b/agent/src/skills/investor-lenses/references/duan-right-business.mdnew file mode 100644index 000000000..0e937b992--- /dev/null+++ b/agent/src/skills/investor-lenses/references/duan-right-business.md@@ -0,0 +1,130 @@+---+name: duan-right-business+lens: Right Business, Right People+attributed_to: Duan Yongping (段永平)+style: quality+markets: A-share, HK and US-listed China names; founder- or owner-operator-led companies+description: Ask whether the business is one you would want to own outright, whether the people running it can be trusted with a decade of your capital, and then concentrate rather than diversify.+---++# Right Business, Right People Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Owning a small number of businesses whose model is simple, whose demand is real,+and whose operators behave decently when nobody is forcing them to. It is+deliberately exclusionary: the default answer is no, and the burden of proof sits+on the candidate.++## Market-fit note++- Built around founder- and owner-operator-led companies, which is a large share of+ the A-share, HK and US-listed China universe. It has little to say about+ professionally-managed, widely-held companies with no identifiable steward.+- Governance evidence in these markets is concrete and available: share pledges by+ the controlling holder, related-party transactions, guarantee obligations to+ affiliates, placement history, and the pattern of promises made and kept in+ earnings communications. Use those, not reputation.+- The "do the right thing" standard is a behavioural test, and behaviour is only+ observable over time. A company with two years of listed history cannot clear it.++## Priority signals (walk in this order)++1. **Is the demand real?** If this product disappeared tomorrow, would customers be+ genuinely worse off, or would they substitute in a week without noticing? This is+ the first gate and it eliminates most candidates.+2. **Is the model simple enough to hold in your head?** Who pays, for what, at what+ margin, and why they come back. Complexity that resists a simple statement is+ treated as a risk, not as sophistication.+3. **The stop-doing list.** What has this company deliberately refused to do —+ markets it declined to enter, revenue it turned down, shortcuts it did not take?+ A company with no stop-doing list has no discipline to observe.+4. **Are the people trustworthy — with evidence, not impression?** Track record of+ promises versus delivery, how minority shareholders were treated in past capital+ actions, related-party dealings, share pledges, whether bad news was disclosed+ early or late, whether the founder's other ventures competed with this one.+5. **Corporate culture as a durable asset.** Is the organization oriented toward the+ user and the long term, or toward this quarter's number? Look at hiring and+ promotion patterns, employee tenure, how the last crisis was handled, and whether+ the culture survives without the founder present.+6. **Return on capital without repeated capital raising.** Can it fund its own+ growth? Serial equity issuance at depressed prices is a governance finding as much+ as a financial one.+7. **Would it survive the top-three test?** If the portfolio could hold only three+ positions, does this make it? If not, the correct size under this lens is zero,+ not small.+8. **Price last.** A fair price for a right business beats a great price for a+ mediocre one — but "fair" still has to be computed, and a right business bought+ at any price is not this framework.++## Disqualifiers (hard vetoes)++- **Business not understood** — an explicit pass, not a discount. Under this lens+ "I don't understand it" ends the analysis with no negative connotation.+- **Any integrity finding on the controlling shareholder or management.** Not+ weighted against strengths; it ends the run.+- **Undisclosed or heavy controlling-shareholder pledges**, guarantees to+ affiliates, or related-party transactions that route value outside the listed+ entity.+- **Demand that is not real** — a product whose disappearance would inconvenience+ nobody.+- **Growth dependent on continuous external financing.**+- **Position would be a small "just in case" allocation.** Under this framework+ that is an admission the conviction is absent.++## Scoring rubric++| Gate | Pass condition |+| --- | --- |+| Real demand | Stated in one sentence, with evidence of switching pain |+| Simple model | Explained in a paragraph, no exceptions clause |+| Stop-doing list | At least two concrete refusals, dated |+| People | Promise-versus-delivery record; clean governance evidence |+| Culture | Observable in hiring, crisis handling, tenure |+| Self-funding | Growth funded from operations |+| Top-three test | Yes / no |+| Price | Fair-value estimate with the assumptions written down |++Every gate is a gate. There is no weighted total.++## Typical misuse++- **Turning a preference into a principle.** "Great company, hold forever" used to+ avoid ever re-examining a thesis. This framework has explicit sell conditions: the+ original judgement was wrong, the business fundamentally changed, or a clearly+ better opportunity exists. If none of those is ever triggered, the framework is+ not being applied, only invoked.+- **Character judged from media presence.** Founder charisma, interviews and social+ posts are not governance evidence. Filings, capital actions and past behaviour are.+- **Concentration without the gates.** The concentration rule is only safe because+ the gates are severe. Concentrating on a candidate that cleared three of eight+ gates inverts the risk profile entirely.+- **Applied to turnarounds or cyclicals.** The lens assumes an already-good business;+ it has no machinery for a business that is currently bad and expected to improve.+- **Ignoring price entirely.** "Right business" is a necessary condition, not a+ sufficient one. A fair-value estimate is still required.+- **Cross-cultural mistranslation of the integrity test.** The standard is about+ observable behaviour toward customers, partners and minority shareholders — not+ about personal virtue or public statements.++## Falsifiers++- A capital action that transfers value away from minority shareholders → the+ people gate fails retroactively and the position thesis is void, irrespective of+ operating performance.+- The stop-doing list is abandoned (entry into the previously refused business) →+ the discipline premise fails.+- Customers substitute away with no measurable pain during a price increase → the+ real-demand gate was wrong.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+right-business framework, …", walk all eight gates explicitly, and cite governance+evidence from filings rather than reputation. This is analysis, not investment+advice.diff --git a/agent/src/skills/investor-lenses/references/fengliu-weak-system.md b/agent/src/skills/investor-lenses/references/fengliu-weak-system.mdnew file mode 100644index 000000000..e1843c6bc--- /dev/null+++ b/agent/src/skills/investor-lenses/references/fengliu-weak-system.md@@ -0,0 +1,127 @@+---+name: fengliu-weak-system+lens: Weak-System Contrarian+attributed_to: Feng Liu (冯柳)+style: contrarian+markets: A-share primarily; adaptable to HK where the same names trade with a discount+description: Assume you have no information advantage, buy where the bad news is already known and priced, and let the position structure rather than the forecast carry the risk control.+---++# Weak-System Contrarian Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Making money without an information edge. It starts from an explicit admission of+weakness — you will never know the company better than insiders, sell-side+specialists or the supply chain — and builds a procedure that does not require+knowing more. Its edge is supposed to come from *position and expectation*, not from+superior facts.++## Market-fit note++- Designed around A-share market structure: high retail participation, fast and+ violent sentiment swings, wide dispersion between price and expectation, and+ liquid mid-caps that can be accumulated on weakness.+- Translates to HK for dual-listed and China-operating names, where the discount and+ the sentiment cycle are often deeper. Translates poorly to markets where+ institutional ownership dominates and expectations reset gradually.+- Requires a stock that can be *bought* on the way down — enough liquidity and no+ hard limit-down mechanics blocking accumulation.++## Priority signals (walk in this order)++1. **Declare the weakness explicitly.** Write down what you do not know and cannot+ find out. If the thesis requires knowing one of those things, stop — that is a+ strong-side thesis wearing this lens's clothes.+2. **Is the bad news known and old?** The candidate must be down substantially on+ *publicly discussed, well-understood* negatives. A stock falling on something the+ market has not yet digested is not in scope: this framework wants the news+ exhausted, not fresh.+3. **Expectation level, measured separately from valuation.** What is the consensus+ assuming — analyst revision direction, position crowding, retail sentiment,+ media tone? The target is low expectation, which is not the same as a low+ multiple. A cheap stock with high hopes fails this test.+4. **Business quality floor.** High gross margin, a product with real demand, a+ balance sheet that survives the bad scenario. The framework buys pessimism about+ *good* businesses, not cheapness in fragile ones — this is the most frequently+ dropped condition and dropping it converts the lens into a falling-knife machine.+5. **Locate the source of the decline.** Cyclical, sentiment-driven, one-off+ operational, or structural. Structural decline is out of scope; the other three+ are the lens's hunting ground. State which one and why.+6. **Asymmetry of the remaining path.** With the bad news priced, what does normal+ (not good) look like? The framework wants cases where merely *not getting worse*+ produces a return, and where further deterioration is bounded by asset value,+ cash or dividend.+7. **Position structure is the risk control.** Because the framework denies itself+ an information edge, it cannot rely on conviction. Build in tranches with+ pre-committed levels, cap single-name weight against the scenario where the thesis+ is simply wrong, and decide the sizing before the position exists.+8. **Reverse test.** State what the seller believes. If the seller's view is coherent+ and you have no basis to reject it, the correct action is a smaller position, not a+ better argument.++## Disqualifiers (hard vetoes)++- **The decline is structural** — end-market substitution, permanent regulatory+ contraction, technology displacement. This lens has no defence against a shrinking+ denominator.+- **Unresolved integrity or fraud risk.** Weak-side reasoning cannot price fraud;+ "priced in" is meaningless when the accounts may be fictional. Stack a forensic+ lens; if it flags, decline.+- **Balance sheet cannot survive the bad case** — refinancing risk, heavy+ controlling-shareholder pledges, covenant pressure.+- **The bad news is fresh**, still developing, or has an unknown magnitude.+- **Expectations are still high** despite the price fall (analyst estimates not yet+ cut, retail enthusiasm intact).+- **The thesis requires an information advantage** the framework has already+ declared it does not have.++## Scoring rubric++| Gate | Pass condition |+| --- | --- |+| Weakness declared | Written list of unknowables; thesis independent of them |+| News exhausted | Negative is public, old, and its magnitude is bounded |+| Expectation low | Revisions cut, sentiment negative, crowding gone |+| Quality floor | Gross margin, real demand, survivable balance sheet |+| Decline source | Cyclical / sentiment / one-off — named |+| Asymmetry | "Merely stops getting worse" produces a return |+| Structure | Tranches, cap and stop condition pre-committed |++## Typical misuse++- **Dropping the quality floor.** Applying weak-side contrarianism to any beaten-down+ stock, which is the single most expensive error available under this lens.+- **Buying fresh bad news.** Confusing "it fell a lot" with "the news is exhausted".+ Falls with unresolved magnitude are momentum, not contrarianism.+- **Running it in a momentum regime.** In a sustained trending market the framework+ systematically buys early and holds through further decline; that is expected+ behaviour, and it must be sized for it, not rationalized away.+- **Using conviction language.** Any sentence beginning "I'm confident that…"+ violates the framework's own premise. The framework's risk control is structure,+ and conviction language signals that structure has been abandoned.+- **Ignoring the reverse test.** Failing to state the seller's coherent case, which+ is the only cheap check available to a self-declared weak participant.+- **Transplanting to institution-dominated markets** where expectations do not+ overshoot as far or reset as fast.++## Falsifiers++- Analyst estimates are still being cut a quarter later and the operational+ deterioration accelerates → the "news exhausted" gate was wrong.+- Gross margin breaks its historical floor → the quality-floor gate fails and the+ position thesis is void.+- The decline turns out to be structural (a substitute takes durable share) → out of+ scope; exit is required by the framework, not optional.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+weak-system contrarian framework, …", begin with the declared list of unknowables,+name the decline source, and state the tranche structure and single-name cap before+any price target. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/fisher-scuttlebutt.md b/agent/src/skills/investor-lenses/references/fisher-scuttlebutt.mdnew file mode 100644index 000000000..d5fb5286d--- /dev/null+++ b/agent/src/skills/investor-lenses/references/fisher-scuttlebutt.md@@ -0,0 +1,122 @@+---+name: fisher-scuttlebutt+lens: Scuttlebutt Growth+attributed_to: Philip Fisher+style: growth+markets: Any market where customers, suppliers, distributors or ex-employees are reachable+description: Verify a growth story through primary qualitative evidence from the people around the business, and judge whether the growth engine is repeatable rather than episodic.+---++# Scuttlebutt Growth Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Finding businesses whose growth comes from a *repeatable organizational capability*+— research productivity, sales organization, cost discipline, customer intimacy —+rather than from one lucky product or one cycle. Its distinguishing move is that+the evidence is gathered from people around the company, not from the company.++## Market-fit note++- Channel evidence in A-shares is frequently available and frequently unreliable:+ distributor commentary is affected by channel-stuffing incentives near+ period-ends. Weight end-customer and ex-employee evidence above distributor+ evidence.+- In HK-listed China operations, on-the-ground evidence and reported segment data+ can diverge for long periods; treat a persistent divergence as a finding, not+ noise.+- For businesses with no reachable ecosystem (holding companies, opaque B2B+ intermediaries), this lens simply cannot be run. Say so rather than substituting+ desk research and calling it scuttlebutt.++## Priority signals (walk in this order)++1. **Runway.** Is there a market large enough for the current products to sustain+ several years of substantial revenue growth? If the growth is already a large+ share of the addressable market, the rest of the lens is moot.+2. **What comes after the current product.** Is there a determination and a+ mechanism to keep developing the next products once the current line matures?+ Look for a pipeline with dates, not aspirations.+3. **Research productivity, not research spending.** R&D as a share of revenue is+ an input. Ask for the output: revenue from products launched in the last three+ years, hit rate on development programs, time from program start to revenue.+4. **Sales organization quality.** Is distribution a genuine capability — coverage,+ attach rates, retention of key accounts, sales productivity per head — or a+ commission scheme? This is the most commonly under-examined asset.+5. **Margin structure and its defence.** Is the margin adequate, and what+ specifically is being done to hold it as costs rise? "Operating leverage" is not+ an answer; pricing, mix, and cost programs are.+6. **Labour and executive relations.** Turnover in the engineering and sales+ organizations, whether promotions come from inside, whether the layer below the+ CEO is visible and credible. Depth of management is a growth constraint.+7. **Cost accounting and controls.** Does management know the profitability of each+ product line and customer, or only the consolidated number? A company that cannot+ answer this cannot allocate capital well.+8. **Candour under bad news.** How did management communicate the last failure —+ the missed launch, the recall, the lost contract? Behaviour in the bad quarter+ predicts behaviour in the next bad quarter.+9. **The scuttlebutt cross-check.** Only after the above: what do customers,+ suppliers, distributors, ex-employees and competitors say about all of it? Ask+ competitors what they fear; ask customers what they would switch to and why they+ have not.++## Disqualifiers (hard vetoes)++- **No independent evidence obtainable.** If every input traces back to company+ materials, the lens has not been run — record it as not-applicable rather than+ passing it.+- **Primary evidence contradicts reported figures** on a material line (channel+ inventory, real end-demand, actual pricing) and the gap is unexplained.+- **Integrity question in management** — this lens explicitly refuses to proceed on+ a business whose management it does not trust, regardless of growth.+- **One-product company with no successor program**, where the current product's+ runway is the entire thesis.+- **Growth bought, not built** — revenue growth driven by acquisitions or by+ extending customer credit, with organic growth flat.++## Scoring rubric++Score each of the nine signals as *strong / adequate / weak / unknown*. The verdict+depends on the *shape*, not the total:++- Weak on runway or successor products → no, whatever the rest looks like.+- Weak on cost accounting or candour → risk-flag, stack the inversion lens.+- Three or more *unknown* → the lens has insufficient evidence; report that, do not+ interpolate.++## Typical misuse++- **Anecdote laundering.** Two enthusiastic customers become "channel checks+ confirm strong demand". Record sample size, who was asked, and what the+ counter-evidence was.+- **Selection bias in sourcing.** Talking only to the customers management+ introduced you to. Note who selected the sample.+- **Qualitative conclusions used to override arithmetic.** Scuttlebutt tells you+ whether the growth is real; it does not tell you what the growth is worth. Price+ discipline must come from another lens.+- **Applied to a cyclical upswing.** Everyone in the ecosystem is optimistic at the+ top of a cycle. Date every piece of qualitative evidence against the cycle.+- **Treating employee-review sites and forums as primary evidence.** Self-selected,+ timing-skewed, and frequently gamed.+- **Compliance blindness.** Pursuing non-public specifics from insiders is not+ research. Stay with observable, public and permissibly shared information.++## Falsifiers++- Revenue from products launched in the last three years falls toward zero →+ research productivity claim fails, and the lens's central premise with it.+- Key-account retention drops while headline revenue grows → growth is coming from+ new-logo churn, not a durable capability.+- The named successor product slips two consecutive periods → the pipeline was+ aspiration.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+scuttlebutt-growth framework, …", and for every qualitative claim record the source+type, sample size and date. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/graham-deep-value.md b/agent/src/skills/investor-lenses/references/graham-deep-value.mdnew file mode 100644index 000000000..7304cb4f1--- /dev/null+++ b/agent/src/skills/investor-lenses/references/graham-deep-value.md@@ -0,0 +1,113 @@+---+name: graham-deep-value+lens: Statistical Deep Value+attributed_to: Benjamin Graham+style: value+markets: Any market with reliable balance-sheet disclosure; strongest where a wide basket can be held+description: Buy a statistically cheap basket against verifiable balance-sheet value, demand a quantified margin of safety, and refuse to pay for forecasts.+---++# Statistical Deep Value Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Not being wrong expensively. It replaces judgement about the future with+measurable, present, auditable value, then insists on paying meaningfully less than+that. It expects to be wrong on individual names and to be right on the basket.++## Market-fit note++- Works wherever balance sheets are audited and comparable, and where you can hold+ 20+ names so idiosyncratic blowups average out.+- In A-shares, statistically cheap screens are dominated by financials, utilities+ and property; treat that concentration as a single macro bet, not diversification.+- In HK, persistent deep discounts often reflect a controlling-shareholder+ discount, not mispricing — see the disqualifiers.++## Priority signals (walk in this order)++1. **Solvency before cheapness.** Current ratio, total debt to net current assets,+ interest coverage, and whether the company can survive two bad years without+ raising capital. A cheap insolvent company is not cheap.+2. **Net current asset value.** Current assets minus *all* liabilities (including+ off-balance-sheet and lease obligations), against market cap. The classic+ threshold is a market cap below two-thirds of that figure — rare outside crises,+ and its rarity is information.+3. **Tangible book, adjusted.** Book value with intangibles and goodwill removed,+ then marked for what the assets would actually fetch: inventory obsolescence,+ receivable ageing, investment property carried at stale valuations, land carried+ at historic cost.+4. **Earnings stability, not earnings growth.** Positive earnings in each of the+ last 5–10 years. Averaged earnings across a full cycle, versus price. Growth+ forecasts are excluded from the valuation on purpose.+5. **Dividend record.** An uninterrupted payout history is evidence the reported+ earnings were real cash.+6. **Margin of safety, quantified.** Price versus the *conservative* value estimate,+ stated as a percentage discount. If you cannot state the number, the lens has not+ been run.++## Disqualifiers (hard vetoes)++- **Leverage that removes optionality** — debt maturing inside 12 months exceeding+ cash plus committed facilities. Cheapness is irrelevant against a refinancing wall.+- **Loss in any of the recent years under review** — the stability test is a gate,+ not a scored input.+- **Asset base that cannot be marked** — the "value" is goodwill, capitalized+ development cost, level-3 assets, or related-party receivables.+- **Value the minority shareholder cannot reach** — cash controlled by a parent,+ assets pledged to related parties, a controlling holder with a history of+ extraction. A discount that exists because value leaks is not a margin of safety.+- **Single-name concentration.** This lens is basket-shaped. Applying it to one+ position removes the statistical premise it depends on.+- **Value derived from a forecast.** If removing the growth assumption removes the+ discount, the case belongs to a different lens.++## Scoring rubric++| Gate | Pass condition |+| --- | --- |+| Solvency | Survives two years of zero growth with no external financing |+| Balance-sheet value | Discount to conservatively adjusted tangible value, stated in % |+| Earnings stability | No loss years in the review window |+| Distribution | Dividends paid, or a credible explanation for retention |+| Basket | ≥ 20 comparable names, or an explicit acknowledgement the premise is broken |++Verdict is the weakest gate, not the average.++## Typical misuse++- **Applied to asset-light businesses.** Software, brands and networks carry almost+ no markable book value; this lens will reject good businesses and reward bad+ balance sheets. Use a quality or GARP lens instead.+- **Applied to a single stock as a conviction case.** The methodology's expected+ return comes from a diversified basket absorbing individual failures.+- **Treating a value trap as a margin of safety.** Cheap assets in a structurally+ declining industry get cheaper: the denominator erodes faster than the discount+ closes. Stack a forensic-short or cycle lens to test this.+- **Ignoring the reason for cheapness.** The lens is deliberately indifferent to+ narrative, which becomes a defect when the narrative is "the assets are impaired+ and the auditor has not caught up yet".+- **Cross-border book comparison.** Accounting standards differ on revaluation,+ leases and capitalization; a discount to book across jurisdictions may be an+ artifact.++## Falsifiers++- The adjusted tangible value falls below the market cap once obsolete inventory,+ ageing receivables and stale property marks are applied → the discount was+ arithmetic, not real.+- A capital raise below book → management disagrees with your asset value.+- Repeated asset write-downs in consecutive periods → the book is a lagging+ indicator and the anchor is unreliable.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+statistical deep-value framework, …", give the discount as a number with the+adjustments that produced it, and state explicitly whether the basket premise+holds. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/lynch-garp.md b/agent/src/skills/investor-lenses/references/lynch-garp.mdnew file mode 100644index 000000000..63f0ec13d--- /dev/null+++ b/agent/src/skills/investor-lenses/references/lynch-garp.md@@ -0,0 +1,125 @@+---+name: lynch-garp+lens: Growth at a Reasonable Price by Category+attributed_to: Peter Lynch+style: growth+markets: Broad — best on mid-caps with visible end products; weakest on financials and commodities+description: Classify the company into a growth category first, then apply the valuation and expectation rules that belong to that category rather than one universal multiple.+---++# GARP-by-Category Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Paying a multiple that is justified by the earnings growth actually being+delivered, with the crucial preliminary step of deciding *what kind of company*+this is. The most common error the lens is designed to prevent is applying+fast-grower expectations to a cyclical, or turnaround patience to a structural+decline.++## Market-fit note++- Category discipline matters more in A-shares, where sentiment can push a+ slow-grower to fast-grower multiples on a thematic label.+- Retail-visible businesses (consumer, restaurants, retail chains) are where the+ lens's observational edge is real; industrial B2B names give up that edge.+- The category rules assume the earnings series is meaningful. Where earnings are+ policy-administered or heavily subsidy-dependent, classify by the underlying+ operating business, not the reported line.++## Priority signals (walk in this order)++1. **Assign the category. Exactly one.**+ - *Slow grower* — mature, low single-digit growth. Held, if at all, for the+ dividend. Valuation anchor: yield and payout sustainability.+ - *Stalwart* — large, 8–12% growth, defensive. Anchor: a modest premium to+ growth; the expected outcome is a moderate gain, not a multiple.+ - *Fast grower* — 20%+ sustained, usually smaller, with room to replicate.+ Anchor: growth versus multiple, plus how many years of replication remain.+ - *Cyclical* — earnings swing with a cycle. Anchor: **inverted** — a low+ multiple on peak earnings is expensive; a high multiple on trough earnings can+ be cheap.+ - *Turnaround* — the question is survival, not growth. Anchor: balance sheet and+ the specific fix.+ - *Asset play* — value sits in an asset the market is not counting. Anchor:+ the asset's realizable value and the mechanism by which it gets realized.+2. **Verify the category against the numbers**, not the label the market has+ applied. Five to ten years of revenue and earnings, and where in the cycle those+ years sit.+3. **Apply the category's valuation rule.** For growth categories, compare the+ multiple to the sustainable growth rate; a multiple far above the growth rate+ requires an explicit reason. For cyclicals, normalize earnings across the cycle+ before any multiple is computed.+4. **Test the growth's mechanics.** For a fast grower: how many units/stores/+ customers exist, how many can exist, at what rate they are being added, and what+ the unit economics look like at maturity. Growth must be countable.+5. **Balance sheet check.** Net debt to equity, and whether growth is being funded+ by operating cash or by financing. A fast grower funded by debt is a cyclical+ wearing a costume.+6. **Inventory and receivables versus sales.** Inventory growing faster than sales+ is the earliest and cheapest warning available.+7. **Insider and buyback behaviour** as corroboration, never as the thesis.+8. **The two-minute statement.** State, in plain language, why you own this, what+ has to happen, and what would make you stop. If it takes longer than two minutes,+ the case is not understood.++## Disqualifiers (hard vetoes)++- **Category cannot be assigned**, or the company sits in two categories at once+ with no dominant one.+- **Multiple far above growth rate with no stated reason** other than that the+ story is popular.+- **Cyclical valued on peak earnings** with a low headline multiple presented as+ cheapness.+- **Growth funded by rising leverage** while operating cash flow lags reported+ earnings.+- **Diversification into unrelated businesses** at the expense of the core engine.+- **"The next X"** as a central argument — an explicit warning sign under this+ framework, because it substitutes analogy for arithmetic.++## Scoring rubric++| Gate | Pass condition |+| --- | --- |+| Category | Assigned, evidenced, single |+| Valuation rule | The category's own rule applied, arithmetic shown |+| Countable growth | Units and rate stated, maturity economics estimated |+| Funding | Growth financed from operations |+| Working capital | Inventory and receivables not outrunning sales |+| Two-minute statement | Written, with the stop condition |++## Typical misuse++- **Formulaic multiple-versus-growth screening.** The comparison is a starting+ heuristic, not a valuation. It is meaningless for financials, for companies with+ low or negative earnings, and for any cyclical.+- **Extrapolating a growth rate off a depressed base.** A 60% rebound year is not a+ growth rate.+- **Applying it to financials.** Bank and insurer earnings are provisioning+ choices; earnings-multiple logic and this lens's growth tests do not translate.+- **Ignoring the category's own trap.** Turnarounds fail more often than they+ succeed; asset plays can stay unrealized indefinitely; stalwarts de-rate quietly.+- **"Buy what you know" as a licence.** Familiarity with a product is a source of+ hypotheses, not a substitute for the financial work — and it systematically biases+ toward consumer names.++## Falsifiers++- Same-store or same-customer metrics turn negative while total revenue grows →+ the growth is expansion-funded, and the fast-grower category is void.+- Inventory days rise for two consecutive periods against flat sales → the earnings+ quality premise fails.+- Normalized mid-cycle earnings come in far below the trailing figure → the company+ was a cyclical all along and the valuation must be redone.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+GARP-by-category framework, …", name the assigned category and the evidence for it+first, and show the arithmetic for that category's valuation rule. This is+analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/marks-cycle-position.md b/agent/src/skills/investor-lenses/references/marks-cycle-position.mdnew file mode 100644index 000000000..c139becd2--- /dev/null+++ b/agent/src/skills/investor-lenses/references/marks-cycle-position.md@@ -0,0 +1,111 @@+---+name: marks-cycle-position+lens: Cycle Positioning and Second-Level Thinking+attributed_to: Howard Marks+style: contrarian+markets: Any liquid market; applies to the market environment rather than to a single security+description: Judge where the market sits on the greed–fear cycle, ask what is already priced in rather than what is true, and set aggressiveness from the cycle position rather than from forecasts.+---++# Cycle Positioning Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Calibrating how aggressive to be, given where sentiment and pricing sit in the+cycle. It deliberately refuses to forecast: it takes the temperature of the present+and adjusts posture. Its unit of analysis is the environment, not the company.++## Market-fit note++- The sentiment indicators below are market-structure dependent. In A-shares, use+ margin-financing balances, new account openings, turnover velocity and new-fund+ issuance; in HK, use southbound flows, IPO pipeline activity and the discount+ behaviour of dual-listed pairs; in crypto, funding rates, perpetual open interest+ and leverage liquidations.+- The lens travels well across markets precisely because it measures behaviour, and+ behaviour rhymes even when instruments differ.++## Priority signals (walk in this order)++1. **Second-level formulation.** Restate the question from "is this a good company+ or a good economy?" to "what is the consensus, is it embedded in the price, and+ in what specific way am I differing from it?" If your view and the consensus+ coincide, there is no edge regardless of correctness.+2. **Take the temperature with observables, not opinions.**+ - risk premia: credit spreads versus their own history, equity risk premium+ - issuance quality: covenant terms, IPO quality, ease of financing for weak+ borrowers — the single most reliable indicator here+ - leverage in the system: margin balances, prime brokerage leverage, derivative+ open interest+ - investor behaviour: fund flows, new-account formation, turnover velocity+ - narrative: whether "this time is different" is being said, and by whom+3. **Place the position on the pendulum**, not on a forecast: euphoria → optimism →+ neutral → pessimism → capitulation. State which observations put it there.+4. **Ask what price implies.** Reverse-engineer the growth, default or margin+ assumptions embedded in the current price. A price is a statement of expectation;+ read it before disputing it.+5. **Set posture, not prediction.** The output is a dial — more aggressive, neutral,+ more defensive — with position sizing and quality preferences attached. Never a+ date, never a level.+6. **Asymmetry check.** In this environment, does being wrong cost much more or much+ less than being right pays? Late-cycle, the asymmetry turns hostile long before+ the cycle turns.++## Disqualifiers (hard vetoes)++- **Any output containing a market-timing call** — a level or a date. That is+ outside the lens by construction.+- **Temperature taken from narrative alone**, with no measurable risk-premium,+ issuance or leverage evidence.+- **Contrarianism for its own sake.** Being opposite the crowd is not an edge;+ being opposite the crowd *and* right about a specific mispricing is. State the+ mispricing.+- **Cycle position asserted without acknowledging that extremes persist.** A cycle+ read is not a trigger; if it is being used as one, the lens is being misused.++## Scoring rubric++| Reading | Evidence pattern | Posture |+| --- | --- | --- |+| Euphoria | Spreads at cycle tights, covenant-lite issuance easy, leverage rising, "new paradigm" talk | Maximum defence: quality up, leverage down, liquidity up |+| Optimism | Premia below average, issuance healthy | Modestly defensive |+| Neutral | Premia near long-run average | Normal posture; the lens adds nothing here, say so |+| Pessimism | Premia above average, issuance selective | Modestly aggressive |+| Capitulation | Forced selling, financing unavailable at any price, quality sold with junk | Maximum aggression the mandate allows |++## Typical misuse++- **Used as a timing tool.** Extremes can persist far longer than a position can be+ financed. The lens says how to be positioned, not when it turns.+- **Applied to a single stock.** A company's fundamentals are not a cycle read;+ conflating them produces confident nonsense in both directions.+- **Sentiment measured with sentiment surveys only.** Surveys are noisy and often+ contradict positioning data. Prefer what people *did* with money — issuance,+ leverage, flows — over what they said.+- **Permanent bearishness laundered as discipline.** Track whether the lens has+ produced any "be aggressive" reading in the last several years; if not, it is+ being applied with a thumb on the scale.+- **Reading a single indicator.** Credit spreads alone, or flows alone, generate+ false extremes. The reading requires convergence across the observable families.++## Falsifiers++- Risk premia widen materially while your reading was euphoria → the temperature+ read was stale; the pendulum had already moved.+- Weak borrowers lose financing access → late-cycle read confirmed regardless of+ index level.+- The consensus you identified turns out not to be the consensus (positioning data+ contradicts the narrative) → the second-level premise was wrong, and the whole+ run is void.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+cycle-positioning framework, …", give the pendulum reading with the observable+evidence per family, and express the conclusion as posture — never as a level or a+date. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/munger-inversion.md b/agent/src/skills/investor-lenses/references/munger-inversion.mdnew file mode 100644index 000000000..10c25e4d9--- /dev/null+++ b/agent/src/skills/investor-lenses/references/munger-inversion.md@@ -0,0 +1,118 @@+---+name: munger-inversion+lens: Inversion+attributed_to: Charlie Munger+style: risk+markets: Any market, any asset class; the least data-dependent lens here+description: Ask how the thesis dies rather than how it wins — enumerate failure paths, assign triggers, and eliminate the ways of being stupid before looking for ways to be clever.+---++# Inversion Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Avoiding permanent capital loss and avoidable stupidity. It never produces a buy+signal — its only outputs are "this specific failure path is live" and "these are+the observable triggers". Treat it as a veto layer stacked on a positive lens, not+a standalone decision procedure.++## Market-fit note++- Portable everywhere because it consumes reasoning rather than data.+- In markets where disclosure is thin, the inversion is *more* valuable, because+ the failure paths are the part you can reason about without a data feed.+- In A-shares and HK, add two failure families that US-designed checklists often+ omit: policy reversal (industry-level administrative intervention) and+ controlling-shareholder pledge/extraction risk.++## Priority signals (walk in this order)++1. **State the thesis as a falsifiable sentence.** "X compounds earnings at 15% for+ five years because of Y." If the thesis cannot be stated this way, invert the+ vagueness itself: an unfalsifiable thesis is the first failure path.+2. **Enumerate at least five distinct death paths**, drawn from different families,+ not five versions of one worry. Standard families:+ - demand disappears (substitution, generational shift, end-market decline)+ - supply economics invert (capacity, input costs, commoditization)+ - the balance sheet breaks (refinancing, covenants, pledged shares, currency)+ - the rules change (regulation, tariffs, licensing, sanctions, tax)+ - the people fail (fraud, succession, empire-building acquisitions, dilution)+ - the price was the whole thesis (multiple compression alone)+3. **For each path: probability band, time-to-impact, and a concrete trigger.** A+ trigger is an observable — a covenant ratio, a filing, a price, a policy+ document — not a feeling. Paths without triggers are not usable.+4. **Compute the loss under the worst plausible path**, not the average path. What+ does a shareholder recover in liquidation or restructuring? Is permanent loss of+ capital possible, or only volatility?+5. **Ask why intelligent, informed sellers are selling.** Construct the strongest+ version of the bear case as its holder would state it. If you cannot state it+ convincingly, you do not yet understand the position.+6. **Run the standing stupidity checklist** — the list of errors that recur+ independently of the specific company:+ - incentive-caused bias (whose compensation depends on this being true?)+ - social proof (how much of the conviction is that respected others hold it?)+ - commitment and consistency (are you defending a published view?)+ - availability (is the reasoning driven by the most recent vivid event?)+ - liking (is the founder's charisma doing analytical work?)+ - deprival super-reaction (are you acting to avoid missing out?)+7. **Historical analogues.** Name two companies that reached this same stage and+ failed, and state which of your death paths killed them.++## Disqualifiers (hard vetoes)++- **A failure path exists whose outcome is permanent total loss and whose trigger+ is not observable in advance.** Unhedgeable, unmonitorable, ruinous — decline.+- **The thesis requires a specific person to keep behaving well** with no structural+ constraint on them.+- **Leverage plus a variable outside management's control** (rates, a single+ customer, a single regulator) that can force action at the worst moment.+- **You cannot articulate the bear case.** Not a judgement about the company — a+ judgement about your readiness.+- **Any path whose probability you rate "low" purely because you have not+ investigated it.** Unknown is not low.++## Scoring rubric++There is no score. The output is a table:++| Death path | Family | Probability | Time to impact | Observable trigger | Recovery if it happens |+| --- | --- | --- | --- | --- | --- |++Plus a single verdict line: *survivable*, *survivable only if monitored via the+listed triggers*, or *not survivable — decline*.++## Typical misuse++- **Used as a decision procedure on its own.** Every asset has failure paths; a+ lens that only enumerates risk will reject everything if allowed to be the whole+ process. It is a veto layer.+- **Symmetric pessimism.** Listing five paths for the candidate and none for the+ alternative (including cash, which has its own path: inflation and opportunity+ cost).+- **Untriggered risk theatre.** Long lists of unfalsifiable worries that no+ observation can ever retire. If a risk cannot be monitored or resolved, say so+ and treat it as a permanent haircut, not a bullet point.+- **Confusing volatility with permanent loss.** The lens is about impairment, not+ drawdown. Conflating them causes exit at exactly the wrong point.+- **Post-hoc inversion.** Running it after the position is on, when the commitment+ bias it is meant to detect is already operating.++## Falsifiers++- A listed trigger fires and the outcome does not follow → the causal model behind+ that path was wrong; revise the path rather than quietly dropping it.+- The bear case turns out to rest on a fact that is checkable and false → that path+ retires, and the retirement should be recorded with its evidence.+- A path you rated low-probability occurs at a peer → re-rate the family, not just+ the instance.++## Output contract++Report under the skill-level output contract. State the verdict as "under an+inversion framework, …", deliver the death-path table with triggers, and separate+permanent-loss risk from volatility. This is analysis, not investment advice.diff --git a/agent/src/skills/investor-lenses/references/qiuguolu-three-questions.md b/agent/src/skills/investor-lenses/references/qiuguolu-three-questions.mdnew file mode 100644index 000000000..94741ae63--- /dev/null+++ b/agent/src/skills/investor-lenses/references/qiuguolu-three-questions.md@@ -0,0 +1,131 @@+---+name: qiuguolu-three-questions+lens: Three Questions — Value, Pricing Power, Industry Structure+attributed_to: Qiu Guolu (邱国鹭)+style: value+markets: A-share and HK; designed around industries whose competitive structure has already formed+description: Answer three questions in order — is it cheap, does the company have pricing power, and is the industry structure favourable — and refuse to let a good answer to one substitute for a bad answer to another.+---++# Three Questions Lens++> **Framework, not investment advice.** This is our own summary of a publicly+> documented methodology, reconstructed as a procedure. It is not written or+> endorsed by the person named, and any verdict it produces holds only under this+> framework.++## What this lens optimizes for++Simplicity that survives contact with a retail-driven market. It reduces the case to+three questions that are answerable from public data, insists all three be answered+independently, and treats industry structure as the variable that most often decides+the outcome and is most often skipped.++## Market-fit note++- Built for A-shares and applies directly to HK-listed China operations. Its+ structural bias — preferring industries where competition has already consolidated —+ matches markets with long histories of capacity overbuild and price wars.+- Least useful in industries whose structure has not yet formed (early-stage+ technology, newly created policy-driven sectors), where the third question has no+ answer yet. Say "unanswerable" rather than guessing.+- Government-influenced pricing is a structural fact here, not an anomaly: an+ industry where the state sets prices has a ceiling on pricing power no matter how+ concentrated it is.++## Priority signals (walk in this order)++**Question 1 — Is it cheap? (便宜是硬道理)**++1. Valuation against the company's own history and against the industry, on the+ measure that fits the business: earnings multiple for stable earners, book+ multiple for asset-heavy and financial businesses, cash-flow multiple where+ accounting earnings are noisy.+2. Test whether the cheapness is real or an artifact of a peak-earnings denominator.+ Normalize across the cycle before concluding.+3. Cross-check the balance sheet: net cash, investment assets, and property carried+ at historic cost that the multiple ignores.++**Question 2 — Does the company have pricing power? (定价权)**++4. Has it raised prices above input inflation and kept the volume? That is the only+ direct evidence; everything else is inference.+5. Gross margin level and stability through the last downturn — pricing power shows+ up as margin that holds when demand does not.+6. Where does the power come from: brand, switching cost, licence, distribution+ control, or genuine cost leadership? Name it. Cost leadership is a real answer here+ and is the most durable one in commoditized industries.+7. Bargaining position against both sides: customer concentration, supplier+ concentration, and the direction of payable and receivable days over five years.++**Question 3 — Is the industry structure favourable? (行业格局)**++8. Concentration and its trend — is share consolidating toward the leaders or+ fragmenting?+9. Capacity: is new capacity still being added, and how long is the lead time? An+ industry adding capacity into weak demand cannot support pricing regardless of+ individual company quality.+10. Barriers to entry, and whether they are real (capital intensity, licence, scale+ economics, distribution) or narrative.+11. Competitive behaviour: is the industry competing on price or on product? A+ consolidated industry that still price-wars is not a favourable structure.+12. Position within the structure — leader, credible challenger, or subscale. In a+ consolidating industry the subscale player usually gets worse even as the industry+ gets better.++## Disqualifiers (hard vetoes)++- **Cheap but no pricing power and deteriorating structure** — the classic value+ trap this framework exists to prevent.+- **Good structure and pricing power, but the price already reflects both.** All three+ questions must pass; a good business at an unjustifiable price fails.+- **Industry still adding capacity aggressively** into flat or falling demand.+- **Structure unanswerable** because the industry has not formed — out of scope, and+ the correct output is "this lens does not apply".+- **Pricing power inferred from margin alone** with no evidence of a price increase+ that stuck. High margin can come from mix or from a temporary input-cost windfall.++## Scoring rubric++| Question | Pass condition |+| --- | --- |+| Cheap | Discount versus own history and peers, on normalized earnings, arithmetic shown |+| Pricing power | A price increase that held, plus margin stability through a downturn, plus a named source |+| Structure | Concentration rising or stable-high, capacity discipline, real barriers, non-price competition |++All three must pass. A strong answer to one never compensates for a failed answer to+another; that substitution is the specific error this framework was constructed to+block.++## Typical misuse++- **Answering only question one.** Cheapness is the most easily measured and the+ least decisive of the three.+- **Structure inferred from market share alone.** Share concentration with continuing+ price wars is a bad structure. Look at competitive behaviour, not just the+ Herfindahl.+- **Applied to industries with no formed structure**, where the answers are invented.+- **Ignoring the company's position within a good structure.** A favourable industry+ does not lift a subscale participant; it often accelerates its decline.+- **Treating administered-price industries as having pricing power** because+ concentration is high. Where the price is set outside the company, the answer to+ question two is no.+- **Ranking simplicity above evidence.** The framework's three questions are simple to+ ask and not simple to answer; a one-line answer to any of them means the work was+ not done.++## Falsifiers++- A price increase is rolled back or volume collapses after it → question two fails,+ regardless of historical margin.+- New capacity announcements accelerate → question three fails, and cheapness becomes+ irrelevant.+- Normalized mid-cycle earnings come in far below trailing earnings → question one was+ answered on a peak denominator and must be redone.++## Output contract++Report under the skill-level output contract. State the verdict as "under a+three-questions framework, …", answer all three questions separately with their own+evidence, and state explicitly which question is the binding constraint. This is+analysis, not investment advice.diff --git a/agent/tests/test_investor_lenses_skill.py b/agent/tests/test_investor_lenses_skill.pynew file mode 100644index 000000000..5eb8857f8--- /dev/null+++ b/agent/tests/test_investor_lenses_skill.py@@ -0,0 +1,270 @@+"""Structural tests for the ``investor-lenses`` skill.++The skill is pure markdown: a router ``SKILL.md`` plus one file per lens under+``references/``. Nothing here executes a lens — these tests guard the properties+that silently rot as lenses are added or renamed:++* the router is loadable by :class:`SkillsLoader` and lands in a real category;+* every lens file parses as frontmatter and declares the same metadata keys;+* the router index and the files on disk agree **in both directions**, so a+ renamed file cannot leave a dead index row and a new file cannot stay orphaned;+* every router link carries the ``investor-lenses/`` prefix and resolves through+ ``read_file`` (bare ``references/...`` links are unreachable — the skills root+ has no top-level ``references/`` directory);+* each lens keeps the sections the output contract depends on, the+ not-investment-advice disclaimer, and framework-conditional phrasing;+* no lens hardcodes a registered tool name, which is what keeps the lenses+ decoupled from the data layer.++No network access: every assertion is a local file read.+"""++from __future__ import annotations++import re+from pathlib import Path+from typing import List++import pytest++from src.agent.frontmatter import parse_frontmatter+from src.agent.skills import SkillsLoader+from src.tools.read_file_tool import ReadFileTool++import json++_SKILL_NAME = "investor-lenses"+_SKILLS_ROOT = Path(__file__).resolve().parents[1] / "src" / "skills"+_SKILL_DIR = _SKILLS_ROOT / _SKILL_NAME+_REFS_DIR = _SKILL_DIR / "references"++# Router index rows link to "investor-lenses/references/<slug>.md".+_INDEX_LINK_RE = re.compile(r"\]\((?P<target>[^)]*references/[^)]+\.md)\)")++# Metadata every lens file must declare.+_REQUIRED_LENS_KEYS = ("name", "lens", "attributed_to", "style", "markets", "description")++# Section headings the skill-level output contract depends on.+_REQUIRED_SECTIONS = (+ "## What this lens optimizes for",+ "## Market-fit note",+ "## Priority signals",+ "## Disqualifiers",+ "## Typical misuse",+ "## Falsifiers",+ "## Output contract",+)++_DISCLAIMER = "**Framework, not investment advice.**"++# Categories SkillsLoader knows how to group (src/agent/skills.py:_CATEGORY_ORDER).+_KNOWN_CATEGORIES = {+ "data-source", "strategy", "analysis", "asset-class",+ "crypto", "flow", "tool", "other",+}+++def _lens_paths() -> List[Path]:+ """Return every lens markdown file on disk, sorted by name."""+ return sorted(_REFS_DIR.glob("*.md"))+++def _router_text() -> str:+ """Return the raw router SKILL.md text."""+ return (_SKILL_DIR / "SKILL.md").read_text(encoding="utf-8")+++def _lens_ids() -> List[str]:+ """Return lens slugs for parametrization (filename stems)."""+ return [path.stem for path in _lens_paths()]+++def _lens_text(slug: str) -> str:+ """Return the raw text of one lens file.++ Args:+ slug: Lens file stem, e.g. ``munger-inversion``.++ Returns:+ Raw markdown text.+ """+ return (_REFS_DIR / f"{slug}.md").read_text(encoding="utf-8")+++# ---------------------------------------------------------------------------+# Directory structure+# ---------------------------------------------------------------------------+++def test_skill_directory_structure() -> None:+ """Router and references directory both exist."""+ assert (_SKILL_DIR / "SKILL.md").is_file()+ assert _REFS_DIR.is_dir()+++def test_lens_count_within_declared_range() -> None:+ """The skill ships a meaningful but bounded number of lenses."""+ assert 8 <= len(_lens_paths()) <= 12, f"found {len(_lens_paths())} lens files"+++def test_router_loads_through_skills_loader() -> None:+ """SkillsLoader picks the skill up with a usable name/description/category."""+ loader = SkillsLoader(+ skills_dir=_SKILLS_ROOT,+ user_skills_dir=Path("/nonexistent-user-skills-dir"),+ )+ skill = next((s for s in loader.skills if s.name == _SKILL_NAME), None)+ assert skill is not None, "investor-lenses not discovered by SkillsLoader"+ assert skill.description.strip(), "router description is empty"+ assert skill.category in _KNOWN_CATEGORIES+ assert skill.body.strip(), "router body is empty"+++# ---------------------------------------------------------------------------+# Frontmatter+# ---------------------------------------------------------------------------+++def test_router_frontmatter_is_parseable() -> None:+ """Router frontmatter parses and names the skill after its directory."""+ meta, body = parse_frontmatter(_router_text())+ assert meta.get("name") == _SKILL_NAME+ assert meta.get("category") in _KNOWN_CATEGORIES+ assert meta.get("description", "").strip()+ assert body.startswith("# "), "router body must open with a markdown H1"++[email protected]("slug", _lens_ids())+def test_lens_frontmatter_is_complete(slug: str) -> None:+ """Every lens declares the full metadata key set, and name matches filename."""+ meta, body = parse_frontmatter(_lens_text(slug))+ assert meta, f"{slug}.md has no parseable frontmatter"+ for key in _REQUIRED_LENS_KEYS:+ assert str(meta.get(key, "")).strip(), f"{slug}.md is missing frontmatter key '{key}'"+ assert meta["name"] == slug, f"{slug}.md declares name={meta['name']!r}"+ assert body.strip(), f"{slug}.md has an empty body"+++def test_lens_styles_cover_distinct_schools() -> None:+ """Lenses span multiple styles rather than restating one school."""+ styles = {parse_frontmatter(_lens_text(slug))[0]["style"] for slug in _lens_ids()}+ assert len(styles) >= 6, f"only {len(styles)} distinct styles: {sorted(styles)}"+++def test_china_market_coverage_is_represented() -> None:+ """At least three lenses speak to A-share / HK market structure."""+ hits = [slug for slug in _lens_ids() if "A-share" in _lens_text(slug)]+ assert len(hits) >= 3, f"only {hits} mention A-share market structure"+++# ---------------------------------------------------------------------------+# Index integrity (both directions)+# ---------------------------------------------------------------------------+++def _router_link_targets() -> List[str]:+ """Return every reference link target written in the router."""+ return [m.group("target") for m in _INDEX_LINK_RE.finditer(_router_text())]+++def test_router_index_and_disk_agree_both_ways() -> None:+ """Every indexed lens exists, and every lens on disk is indexed."""+ indexed = {Path(t).stem for t in _router_link_targets()}+ on_disk = set(_lens_ids())+ assert indexed - on_disk == set(), f"router links to missing lenses: {sorted(indexed - on_disk)}"+ assert on_disk - indexed == set(), f"lens files absent from the router index: {sorted(on_disk - indexed)}"++[email protected]("target", _router_link_targets())+def test_router_links_carry_skill_prefix(target: str) -> None:+ """Links are prefixed with the skill name so they resolve from the skills root."""+ assert target.startswith(f"{_SKILL_NAME}/"), (+ f"link must start with '{_SKILL_NAME}/', got: {target}"+ )++[email protected]("target", _router_link_targets())+def test_router_links_resolve_through_read_file(target: str) -> None:+ """Each router link is reachable via the read_file tool's skills root."""+ body = json.loads(ReadFileTool().execute(path=target))+ assert body["status"] == "ok", f"{target} did not resolve: {body}"+ assert body["content"].strip()+++# ---------------------------------------------------------------------------+# Lens content contract+# ---------------------------------------------------------------------------++[email protected]("slug", _lens_ids())+def test_lens_has_required_sections(slug: str) -> None:+ """Each lens keeps the sections that make it an operable procedure."""+ text = _lens_text(slug)+ for heading in _REQUIRED_SECTIONS:+ assert heading in text, f"{slug}.md is missing section '{heading}'"++[email protected]("slug", _lens_ids())+def test_lens_carries_disclaimer(slug: str) -> None:+ """Each lens states it is a framework and not investment advice."""+ assert _DISCLAIMER in _lens_text(slug)++[email protected]("slug", _lens_ids())+def test_lens_requires_framework_conditional_verdict(slug: str) -> None:+ """The output contract of each lens demands a framework-conditional verdict.++ Checked inside the ``## Output contract`` section rather than the whole file,+ so the boilerplate disclaimer at the top cannot satisfy it.+ """+ parts = _lens_text(slug).split("## Output contract", 1)+ assert len(parts) == 2, f"{slug}.md has no output-contract section"+ # Prose is hard-wrapped, so collapse whitespace before matching phrases.+ contract = " ".join(parts[1].split())+ assert re.search(r"under (?:this|an?) [\w\- ]{0,40}?framework", contract), (+ f"{slug}.md output contract never requires a framework-conditional verdict"+ )+ assert "not investment advice" in contract, (+ f"{slug}.md output contract omits the not-investment-advice line"+ )++[email protected]("slug", _lens_ids())+def test_lens_is_not_a_stub(slug: str) -> None:+ """Guard against placeholder lens files sneaking into the index."""+ assert len(_lens_text(slug)) > 2_500, f"{slug}.md looks like a stub"+++# ---------------------------------------------------------------------------+# Decoupling from the data layer+# ---------------------------------------------------------------------------+++def _registered_multiword_tool_names() -> List[str]:+ """Return registered tool names containing an underscore.++ Single-word tool names (``bash``, ``pattern``, ``sentiment``) are ordinary+ English words and cannot be distinguished from prose, so only the snake_case+ names are checked.++ Returns:+ Sorted list of multi-word tool names.+ """+ from src.tools import _discover_subclasses++ return sorted({c.name for c in _discover_subclasses() if c.name and "_" in c.name})++[email protected]("slug", _lens_ids())+def test_lens_does_not_hardcode_tool_names(slug: str) -> None:+ """Lenses describe reasoning only; naming a tool would couple them to the data layer."""+ text = _lens_text(slug)+ leaked = [name for name in _registered_multiword_tool_names() if name in text]+ assert not leaked, f"{slug}.md hardcodes tool name(s): {leaked}"+++def test_router_does_not_hardcode_tool_names() -> None:+ """The router routes between lenses by markdown link, not by tool name."""+ text = _router_text()+ leaked = [name for name in _registered_multiword_tool_names() if name in text]+ assert not leaked, f"SKILL.md hardcodes tool name(s): {leaked}"