One rating table; typed thesis triggers; rating-word and gap-direction ingestion rules; clause-bounded labels
Browse filesFiles changed (6)
188 unmodified lines189190191192193194188 unmodified lines"""What a persona sees: the token, its current value and its label."""lines = ["NUMBER TOKENS — write every figure ONLY as its token, e.g. \"the price sits [[PRICE_VS_COMPOSITE]] the market composite\".","Never type a number, percentage, dollar amount or multiple yourself; a sentence that does is removed.","You may use [[OWN_RETURN]] for your own scenario return. Tokens available (token = value — meaning):"]for cid, c in cat.items():if c.deferred:188 unmodified lines189190191192193194195188 unmodified lines"""What a persona sees: the token, its current value and its label."""lines = ["NUMBER TOKENS — write every figure ONLY as its token, e.g. \"the price sits [[PRICE_VS_COMPOSITE]] the market composite\".","Never type a number, percentage, dollar amount or multiple yourself; a sentence that does is removed.","Relationship tokens (\"…above\"/\"…below\") already contain their direction: write \"the price is [[PRICE_VS_COMPOSITE]] the market composite\", never add another \"above\"/\"below\" after them.","You may use [[OWN_RETURN]] for your own scenario return. Tokens available (token = value — meaning):"]for cid, c in cat.items():if c.deferred:
121 unmodified lines1221231241251261271284 unmodified lines13313413513613713813914 unmodified lines154155156157158159160161162163164121 unmodified linesreturn v# ── REPORT ────────────────────────────────────────────────────────────────────────def rules(self, cat, own=None):s = self.statepm_rel = (s.quant.get("price_model") or {}).get("reliability") or {}pr_rel = (s.quant.get("panel_rank") or {}).get("reliability") or {}4 unmodified linesquant_forbidden_phrases=tuple(set(pm_rel.get("forbidden_phrases") or ()) | set(pr_rel.get("forbidden_phrases") or ())),plan_sales_present=bool(ins.get("plan_only") or (ins.get("plan_sale_value") or 0) > 0),officers={r: (v or {}).get("name") for r, v in (s.leadership.get("roles") or {}).items()},own_return_claim=own)def _ingest_seat(self, entry, rules, source):para, rej = P.ingest(entry.get("reasoning") or "", rules, source + ".reasoning")14 unmodified liness.require_stage("ANALYSIS_FINALIZED")cat = C.build_catalog(s, include_deferred=True)own = {"neutral": "SCENARIO_NEUTRAL_RETURN", "bear": "SCENARIO_BEAR_RETURN", "bull": "SCENARIO_BULL_RETURN", "pm": "PM_RETURN"}seats = {role: self._ingest_seat(e, self.rules(cat, own.get(role)), role) for role, e in (seat_prose or {}).items()}summ = (summary_fn or B.call_summary)(B.summary_prompt(s, cat)) or {}if not summ:self.notes.append("summary model unavailable; the report is published without an executive summary")R0 = self.rules(cat)sm, rj = P.ingest(summ.get("summary") or "", R0, "summary")self.rejections += rjth, rk = [], []121 unmodified lines1221231241251261271284 unmodified lines13313413513613713813914014114 unmodified lines156157158159160161162163164165166167168169121 unmodified linesreturn v# ── REPORT ────────────────────────────────────────────────────────────────────────def rules(self, cat, own=None, own_label=None):s = self.statepm_rel = (s.quant.get("price_model") or {}).get("reliability") or {}pr_rel = (s.quant.get("panel_rank") or {}).get("reliability") or {}4 unmodified linesquant_forbidden_phrases=tuple(set(pm_rel.get("forbidden_phrases") or ()) | set(pr_rel.get("forbidden_phrases") or ())),plan_sales_present=bool(ins.get("plan_only") or (ins.get("plan_sale_value") or 0) > 0),officers={r: (v or {}).get("name") for r, v in (s.leadership.get("roles") or {}).items()},own_return_claim=own, own_label=own_label,held_labels=tuple({x for x in [s.value("recommendation.rating"), s.scenarios.get("pm_label")]+ [(s.scenarios.get(k) or {}).get("label") for k in ("bear", "neutral", "bull")] if x}))def _ingest_seat(self, entry, rules, source):para, rej = P.ingest(entry.get("reasoning") or "", rules, source + ".reasoning")14 unmodified liness.require_stage("ANALYSIS_FINALIZED")cat = C.build_catalog(s, include_deferred=True)own = {"neutral": "SCENARIO_NEUTRAL_RETURN", "bear": "SCENARIO_BEAR_RETURN", "bull": "SCENARIO_BULL_RETURN", "pm": "PM_RETURN"}labels = {k: (s.scenarios.get(k) or {}).get("label") for k in ("bear", "neutral", "bull")}labels["pm"] = s.scenarios.get("pm_label")seats = {role: self._ingest_seat(e, self.rules(cat, own.get(role), labels.get(role)), role)for role, e in (seat_prose or {}).items()}summ = (summary_fn or B.call_summary)(B.summary_prompt(s, cat)) or {}if not summ:self.notes.append("summary model unavailable; the report is published without an executive summary")R0 = self.rules(cat, own_label=s.value("recommendation.rating"))sm, rj = P.ingest(summ.get("summary") or "", R0, "summary")self.rejections += rjth, rk = [], []
71 unmodified lines7273747576777 unmodified lines8586878889908 unmodified lines9910010110210310410513 unmodified lines11912012112212312471 unmodified linesplan_sales_present: bool = Falseofficers: dict = field(default_factory=dict) # role → canonical nameown_return_claim: str | None = None # the claim [[OWN_RETURN]] resolves todef _split(text):7 unmodified linesLABEL_WINDOW = 48def label_violations(fragments, prohibited_for):8 unmodified linesif not f.claim_id:ctx += f.textcontinuebefore = ctx[-LABEL_WINDOW:].lower()for bad in (prohibited_for(f.claim_id) or ()):if bad.lower() in before and not DENIAL.search(before[-24:]):out.append((f.claim_id, bad))13 unmodified linesreturn False, f"unknown or unavailable claim token [[{m.group(1)}]]"for cid, bad in label_violations(to_fragments(sentence, rules), lambda c: rules.catalog[c].prohibited):return False, f"[[{cid}]] labelled '{bad}', a label that claim forbids"res = _residual(sentence)mm = MATERIAL_NUMBER.search(res)if mm:71 unmodified lines72737475767778797 unmodified lines878889909192939495968 unmodified lines10510610710810911011113 unmodified lines12512612712812913013113213313413513613713813914071 unmodified linesplan_sales_present: bool = Falseofficers: dict = field(default_factory=dict) # role → canonical nameown_return_claim: str | None = None # the claim [[OWN_RETURN]] resolves toown_label: str | None = None # this author's rating label (one rating table)held_labels: tuple = () # every rating label the analysis actually holdsdef _split(text):7 unmodified linesLABEL_WINDOW = 48CLAUSE = re.compile(r"[:;—–()]") # a label never reaches across a clause boundaryRATING_WORD = re.compile(r"\b(STRONG[ -]BUY|STRONG[ -]SELL|BUY|SELL|HOLD)\b|\b((?:strong[ -])?(?:buy|sell|hold))[ -](?:view|call|rating|recommendation|stance)\b")FIRST_PERSON = re.compile(r"\b(?:I|my|we|our|me)\b")GAP_THEN_DIRECTION = re.compile(r"\[\[([A-Z0-9_]+)\]\]\s+(?:above|below|over|under)\b", re.I)def label_violations(fragments, prohibited_for):8 unmodified linesif not f.claim_id:ctx += f.textcontinuebefore = CLAUSE.split(ctx[-LABEL_WINDOW:])[-1].lower()for bad in (prohibited_for(f.claim_id) or ()):if bad.lower() in before and not DENIAL.search(before[-24:]):out.append((f.claim_id, bad))13 unmodified linesreturn False, f"unknown or unavailable claim token [[{m.group(1)}]]"for cid, bad in label_violations(to_fragments(sentence, rules), lambda c: rules.catalog[c].prohibited):return False, f"[[{cid}]] labelled '{bad}', a label that claim forbids"for m in GAP_THEN_DIRECTION.finditer(sentence):cid = rules.own_return_claim if m.group(1) == "OWN_RETURN" else m.group(1)if getattr(rules.catalog.get(cid), "stype", None) == "GAP":return False, f"[[{m.group(1)}]] already states its direction; a second direction word inverts or doubles it"for m in RATING_WORD.finditer(sentence):lab = re.sub(r"[ -]+", " ", (m.group(1) or m.group(2) or "")).upper()if rules.held_labels and lab not in rules.held_labels:return False, f"rating word '{m.group(0)}' is not a rating this analysis holds"if rules.own_label and FIRST_PERSON.search(sentence) and lab != rules.own_label:return False, f"states its own view as '{lab}' but its rating is {rules.own_label}"res = _residual(sentence)mm = MATERIAL_NUMBER.search(res)if mm:
147 unmodified lines148149150151152153154155156157158147 unmodified linesitems = []for i, t in enumerate(trg[:3]):dest = "the bull case" if t.get("scenario_destination") == "BULL" else "the bear case"move = "rises" if str(t.get("direction_of_change")).lower() in ("up", "increase", "rise", "above", "higher", ">") else "falls"item = [r.t(f"If {t.get('metric_id')} {move} {t.get('condition_operator') or 'past'} "),r.p(f"scenarios.triggers.{i}.threshold", C.TEXT, "trigger threshold (hypothetical)"),r.t(f", the view moves toward {dest}.")]items.append(item)B.append(Block("bullets", "decided", items, title="What would change the view"))# ── debate ──147 unmodified lines148149150151152153154155156157147 unmodified linesitems = []for i, t in enumerate(trg[:3]):dest = "the bull case" if t.get("scenario_destination") == "BULL" else "the bear case"verb = "rises to" if t.get("side") == "above" else "falls to"items.append([r.t(f"If {t.get('metric_id')} {verb} "),r.p(f"scenarios.triggers.{i}.threshold", t.get("threshold_kind") or C.TEXT, "trigger threshold (hypothetical)"),r.t(f" or {'above' if t.get('side') == 'above' else 'below'}, the view moves toward {dest}.")])B.append(Block("bullets", "decided", items, title="What would change the view"))# ── debate ──
390 unmodified lines3913923933943953963977 unmodified lines405406407408409410411412413414415416417418419420390 unmodified linesrows = {}for key in ("bear", "neutral", "bull"):e = seats.get(key) or {}rows[key] = {"return": _f(e.get("return")), "label": e.get("recommendation"), "model": e.get("model"),"confidence": _f(e.get("confidence"))}pb, pn, pu = _f(db.get("p_bear")), _f(db.get("p_neutral")), _f(db.get("p_bull"))for key, p in (("bear", pb), ("neutral", pn), ("bull", pu)):7 unmodified liness.scenarios.pm_return = metric("pm_return", "PM_SCENARIO_RETURN", pm_ret, NTM, accounting_basis=MODEL, unit="ratio",derivation="Σ scenario probability × scenario price return",quality_status=MODEL_ESTIMATE if complete else UNAVAILABLE)s.scenarios.pm_label = db.get("pm_recommendation")s.scenarios.pm_confidence = _f(db.get("pm_confidence"))s.scenarios.panel_complete = bool(db.get("panel_complete")) and completes.scenarios.missing_roles = list(db.get("missing_roles") or [])s.scenarios.probability_audit = db.get("scenario_probability_audit")s.scenarios.evidence = db.get("evidence_lineage")s.scenarios.triggers = [dict(t) for t in (db.get("thesis_triggers") or [])]return stateRATING_BANDS = ((0.20, "STRONG BUY"), (0.10, "BUY"), (-0.05, "HOLD"), (-0.20, "SELL"))390 unmodified lines3913923933943953963973983997 unmodified lines407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453390 unmodified linesrows = {}for key in ("bear", "neutral", "bull"):e = seats.get(key) or {}ret = _f(e.get("return"))# one rating table for every label in the document: a seat's label is the band of its returnrows[key] = {"return": ret, "label": rating_for(round(ret, 3)) if ret is not None else None, "model": e.get("model"),"confidence": _f(e.get("confidence"))}pb, pn, pu = _f(db.get("p_bear")), _f(db.get("p_neutral")), _f(db.get("p_bull"))for key, p in (("bear", pb), ("neutral", pn), ("bull", pu)):7 unmodified liness.scenarios.pm_return = metric("pm_return", "PM_SCENARIO_RETURN", pm_ret, NTM, accounting_basis=MODEL, unit="ratio",derivation="Σ scenario probability × scenario price return",quality_status=MODEL_ESTIMATE if complete else UNAVAILABLE)s.scenarios.pm_label = rating_for(round(pm_ret, 3)) if pm_ret is not None else Nones.scenarios.pm_confidence = _f(db.get("pm_confidence"))s.scenarios.panel_complete = bool(db.get("panel_complete")) and completes.scenarios.missing_roles = list(db.get("missing_roles") or [])s.scenarios.probability_audit = db.get("scenario_probability_audit")s.scenarios.evidence = db.get("evidence_lineage")s.scenarios.triggers = [x for x in (_typed_trigger(t) for t in (db.get("thesis_triggers") or [])) if x]s.scenarios.triggers_dropped = [{"metric_id": t.get("metric_id"), "threshold": t.get("threshold"), "operator": t.get("condition_operator")}for t in (db.get("thesis_triggers") or []) if not _typed_trigger(t)]return state_OPS = {">": "above", ">=": "above", "<": "below", "<=": "below"}def _typed_trigger(t):"""A thesis trigger is a structured judgement: a metric, a comparison and a typed threshold.The PM's JSON threshold is coerced to {value, unit}; a trigger whose comparison or thresholdcannot be typed is not publishable (it stays in QA) rather than rendered as free text."""import re as _reop = str(t.get("condition_operator") or "").strip()raw = str(t.get("threshold") or "").strip()if op not in _OPS or not raw:return Nonem = _re.fullmatch(r"(-|−)?\s*(\$)?\s*(\d+(?:\.\d+)?)\s*(%|x|B|bn|M)?", raw.replace(",", ""))if not m:return Nonev = float(m.group(3)) * (-1 if m.group(1) else 1)unit = m.group(4)if m.group(2) and unit in (None, "B", "bn", "M"):kind, v = ("CURRENCY_BIG", v * (1e9 if unit in ("B", "bn") else 1e6)) if unit else ("CURRENCY", v)elif unit == "%":kind, v = "PCT", v / 100.0elif unit == "x":kind = "MULTIPLE"else:return Nonereturn {"metric_id": t.get("metric_id"), "side": _OPS[op], "threshold": v, "threshold_kind": kind,"scenario_destination": t.get("scenario_destination"), "polarity": t.get("polarity"), "status": t.get("status")}RATING_BANDS = ((0.20, "STRONG BUY"), (0.10, "BUY"), (-0.05, "HOLD"), (-0.20, "SELL"))
379 unmodified lines380381382379 unmodified linesdef test_sensitivity_shifts_are_claims_not_text(good):run, payload, _ = goodassert "Peak market share +25.0%" in payload["markdown"] and "Risk-free rate +1.0 pts" in payload["markdown"]379 unmodified lines380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425379 unmodified linesdef test_sensitivity_shifts_are_claims_not_text(good):run, payload, _ = goodassert "Peak market share +25.0%" in payload["markdown"] and "Risk-free rate +1.0 pts" in payload["markdown"]def test_one_rating_table_labels_every_seat():run, payload, _ = F.run_pipeline(llm=F.llm_result(bear=-0.185))assert run.state.scenarios.get("bear")["label"] == "SELL" # the persona table said STRONG SELLassert "STRONG SELL" not in payload["markdown"]def test_rating_words_must_be_held_by_the_analysis():llm = F.llm_result(bull=0.003) # VST: a +0.3% bull is a HOLDllm["round2"]["gpt"]["reasoning"] = "I maintain a strong-buy view. Demand supports [[OWN_RETURN]]."llm["round2"]["kimi"]["reasoning"] = "I hold my SELL call at [[OWN_RETURN]]."run, payload, _ = F.run_pipeline(llm=llm)assert any("strong-buy" in r.sentence for r in run.rejections)assert "I hold my SELL call" in payload["markdown"]def test_gap_token_followed_by_a_direction_word_is_rejected():llm = F.llm_result()llm["round2"]["kimi"]["reasoning"] = "Consensus is [[FORECAST_EPS_VS_CONSENSUS]] above the engine. My case is [[OWN_RETURN]]."run, payload, _ = F.run_pipeline(llm=llm)assert any("already states its direction" in r.reason for r in run.rejections)def test_triggers_are_typed_or_withheld():llm = F.llm_result()llm["thesis_triggers"] = [{"metric_id": "forecast operating margin", "condition_operator": ">=", "threshold": "15%", "scenario_destination": "BULL"},{"metric_id": "consensus EPS revisions", "condition_operator": "beyond", "threshold": "toward $3.92", "scenario_destination": "BEAR"},{"metric_id": "price", "condition_operator": "<=", "threshold": "$129.79", "scenario_destination": "BEAR"}]run, payload, failed = F.run_pipeline(llm=llm)assert failed is Noneassert [t["threshold_kind"] for t in run.state.scenarios.get("triggers")] == ["PCT", "CURRENCY"]assert run.state.scenarios.get("triggers_dropped")[0]["threshold"] == "toward $3.92"md = payload["markdown"]assert "If forecast operating margin rises to 15.0% or above" in md and "If price falls to $129.79 or below" in mdassert "toward $3.92" not in mddef test_a_label_does_not_reach_across_a_clause_boundary():summ = dict(F.SUMMARY, thesis=["Earnings look weaker than consensus assumes: engine EPS of [[FORECAST_EPS]] is the base."])run, payload, _ = F.run_pipeline(summary=summ)assert not any("FORECAST_EPS" in r.reason for r in run.rejections)
engine/catalog.py+1
engine/pipeline.py+9-4
engine/prose.py+17-1
engine/report_model.py+4-5
engine/state_builder.py+36-3
engine/tests/test_pipeline.py+43