Convert Claude Code or Codex into the most intelligent Deep Research Agent. Collect, search, and synthesize web research into a persistent, searchable wiki that builds on itself. Hosted API + MCP: hyperresearch.ai
Python agentsagentskillscitationsclaude-codecodexcodex-plugincodex-skilldeep-researchdeep-research-agentdeepresearchmcp-serverresearchresearch-agentresearch-tools
feat: run levers with auto-selected register, domain notes, inference depth (#54)
Jordan Gibbs171da3784bd3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e016b9c..fd9d8ba 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,15 @@## [Unreleased]+### Run levers: auto-selected register, domain notes, and inference depth++The pipeline had one hard-coded voice (evaluative-argumentative), so a "teach me X" or "survey the landscape" query got an opinionated verdict report. The Q62 register experiment showed the judge prices register heavily (+2.5 RACE from register alone), so register is now a run-time lever instead of a constant.++- **Three levers, auto-selected in step 1** and written into the decomposition: `register` (`teach` / `survey` / `analyze` / `advocate`, classified from the query's verb shape, defaulting to `analyze` — today's behavior — unless the signal is strong; explicit user directives always win), freeform `domain_notes` (sourcing strategy, evidence norms, recency window), and `inference_depth` (`surface` / `standard` / `deep` — the rabbithole dial; step 4 may upgrade it after seeing the actual corpus via `hpr levers set <tag> inference_depth=deep --rerender`).+- **`hpr levers render <tag>`** materializes the levers into four role-scoped shim files (`shims/{research,drafting,critics,polish}.md`) that spawn templates paste VERBATIM into subagent prompts — the orchestrator never composes posture text. Shims compose additively (register block + domain block + depth block), and division of labor is strict: profiles own every number, levers own posture only (drift-proofed by a test that rejects numeric budget ranges in shim text).+- **The critics and polish auditor are register-aware**, so the pipeline can't undo its own mode: in survey/teach register the dialectic critic flags unfair representation instead of missing commitment, the instruction critic stops demanding rankings the prompt never asked for, and the polish auditor's hedge-striking stands down. In advocate register all three tighten instead. The cite-checker and ship gate receive NO shim — verification never softens by mode.+- **Graceful degradation everywhere:** agents proceed with today's defaults when no directives block arrives, lever-less runs skip the new `levers-rendered` verify check, and `run status` surfaces the chosen levers so a misclassification is visible before hours of pipeline run on it.+### Ship gate enforcement: `run finish` (lessons from the first premier run)The first end-to-end premier benchmark run exposed both prose-only gates failing exactly the way prose gates fail: the orchestrator never invoked `run verify` (a 25,647-word report shipped against a 16K ceiling), and when lint flagged 24 hallucinated/mangled quotes it wrote itself a "false positives" memo and shipped anyway.diff --git a/src/hyperresearch/cli/__init__.py b/src/hyperresearch/cli/__init__.pyindex d797783..4d90502 100644--- a/src/hyperresearch/cli/__init__.py+++ b/src/hyperresearch/cli/__init__.py@@ -131,6 +131,7 @@ from hyperresearch.cli.citecheck_cmd import app as citecheck_appfrom hyperresearch.cli.claims_cmd import app as claims_appfrom hyperresearch.cli.embed_cmd import app as embed_appfrom hyperresearch.cli.escalation_cmd import app as escalation_app+from hyperresearch.cli.levers_cmd import app as levers_appfrom hyperresearch.cli.link import app as link_appfrom hyperresearch.cli.profile_cmd import app as profile_appfrom hyperresearch.cli.run_cmd import app as run_app@@ -142,6 +143,7 @@ app.add_typer(embed_app, name="embed", help="Semantic-search embeddings.")app.add_typer(run_app, name="run", help="Per-run workspaces + manifest (init/status/resume).")app.add_typer(escalation_app, name="escalation", help="Browser-lane queue for blocked fetches.")app.add_typer(citecheck_app, name="citecheck", help="Citation-sentence binding verification.")+app.add_typer(levers_app, name="levers", help="Run levers (register/domain/inference shims).")app.add_typer(sources_app, name="sources", help="Fetched web sources.")app.add_typer(assets_app, name="assets", help="Downloaded images, screenshots, and media.")diff --git a/src/hyperresearch/cli/levers_cmd.py b/src/hyperresearch/cli/levers_cmd.pynew file mode 100644index 0000000..d9936b9--- /dev/null+++ b/src/hyperresearch/cli/levers_cmd.py@@ -0,0 +1,105 @@+"""Run levers — render/update the per-run posture shim files."""++from __future__ import annotations++import typer++from hyperresearch.cli._output import console, output+from hyperresearch.models.output import error, success++app = typer.Typer()+++def _discover(json_output: bool):+ from hyperresearch.core.vault import Vault, VaultError++ try:+ return Vault.discover()+ except VaultError as e:+ if json_output:+ output(error(str(e), "NO_VAULT"), json_mode=True)+ else:+ console.print(f"[red]Error:[/] {e}")+ raise typer.Exit(1) from e+++def _fail(msg: str, code: str, json_output: bool) -> None:+ if json_output:+ output(error(msg, code), json_mode=True)+ else:+ console.print(f"[red]Error:[/] {msg}")+ raise typer.Exit(1)++[email protected]("render")+def levers_render(+ vault_tag: str = typer.Argument(..., help="Run tag (shims land in runs/<tag>/shims/)"),+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),+) -> None:+ """Render the four role shim files from the run's decomposition levers.++ Reads the "levers" block of runs/<tag>/prompt-decomposition.json+ (defaults: register=analyze, inference_depth=standard when absent) and+ writes shims/{research,drafting,critics,polish}.md for the orchestrator+ to paste verbatim into subagent spawn prompts.+ """+ from hyperresearch.core.levers import LeverError, render_shims++ vault = _discover(json_output)+ vault.auto_sync()+ try:+ result = render_shims(vault, vault_tag)+ except LeverError as e:+ _fail(str(e), "LEVER_ERROR", json_output)+ return+ levers = result["levers"]+ if json_output:+ output(success(result, vault=str(vault.root)), json_mode=True)+ else:+ console.print(+ f"[green]Levers rendered:[/] register={levers['register']} "+ f"inference_depth={levers['inference_depth']} "+ f"({len(result['files'])} shim files)"+ )++[email protected]("set")+def levers_set(+ vault_tag: str = typer.Argument(..., help="Run tag"),+ assignments: list[str] = typer.Argument(..., help="key=value pairs (register, inference_depth, domain_notes)"),+ rerender: bool = typer.Option(False, "--rerender", help="Re-render the shim files after updating"),+ json_output: bool = typer.Option(False, "--json", "-j", help="JSON output"),+) -> None:+ """Update the run's levers block (e.g. step 4 upgrading inference_depth).++ Example: hpr levers set my-run inference_depth=deep --rerender+ """+ from hyperresearch.core.levers import LeverError, render_shims, set_levers++ vault = _discover(json_output)+ vault.auto_sync()++ updates: dict = {}+ for pair in assignments:+ if "=" not in pair:+ _fail(f"expected key=value, got '{pair}'", "LEVER_ERROR", json_output)+ key, value = pair.split("=", 1)+ updates[key.strip()] = value.strip()++ try:+ levers = set_levers(vault, vault_tag, updates)+ result = {"levers": levers, "rerendered": rerender}+ if rerender:+ result = {**render_shims(vault, vault_tag), "rerendered": True}+ except LeverError as e:+ _fail(str(e), "LEVER_ERROR", json_output)+ return+ if json_output:+ output(success(result, vault=str(vault.root)), json_mode=True)+ else:+ lv = result["levers"]+ suffix = " (shims re-rendered)" if rerender else ""+ console.print(+ f"[green]Levers updated:[/] register={lv['register']} "+ f"inference_depth={lv['inference_depth']}{suffix}"+ )diff --git a/src/hyperresearch/cli/run_cmd.py b/src/hyperresearch/cli/run_cmd.pyindex 9f52e56..4be3c09 100644--- a/src/hyperresearch/cli/run_cmd.py+++ b/src/hyperresearch/cli/run_cmd.py@@ -105,6 +105,12 @@ def run_status(output(success(summary, vault=str(vault.root)), json_mode=True)else:console.print(f"[bold]{summary['vault_tag']}[/] ({summary['profile']}) status: {summary['status']}")+ levers = summary.get("levers")+ if levers:+ console.print(+ f" levers: register={levers.get('register', 'analyze')} "+ f"inference_depth={levers.get('inference_depth', 'standard')}"+ )esc = summary.get("escalations")if esc and (esc.get("queued") or esc.get("needs_human")):console.print(diff --git a/src/hyperresearch/core/hooks.py b/src/hyperresearch/core/hooks.pyindex ec0137f..2815f50 100644--- a/src/hyperresearch/core/hooks.py+++ b/src/hyperresearch/core/hooks.py@@ -129,6 +129,11 @@ depth packet becomes a weak draft section.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.This is the north star for every decision you make. If a locus doesn'tserve the research_query, reject it — no matter how interesting it is.@@ -329,6 +334,11 @@ reading of the evidence.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **locus**: the full locus object from the loci-analyst output (name,flavor, one_line, rationale, corpus_evidence, suggested_starting_urls,suggested_searches, and — for dialectical loci — opposing_positions).@@ -600,6 +610,11 @@ actually gathered, not guesses.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. Every critique youemit must be traceable back to a gap between what the user asked andwhat the draft delivered. A finding that doesn't serve the@@ -662,6 +677,12 @@ Use the **Write tool** to save your findings JSON to `output_path`. Do NOT use Bthe vault covers. Should be patched.- **Severity `minor`** — a hedge or qualifier would strengthen the claimbut the draft isn't wrong.+- **Register-conditional standard.** Your commitment expectations follow+ the Run directives block when one is present: in teach or survey+ register, even-handed hedged treatment of a contested point is CORRECT+ — flag unfair or missing representation of a view instead of the+ absence of a committed position. In advocate register, the steel-man's+ quality is the central standard and a weak opposing case is critical.- **At most << p.critic_finding_caps.dialectic >> findings.** If you see more than << p.critic_finding_caps.dialectic >>, return the << p.critic_finding_caps.dialectic >> mostload-bearing. Returning 40 small findings buries the critical ones.- **Never propose deleting and retyping an entire section.** That is@@ -716,6 +737,11 @@ rather than gesturing at it from a distance.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. Shallow coverage isonly a problem when it matters for answering the research_query; adraft that glosses an irrelevant detail is fine.@@ -819,6 +845,11 @@ because the orchestrator's structural choices buried them.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. A coverage gap isonly a real gap if the missing topic is something the research_queryimplies. Don't flag orthogonal material that happens to be in the@@ -974,6 +1005,11 @@ hand findings to the patcher (Layer 6). You do NOT modify the draft.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.This is THE primary input for you — your critiques are measured byhow the draft maps to THIS text, in THIS shape, with THESE named@@ -1209,6 +1245,11 @@ let these crowd out core instruction-following findings. Use- **Keep recommendations surgical.** Same discipline as the other critics —your recommendation should describe a minimal change that addressesthe atomic item.+- **Register-conditional.** When the Run directives block sets teach or+ survey register, do not emit findings demanding a committed ranking or+ verdict the user's prompt did not itself name — coverage-shaped+ delivery is correct in those registers. Format cues the prompt names+ explicitly always win, regardless of register.- **For `wrong-format` findings**, a full format change (ranked-list→ FAQ) is structural — flag `severity: critical` with a descriptionin `issue`. These escalate to the orchestrator, not the revisor.@@ -1291,6 +1332,11 @@ Concretely:## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.Before applying any finding, ask: does this edit bring the draftcloser to answering this? An edit that satisfies a critic's finding@@ -1444,6 +1490,11 @@ attempt it yourself.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.Use it to check prompt adherence — does the final draft actuallydeliver what the user asked for? Mismatches go in `escalations`, not@@ -1632,6 +1683,12 @@ section number.### 3a. Hedge language that softens committed claims+**Register guard:** when the Run directives block sets teach or survey+register, SKIP the commitment-forcing rules in this section — even-handed+hedged language on contested points is correct there — and apply only+the hedge-stack rule. In advocate register, apply this section at+maximum strength.+The draft upstream was built to commit to positions. If the patcheror any earlier layer added hedging verbs that soften a claim theparagraph already supports with evidence, strike the hedge. This is@@ -1800,6 +1857,11 @@ all three. Your draft is an INPUT to the synthesis, not the final output.## Inputs (from the main orchestrator)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.- **query_file_path**: path to the persisted query file.- **vault_tag**: corpus tag.@@ -1995,6 +2057,11 @@ mental model; writing the final report is a fresh act.## Inputs (from the orchestrator)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.- **query_file_path**: path to the persisted query file.- **draft_paths**: array of 3 paths — `[research/runs/<vault_tag>/temp/draft-a.md,@@ -2079,7 +2146,9 @@ permitted to be uneven — pass 2 cleans it up. Goals for pass 1:section's topic. Don't gesture at them — argue through them.7. **Commit, don't hedge.** Where the synthesis plan says "commit to sideX on tension Y," commit. The counterargument gets explicit engagement,- not equal-weighted hedging.+ not equal-weighted hedging. (Register-conditional: the Run directives+ block adjusts this posture — in teach or survey register, present+ contested points even-handedly instead of committing.)8. **Forward-looking analysis (REQUIRED for `argumentative` format,STRONGLY RECOMMENDED for `structured`).** Include at least onesubstantial paragraph (200+ chars) or a dedicated subsection@@ -2379,6 +2448,11 @@ apply. You are advisory.## Inputs (from the orchestrator)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL.- **draft_path**: `research/notes/final_report_<vault_tag>.md` — the polished report.- **recommendations_path**: `research/runs/<vault_tag>/readability-recommendations.json`@@ -2585,6 +2659,11 @@ analyst, fetch new sources, or move on.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: canonical, verbatim. GOSPEL. Your analysis isscoped to this question — the digest should surface what matters forthis specific research_query, not a generic abstract.@@ -2745,6 +2824,11 @@ You are a research fetcher with agency to chase primary sources. Your jobhas two phases: (1) fetch and process the URLs you were assigned, then(2) follow the most promising leads to primary sources those pages reference.+Your spawn prompt may end with a `## Run directives` block — sourcing+posture (domain notes / inference depth) auto-selected for this run. It+is BINDING and wins wherever it adjusts a default in this prompt. No+block = this prompt's defaults apply unchanged.+## Period-pinned filings (READ FIRST)When the parent agent's research_query names a specific historical reporting@@ -3004,6 +3088,11 @@ to drafting.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim. GOSPEL.- **corpus_tag**: vault tag for searching.- **comparisons_path**: `research/runs/<vault_tag>/comparisons.md`@@ -3108,6 +3197,11 @@ You are the hyperresearch browser-lane fetcher. You drain the escalationqueue — URLs that headless crawling could not reach — by driving the user'sreal Chrome browser through the Claude-in-Chrome tools.+Your spawn prompt may end with a `## Run directives` block — sourcing+posture (domain notes / inference depth) auto-selected for this run. It+is BINDING for how you read and summarize what you fetch. It never+overrides the hard scope boundary below.+## Hard scope boundary (read first)You NEVER attempt to solve, bypass, or automate CAPTCHAs, 2FA prompts, ordiff --git a/src/hyperresearch/core/levers.py b/src/hyperresearch/core/levers.pynew file mode 100644index 0000000..e2bca49--- /dev/null+++ b/src/hyperresearch/core/levers.py@@ -0,0 +1,330 @@+"""Run levers: per-run posture shims rendered into shim files.++Levers are run-time choices step 1 writes into prompt-decomposition.json:++ "levers": {+ "register": "teach" | "survey" | "analyze" | "advocate",+ "register_confidence": "high" | "low",+ "domain_notes": "<2-3 freeform sentences>",+ "inference_depth": "surface" | "standard" | "deep",+ "rationale": {...}+ }++`render_shims` composes them into four role-scoped shim files under+`research/runs/<tag>/shims/` which the orchestrator pastes VERBATIM into+subagent spawn prompts. Division of labor: install-time profiles own every+number (source targets, budgets, word ceilings); levers own posture only.+Shim text must never restate a numeric budget.++The cite-checker and the ship gate receive no shim by design: verification+is register-independent and never softens by mode.+"""++from __future__ import annotations++import json++REGISTERS = ("teach", "survey", "analyze", "advocate")+INFERENCE_DEPTHS = ("surface", "standard", "deep")+ROLES = ("research", "drafting", "critics", "polish")++DEFAULT_LEVERS = {+ "register": "analyze",+ "register_confidence": "high",+ "domain_notes": "",+ "inference_depth": "standard",+}+++class LeverError(Exception):+ pass+++# ---------------------------------------------------------------------------+# Register posture blocks, per role. Additive composition only: one register+# block + one domain block + one inference block per file. Never author the+# register x depth cross-product.+# ---------------------------------------------------------------------------++_REGISTER_DRAFTING = {+ "analyze": """\+Default evaluative posture (this run confirms your prompt's defaults).+Write authoritative analysis: commit to the positions the evidence+supports, engage the strongest counterarguments explicitly, and rank+when the query asks which option wins. No adjustment to your prompt.""",+ "teach": """\+TEACH register. The reader is a motivated non-specialist who wants to+UNDERSTAND this subject, not to receive a verdict. Voice: patient+expert. Extend the primer discipline downward: subsections open with+plain-language explanation too, and every term is defined at first+use. A short glossary section is permitted where the vocabulary is+heavy. Frame conclusions as "what the evidence supports" rather than+rankings; a committed top-pick is NOT required. On contested points,+present each side's best case fairly before saying which way the+evidence leans. Worked examples and concrete analogies are encouraged+wherever they make a mechanism click.""",+ "survey": """\+SURVEY register. The product is a map of the field, not a verdict.+Voice: neutral cartographer. Coverage and organization outrank+argument: name every school of thought, position each approach+relative to the others, and prefer comparison tables wherever three+or more entities share dimensions. A committed thesis or ranking is+NOT required; where the field disagrees, chart the disagreement and+attribute each position instead of resolving it. Keep evaluative+asides brief and clearly sourced. Dramatic standalone sentences do+not belong in this register.""",+ "advocate": """\+ADVOCATE register. The report defends ONE thesis, named early and+argued throughout. Every section either advances the thesis or+disarms an objection to it. A steel-man treatment of the strongest+opposing case is MANDATORY: state the objection at full strength,+then answer it with evidence. Commitment is maximal; hedges belong+only on unverified secondhand specifics, never on the thesis or its+supporting chain.""",+}++_REGISTER_CRITICS = {+ "analyze": """\+Default evaluative posture (this run confirms your prompt's defaults).+Commitment checks apply as written: a draft that hedges where its own+evidence supports a stronger claim is a finding.""",+ "teach": """\+TEACH register. Adjust your failure modes: hedged neutrality on+genuinely contested points is CORRECT in this register, not a+finding. Instead, flag places where a view is represented unfairly+or a mechanism is asserted without being explained. Do not demand a+committed ranking; the instruction-following standard is that the+reader comes away understanding the subject. Findings that would+convert patient explanation into verdict-first argument are wrong+for this run.""",+ "survey": """\+SURVEY register. Adjust your failure modes: the draft is a map, not+an argument. Do not flag the absence of a committed thesis or+ranking. DO flag: a school of thought the corpus supports that the+draft omits, imbalanced coverage (one approach detailed, a peer+approach skimmed), unattributed resolution of a live disagreement,+and comparisons left in prose that belong in tables.""",+ "advocate": """\+ADVOCATE register. Tighten the commitment checks: the draft defends+one thesis, and the quality of its steel-man is your central+standard. A weakly stated or strawmanned opposing case is a critical+finding. Hedging on the thesis or its supporting chain is a finding;+hedging on unverified secondhand specifics is honesty and stays.""",+}++_REGISTER_POLISH = {+ "analyze": """\+Default evaluative posture (this run confirms your prompt's defaults).+Hedge-striking and the one-kicker-per-section budget apply as+written.""",+ "teach": """\+TEACH register. Do NOT strike hedges to force commitment: on+contested points, even-handed language is correct here, and the+hedge rule applies only to hedge-stacks and filler softeners.+Kicker budget is effectively zero: fold dramatic standalone+sentences into plain prose. Preserve primers, definitions, worked+examples, and glossary material; they are the product, not filler.""",+ "survey": """\+SURVEY register. Do NOT strike hedges to force commitment: neutral,+attributed language on disagreements is correct here, and the hedge+rule applies only to hedge-stacks and filler softeners. Kicker+budget is effectively zero: fold dramatic standalone sentences into+plain prose. Preserve coverage material and comparison tables even+where they read as unopinionated; the map is the product.""",+ "advocate": """\+ADVOCATE register. Hedge-striking at maximum: any softener on the+thesis or its supporting chain goes, per the existing evidence-backed+rule. Preserve the steel-man section intact; trimming the opposing+case's best evidence is forbidden.""",+}++# ---------------------------------------------------------------------------+# Inference-depth blocks.+# ---------------------------------------------------------------------------++_INFERENCE_RESEARCH = {+ "standard": """\+Standard depth (this run confirms your prompt's defaults). Follow the+normal sourcing playbook.""",+ "surface": """\+SURFACE depth. The question is answerable from authoritative+consensus sources. Prefer canonical reviews, primary standards, and+high-citation papers; stop when they agree. Do not open rabbitholes+or chase gray literature; a consistent consensus answer ends the+search.""",+ "deep": """\+DEEP inference. The surface web underdetermines this question, so the+value is in what takes digging: gray literature, regulatory and+financial filings, conference posters, theses, and named-practitioner+forum or mailing-list posts are all in scope. Treat audited absences+as findings: when a figure SHOULD be published and is not, search for+it hard, then record the absence itself with what you searched.+Lower-authority sources are usable WITH their provenance and+reliability tagged in the note. Spend toward the top of your assigned+budgets when a lead is genuinely load-bearing.""",+}++_INFERENCE_DRAFTING = {+ "standard": """\+Standard depth (this run confirms your prompt's defaults).""",+ "surface": """\+SURFACE depth. Report the consensus; do not construct novel inference+chains beyond what sources state directly.""",+ "deep": """\+DEEP inference. Explicit inference chains are licensed WITH+provenance stated: when no source states X but sourced claims A and B+jointly imply it, say so in exactly that shape, citing A and B. Never+present an inference as a sourced fact; the citation checker verifies+number-bearing sentences pair-by-pair and an inference dressed as a+quote or finding will be flagged. Audited absences (what the record+should contain but does not) are reportable findings.""",+}++_INFERENCE_CRITICS = {+ "standard": """\+Standard depth (this run confirms your prompt's defaults).""",+ "surface": """\+SURFACE depth. Flag any inference chain that goes beyond what the+cited sources state; this run stays on consensus ground.""",+ "deep": """\+DEEP inference. Inferential syntheses are expected in this draft; do+not flag inference itself. DO flag inference without provenance+discipline: any derived claim that fails to name the sourced claims+it derives from, and any audited absence asserted without stating+what was searched.""",+}+++def validate_levers(levers: dict) -> dict:+ """Merge with defaults and validate enums. Returns the resolved dict."""+ if not isinstance(levers, dict):+ raise LeverError("levers must be an object")+ resolved = {**DEFAULT_LEVERS, **{k: v for k, v in levers.items() if v is not None}}+ if resolved["register"] not in REGISTERS:+ raise LeverError(+ f"unknown register '{resolved['register']}' (one of {', '.join(REGISTERS)})"+ )+ if resolved["inference_depth"] not in INFERENCE_DEPTHS:+ raise LeverError(+ f"unknown inference_depth '{resolved['inference_depth']}' "+ f"(one of {', '.join(INFERENCE_DEPTHS)})"+ )+ if not isinstance(resolved.get("domain_notes", ""), str):+ raise LeverError("domain_notes must be a string")+ return resolved+++def _header(levers: dict) -> str:+ return (+ "## Run directives\n\n"+ "Auto-selected for this run in step 1; binding wherever they adjust "+ "a default in your prompt. Absent instructions here leave your "+ "prompt's defaults untouched.\n\n"+ f"- register: {levers['register']}\n"+ f"- inference depth: {levers['inference_depth']}\n"+ )+++def _domain_block(levers: dict) -> str:+ notes = (levers.get("domain_notes") or "").strip()+ if not notes:+ return ""+ return f"\n### Domain notes\n\n{notes}\n"+++def compose_shims(levers: dict) -> dict[str, str]:+ """Compose the four role shims. Additive: register + domain + depth."""+ lv = validate_levers(levers)+ reg, depth = lv["register"], lv["inference_depth"]++ research = (+ _header(lv)+ + _domain_block(lv)+ + f"\n### Inference depth\n\n{_INFERENCE_RESEARCH[depth]}\n"+ )+ drafting = (+ _header(lv)+ + f"\n### Register posture\n\n{_REGISTER_DRAFTING[reg]}\n"+ + _domain_block(lv)+ + f"\n### Inference depth\n\n{_INFERENCE_DRAFTING[depth]}\n"+ )+ critics = (+ _header(lv)+ + f"\n### Register posture\n\n{_REGISTER_CRITICS[reg]}\n"+ + f"\n### Inference depth\n\n{_INFERENCE_CRITICS[depth]}\n"+ )+ polish = _header(lv) + f"\n### Register posture\n\n{_REGISTER_POLISH[reg]}\n"++ return {"research": research, "drafting": drafting, "critics": critics, "polish": polish}+++def _decomposition_path(vault, vault_tag: str):+ return vault.run_dir(vault_tag) / "prompt-decomposition.json"+++def read_levers(vault, vault_tag: str) -> dict:+ """Levers block from the run's decomposition; defaults when absent."""+ dpath = _decomposition_path(vault, vault_tag)+ if not dpath.exists():+ raise LeverError(f"no prompt-decomposition.json for run '{vault_tag}' ({dpath})")+ try:+ decomp = json.loads(dpath.read_text(encoding="utf-8"))+ except json.JSONDecodeError as e:+ raise LeverError(f"corrupt prompt-decomposition.json: {e}") from e+ return validate_levers(decomp.get("levers") or {})+++def set_levers(vault, vault_tag: str, updates: dict) -> dict:+ """Update the decomposition's levers block in place. Returns resolved levers."""+ dpath = _decomposition_path(vault, vault_tag)+ if not dpath.exists():+ raise LeverError(f"no prompt-decomposition.json for run '{vault_tag}' ({dpath})")+ decomp = json.loads(dpath.read_text(encoding="utf-8"))+ levers = {**(decomp.get("levers") or {}), **updates}+ resolved = validate_levers(levers) # raises before any write+ decomp["levers"] = levers+ dpath.write_text(json.dumps(decomp, indent=2) + "\n", encoding="utf-8")+ return resolved+++def render_shims(vault, vault_tag: str) -> dict:+ """Render the four shim files from the run's decomposition levers.++ Records the resolved levers on the run manifest when one exists (a+ render outside a managed run is legal and simply skips the manifest).+ """+ levers = read_levers(vault, vault_tag)+ shims = compose_shims(levers)++ shims_dir = vault.run_dir(vault_tag) / "shims"+ shims_dir.mkdir(parents=True, exist_ok=True)+ written = []+ for role in ROLES:+ path = shims_dir / f"{role}.md"+ path.write_text(shims[role], encoding="utf-8")+ written.append(str(path))++ from hyperresearch.core.runs import RunError, _save, load_manifest, record_event++ try:+ manifest = load_manifest(vault, vault_tag)+ except RunError:+ manifest = None+ if manifest is not None:+ manifest["levers"] = {+ "register": levers["register"],+ "inference_depth": levers["inference_depth"],+ "domain_notes": levers.get("domain_notes", ""),+ }+ _save(vault, vault_tag, manifest)+ record_event(+ vault,+ vault_tag,+ {+ "type": "levers",+ "register": levers["register"],+ "inference_depth": levers["inference_depth"],+ },+ )++ return {"levers": levers, "files": written}diff --git a/src/hyperresearch/core/runs.py b/src/hyperresearch/core/runs.pyindex bbb3559..987d74e 100644--- a/src/hyperresearch/core/runs.py+++ b/src/hyperresearch/core/runs.py@@ -358,14 +358,33 @@ def verify_run(vault, vault_tag: str) -> dict:decomp_path = run_dir / "prompt-decomposition.json"response_format = Nonerequired_headings: list[str] = []+ declares_levers = Falseif decomp_path.exists():try:decomp = json.loads(decomp_path.read_text(encoding="utf-8-sig"))response_format = decomp.get("response_format")required_headings = decomp.get("required_section_headings", []) or []+ declares_levers = bool(decomp.get("levers"))except json.JSONDecodeError:check("decomposition-readable", False, "prompt-decomposition.json is not valid JSON")+ # Runs that declared levers must have rendered the shim files the+ # spawn contract pastes downstream. Lever-less runs (pre-levers or+ # defaults-only) skip the check entirely.+ if declares_levers:+ from hyperresearch.core.levers import ROLES++ missing_shims = [+ role for role in ROLES+ if not (run_dir / "shims" / f"{role}.md").exists()+ ]+ check(+ "levers-rendered",+ not missing_shims,+ "all shim files present" if not missing_shims+ else f"missing shims: {missing_shims} (run `hpr levers render {vault_tag}`)",+ )+if response_format and response_format in profile.word_targets:low, high = profile.word_targets[response_format]wc = len(report_text.split())diff --git a/src/hyperresearch/skills/hyperresearch-1-decompose.md b/src/hyperresearch/skills/hyperresearch-1-decompose.mdindex 9f9d007..cf9d5e1 100644--- a/src/hyperresearch/skills/hyperresearch-1-decompose.md+++ b/src/hyperresearch/skills/hyperresearch-1-decompose.md@@ -90,7 +90,14 @@ Read both before starting. The vault_tag is in the scaffold's "Run config" secti"scope_conditions": ["urban rail specifically, not mainline"],"pipeline_tier": "full","response_format": "argumentative",- "citation_style": "wikilink"+ "citation_style": "wikilink",+ "levers": {+ "register": "analyze",+ "register_confidence": "high",+ "domain_notes": "Sourcing: academic APIs first (arXiv, Nature); recency matters within 24 months for hardware claims; measured figures outrank vendor claims.",+ "inference_depth": "standard",+ "rationale": {"register": "query asks which approaches are most effective — evaluation-shaped", "inference_depth": "surface literature appears rich; revisit at loci analysis"}+ }}```@@ -133,6 +140,25 @@ Read both before starting. The vault_tag is in the scaffold's "Run config" secti**Wrapper override:** if `research/wrapper_contract.json` exists and specifies `citation_style`, it overrides the default. The benchmark harness sets `"inline"` via wrapper_contract so RACE evaluators can read numbered references; everything else gets the wikilink default.+ **`levers`** — run-time posture, auto-selected here and rendered into shim files that every downstream spawn receives. Three fields:++ **`register`** — the report's voice. Classify from the query's verb shape:++ | Register | Signal words / patterns |+ |----------|------------------------|+ | `"teach"` | "explain", "how does X work", "help me understand", "walk me through", "what is X and why" |+ | `"survey"` | "overview of", "survey", "landscape", "compile", "list the approaches", "what are the main X" — coverage-shaped, no verdict requested |+ | `"analyze"` | "evaluate", "assess", "compare and determine", "which is most effective", "feasibility of" — evaluation-shaped (the default) |+ | `"advocate"` | "should we", "argue for/against", "make the case", "recommend a course of action" |++ **Confidence rule:** set `register_confidence`. Deviate from `"analyze"` ONLY when the signal is strong (`"high"` confidence); ambiguous or mixed-signal queries get `"analyze"` with `"low"` confidence. A wrong register costs more than a default one.++ **Precedence:** an explicit user directive in the query ("make it a survey", "just teach me", "mode=teach") ALWAYS wins over your classification. If `research/wrapper_contract.json` has a `levers` key, it wins over classification but not over explicit user text.++ **`domain_notes`** — 2-3 freeform sentences: sourcing strategy for this topic (academic-first? primary documents? filings?), evidence norms (what counts as strong here), and the recency window that matters. Always write them; downstream research and drafting agents read them verbatim.++ **`inference_depth`** — `"surface"` (bounded question, authoritative consensus suffices), `"standard"` (default), or `"deep"` (the answer likely lives beyond the clear web: gray literature, filings, inference over absences). This is PROVISIONAL — step 4 re-evaluates it against the actual corpus and may upgrade it.+8. **Coverage matrix self-audit.** Re-read the verbatim query. Walk through it phrase by phrase and extract every **significant noun phrase, proper noun, technical term, and category name**. For each:- Does it map to at least one atomic item in the decomposition?- Is the decomposition's interpretation **as broad as the phrase's natural scope**? (e.g., "SaaS applications" must not be narrowed to "POS SaaS"; "rugged tablets" must not be collapsed into "payment terminals")@@ -154,12 +180,21 @@ Read both before starting. The vault_tag is in the scaffold's "Run config" secti9. **Update the scaffold.** Append a "Tier rationale" subsection to `research/runs/<vault_tag>/scaffold.md` with a 2-3 sentence justification for the tier classification.+10. **Render the lever shims:**++ ```bash+ $HPR levers render <vault_tag> -j+ ```++ This writes `research/runs/<vault_tag>/shims/{research,drafting,critics,polish}.md` from the levers block. Later steps paste these files VERBATIM into subagent spawn prompts — you never compose or edit shim text yourself. If the command errors on an enum value, fix the levers block in the decomposition and re-run it.+---## Exit criterion- `research/runs/<vault_tag>/prompt-decomposition.json` exists, is valid JSON, every atomic item traces to the research_query-- `pipeline_tier` + `response_format` + `citation_style` are all set+- `pipeline_tier` + `response_format` + `citation_style` are all set, and the `levers` block is present (register, domain_notes, inference_depth)+- `$HPR levers render` succeeded — all four shim files exist under `research/runs/<vault_tag>/shims/`- `research/runs/<vault_tag>/temp/coverage-matrix.md` exists with **zero `Gap? = YES` rows**- `research/runs/<vault_tag>/scaffold.md` includes a Tier rationale subsectiondiff --git a/src/hyperresearch/skills/hyperresearch-10-triple-draft.md b/src/hyperresearch/skills/hyperresearch-10-triple-draft.mdindex 6a5ec44..ffe65a2 100644--- a/src/hyperresearch/skills/hyperresearch-10-triple-draft.md+++ b/src/hyperresearch/skills/hyperresearch-10-triple-draft.md@@ -173,6 +173,8 @@ prompt: |- citation_style: "<wikilink|inline|none>"- modality: "<collect|synthesize|compare|forecast>"+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/drafting.md here, verbatim.+Read every note on must_read_note_ids before writing. Do NOT surveythe vault — your reading list is curated. Do NOT fetch new sources.Write your draft from your assigned angle, citing your curated sources.diff --git a/src/hyperresearch/skills/hyperresearch-11-synthesize.md b/src/hyperresearch/skills/hyperresearch-11-synthesize.mdindex c22eea5..62fad4c 100644--- a/src/hyperresearch/skills/hyperresearch-11-synthesize.md+++ b/src/hyperresearch/skills/hyperresearch-11-synthesize.md@@ -179,6 +179,8 @@ prompt: |- response_format: "<short|structured|argumentative>"- citation_style: "<wikilink|inline|none>"+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/drafting.md here, verbatim.+Read everything. Write pass 1 to pass1_output_path. Then audit pass 1for redundancy, voice consistency, weak sections, and length, andwrite the cleaned pass 2 to final_output_path. Do not paste paragraphsdiff --git a/src/hyperresearch/skills/hyperresearch-12-critics.md b/src/hyperresearch/skills/hyperresearch-12-critics.mdindex 9af2f06..1765712 100644--- a/src/hyperresearch/skills/hyperresearch-12-critics.md+++ b/src/hyperresearch/skills/hyperresearch-12-critics.md@@ -53,6 +53,8 @@ Read these inputs:- output_path: research/runs/<vault_tag>/critic-findings-<critic-name>.json- vault_tag: <vault_tag>- decomposition_path: research/runs/<vault_tag>/prompt-decomposition.json (instruction-critic only)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/critics.md here, verbatim.```3. **Wait for all critics.** If one fails, you can proceed with the partial set, but log the absence to the run log — the patch pass is less robust with missing critic coverage. **Do NOT skip the instruction-critic specifically** — it's the only critic measuring prompt adherence, which is the dimension with the widest variance.diff --git a/src/hyperresearch/skills/hyperresearch-13-gap-fetch.md b/src/hyperresearch/skills/hyperresearch-13-gap-fetch.mdindex a18a335..2fa10e0 100644--- a/src/hyperresearch/skills/hyperresearch-13-gap-fetch.md+++ b/src/hyperresearch/skills/hyperresearch-13-gap-fetch.md@@ -62,6 +62,8 @@ Read these inputs:- vault_tag: <vault_tag>- urls: [<gap-targeted URLs>]- extra_tags: ["post-critic-fill"]++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```Each fetcher: fetches, quality-checks, summarizes, extracts claims (same procedure as step 2). Tags notes with `vault_tag` + `post-critic-fill`. Writes claims to `research/runs/<vault_tag>/temp/claims-<note-id>.json`.diff --git a/src/hyperresearch/skills/hyperresearch-14-patcher.md b/src/hyperresearch/skills/hyperresearch-14-patcher.mdindex 1be0e7f..2d547ad 100644--- a/src/hyperresearch/skills/hyperresearch-14-patcher.md+++ b/src/hyperresearch/skills/hyperresearch-14-patcher.md@@ -89,6 +89,8 @@ prompt: |]- patch_log_path: research/runs/<vault_tag>/patch-log.json (already stubbed)- evidence_digest_path: research/runs/<vault_tag>/temp/evidence-digest.md++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/critics.md here, verbatim.```The patcher's job:diff --git a/src/hyperresearch/skills/hyperresearch-15-polish.md b/src/hyperresearch/skills/hyperresearch-15-polish.mdindex 17c9af5..40e5a08 100644--- a/src/hyperresearch/skills/hyperresearch-15-polish.md+++ b/src/hyperresearch/skills/hyperresearch-15-polish.md@@ -58,6 +58,8 @@ prompt: |YOUR INPUTS:- draft_path: research/notes/final_report_<vault_tag>.md- polish_log_path: research/runs/<vault_tag>/polish-log.json (already stubbed)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/polish.md here, verbatim.```The polish auditor strips:diff --git a/src/hyperresearch/skills/hyperresearch-16-readability-audit.md b/src/hyperresearch/skills/hyperresearch-16-readability-audit.mdindex 633ca7a..ad7c016 100644--- a/src/hyperresearch/skills/hyperresearch-16-readability-audit.md+++ b/src/hyperresearch/skills/hyperresearch-16-readability-audit.md@@ -57,6 +57,8 @@ prompt: |- draft_path: research/notes/final_report_<vault_tag>.md- recommendations_path: research/runs/<vault_tag>/readability-recommendations.json+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/polish.md here, verbatim.+Write recommendations as a JSON array per the schema in your agentprompt. Cap at << p.readability_rec_cap >> recommendations, prioritized by impact.```diff --git a/src/hyperresearch/skills/hyperresearch-2-width-sweep.md b/src/hyperresearch/skills/hyperresearch-2-width-sweep.mdindex f7427a7..e74c94f 100644--- a/src/hyperresearch/skills/hyperresearch-2-width-sweep.md+++ b/src/hyperresearch/skills/hyperresearch-2-width-sweep.md@@ -150,6 +150,8 @@ prompt: |- vault_tag: <vault_tag>- urls: [<batch URLs, exactly as assigned — with each URL's utility score when scored, e.g. "https://... (utility: 14)">]- batch_id: <number>++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```**CRITICAL: no token waste.** Each fetcher gets ONLY its batch. No fetcher searches for new URLs or duplicates another fetcher's work. If a fetcher finishes early, it's done.@@ -263,6 +265,8 @@ prompt: |YOUR INPUTS:- vault_tag: <vault_tag>- drain up to 10 items (claim via `$HPR escalation claim --tag <vault_tag>`)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```**When the browser-fetcher returns with `needs_human` items** (CAPTCHAs, logins, 2FA — it NEVER solves these itself):@@ -315,6 +319,8 @@ prompt: |- source_note_id: <vault note id of the long source>- output_path: research/runs/<vault_tag>/temp/source-analysis-<source_note_id>.md- vault_tag: <vault_tag>++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```---diff --git a/src/hyperresearch/skills/hyperresearch-4-loci-analysis.md b/src/hyperresearch/skills/hyperresearch-4-loci-analysis.mdindex e1f111c..af8eb46 100644--- a/src/hyperresearch/skills/hyperresearch-4-loci-analysis.md+++ b/src/hyperresearch/skills/hyperresearch-4-loci-analysis.md@@ -52,6 +52,8 @@ Survey the corpus: `$HPR note list --tag <vault_tag> --all -j` to confirm width- corpus_tag: <vault_tag>- analyst_id: "a" (for one) / "b" (for the other)- output_path: research/runs/<vault_tag>/loci-a.json (or research/runs/<vault_tag>/loci-b.json)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```2. **Wait for both.** If one fails, proceed with the single successful output. If both fail (empty loci lists), tell the user the width sweep was too thin and stop — do not force depth on a weak corpus.@@ -101,6 +103,14 @@ Survey the corpus: `$HPR note list --tag <vault_tag> --all -j` to confirm width6. **Decide investigator count.** Spawn ONE depth-investigator (in step 5) per locus with `source_budget > 0`, capped at << p.investigator_max >>. If only 1 locus passes scoring, spawn 1.+7. **Reconsider `inference_depth` against the actual corpus.** Step 1 set it provisionally from the query alone; you have now seen what the surface web actually holds. Upgrade to `deep` when the corpus shows the load-bearing questions are underdetermined by clearly-published sources — high-uncertainty loci where the missing evidence is gray literature, filings, or unpublished figures rather than papers nobody fetched yet. Downgrade to `surface` only if step 1 chose `deep` and the corpus turned out rich and univocal. To change it:++ ```bash+ $HPR levers set <vault_tag> inference_depth=deep --rerender -j+ ```++ The `--rerender` refreshes the shim files so step 5's investigators inherit the new posture. If the step-1 value still fits, do nothing.+**INVARIANT:** at least one `flavor: "dialectical"` locus must be present unless an analyst's `skip_loci` justifies its absence with specific evidence of a univocal corpus. No dialectical locus + no justification = re-spawn the loci-analyst with a tighter prompt.**Placeholder-breadcrumb ban:** depth investigators will fetch sources; do not hand them breadcrumb placeholders like `hyperresearch-locus-seed` — use real source note ids from the vault or omit `--suggested-by` entirely.diff --git a/src/hyperresearch/skills/hyperresearch-5-depth-investigation.md b/src/hyperresearch/skills/hyperresearch-5-depth-investigation.mdindex d4f8908..eb396ae 100644--- a/src/hyperresearch/skills/hyperresearch-5-depth-investigation.md+++ b/src/hyperresearch/skills/hyperresearch-5-depth-investigation.md@@ -57,6 +57,8 @@ Read these inputs:- locus_name: <locus name>- source_budget: <hard cap on additional sources you can fetch>+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.+CRITICAL: Read the full source text of relevant vault notes (via`hyperresearch note show <id1> <id2> ... -j`) BEFORE writing yourinterim note. Drafting from summaries alone produces paraphrase;diff --git a/src/hyperresearch/skills/hyperresearch-8-corpus-critic.md b/src/hyperresearch/skills/hyperresearch-8-corpus-critic.mdindex 9959b09..bf525c8 100644--- a/src/hyperresearch/skills/hyperresearch-8-corpus-critic.md+++ b/src/hyperresearch/skills/hyperresearch-8-corpus-critic.md@@ -80,6 +80,8 @@ The targeted fetch wave in the next step will pull these filings BEFORE the corp- comparisons_path: research/runs/<vault_tag>/comparisons.md- loci_path: research/runs/<vault_tag>/loci.json- output_path: research/runs/<vault_tag>/corpus-critic-gaps.json++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```2. **Read the gaps output** (`research/runs/<vault_tag>/corpus-critic-gaps.json`). Each gap has a `priority` (critical / high) and a `type` (overturning / strengthening / independent-verification).@@ -105,6 +107,8 @@ The targeted fetch wave in the next step will pull these filings BEFORE the corp- search_queries: [<gap.search_queries>]- source_type: <gap.source_type>- gap_id: <gap.id>++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```4. **Assess results.**diff --git a/src/hyperresearch/skills/hyperresearch.md b/src/hyperresearch/skills/hyperresearch.mdindex d3a5e55..12be261 100644--- a/src/hyperresearch/skills/hyperresearch.md+++ b/src/hyperresearch/skills/hyperresearch.md@@ -172,6 +172,8 @@ When a step skill instructs you to spawn a subagent, the prompt you pass MUST in3. **The subagent's specific inputs** (vault_tag, output_path, locus, etc.). Each step skill's spawn template documents the required fields.+4. **The run's shim file, pasted VERBATIM.** Step 1 renders posture shims (register / domain notes / inference depth) to `research/runs/<vault_tag>/shims/{research,drafting,critics,polish}.md`. Each step skill's spawn template names which shim its subagents receive; append that file's FULL contents to the end of the spawn prompt, unedited. You never write, summarize, or trim shim text — the file is the single source of truth. The cite-checker receives NO shim (verification is register-independent). If the shims directory is missing, run `$HPR levers render <vault_tag> -j` before spawning.+Skipping any of these in a Task prompt is a process violation.---@@ -260,6 +262,7 @@ Ship only after `run finish` reports `"passed": true`: the final report lives at12. **Subagents read full source text.** Draft sub-orchestrators MUST batch-read every note in their `must_read_note_ids` list before writing. Fetchers MUST chase 3-8 primary sources via citation chains.13. **NEVER emit a bare text response while subagent tasks are in flight.**14. **A run is complete ONLY when `run finish` reports `passed: true`.** Gate failures are fixed by changing the report, never by re-interpreting, downgrading, or memo-ing away the checks. If 3 fix rounds don't clear the gate, the run stays `blocked` and you say so.+15. **Shim files are pasted verbatim.** The lever shims under `research/runs/<vault_tag>/shims/` go into spawn prompts whole and unedited, per the spawn contract. The orchestrator never composes, summarizes, or omits shim text, and never gives the cite-checker one.---diff --git a/tests/fixtures/golden_prompts/agents/browser_fetcher_agent.md b/tests/fixtures/golden_prompts/agents/browser_fetcher_agent.mdindex 7f6c57c..a00b0a9 100644--- a/tests/fixtures/golden_prompts/agents/browser_fetcher_agent.md+++ b/tests/fixtures/golden_prompts/agents/browser_fetcher_agent.md@@ -18,6 +18,11 @@ You are the hyperresearch browser-lane fetcher. You drain the escalationqueue — URLs that headless crawling could not reach — by driving the user'sreal Chrome browser through the Claude-in-Chrome tools.+Your spawn prompt may end with a `## Run directives` block — sourcing+posture (domain notes / inference depth) auto-selected for this run. It+is BINDING for how you read and summarize what you fetch. It never+overrides the hard scope boundary below.+## Hard scope boundary (read first)You NEVER attempt to solve, bypass, or automate CAPTCHAs, 2FA prompts, ordiff --git a/tests/fixtures/golden_prompts/agents/depth_critic_agent.md b/tests/fixtures/golden_prompts/agents/depth_critic_agent.mdindex 9adfbb2..08661bf 100644--- a/tests/fixtures/golden_prompts/agents/depth_critic_agent.md+++ b/tests/fixtures/golden_prompts/agents/depth_critic_agent.md@@ -30,6 +30,11 @@ rather than gesturing at it from a distance.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. Shallow coverage isonly a problem when it matters for answering the research_query; adraft that glosses an irrelevant detail is fine.diff --git a/tests/fixtures/golden_prompts/agents/depth_investigator_agent.md b/tests/fixtures/golden_prompts/agents/depth_investigator_agent.mdindex 65cac9c..9955dfc 100644--- a/tests/fixtures/golden_prompts/agents/depth_investigator_agent.md+++ b/tests/fixtures/golden_prompts/agents/depth_investigator_agent.md@@ -40,6 +40,11 @@ reading of the evidence.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **locus**: the full locus object from the loci-analyst output (name,flavor, one_line, rationale, corpus_evidence, suggested_starting_urls,suggested_searches, and — for dialectical loci — opposing_positions).diff --git a/tests/fixtures/golden_prompts/agents/dialectic_critic_agent.md b/tests/fixtures/golden_prompts/agents/dialectic_critic_agent.mdindex 5a2a19d..925ea1b 100644--- a/tests/fixtures/golden_prompts/agents/dialectic_critic_agent.md+++ b/tests/fixtures/golden_prompts/agents/dialectic_critic_agent.md@@ -37,6 +37,11 @@ actually gathered, not guesses.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. Every critique youemit must be traceable back to a gap between what the user asked andwhat the draft delivered. A finding that doesn't serve the@@ -99,6 +104,12 @@ Use the **Write tool** to save your findings JSON to `output_path`. Do NOT use Bthe vault covers. Should be patched.- **Severity `minor`** — a hedge or qualifier would strengthen the claimbut the draft isn't wrong.+- **Register-conditional standard.** Your commitment expectations follow+ the Run directives block when one is present: in teach or survey+ register, even-handed hedged treatment of a contested point is CORRECT+ — flag unfair or missing representation of a view instead of the+ absence of a committed position. In advocate register, the steel-man's+ quality is the central standard and a weak opposing case is critical.- **At most 12 findings.** If you see more than 12, return the 12 mostload-bearing. Returning 40 small findings buries the critical ones.- **Never propose deleting and retyping an entire section.** That isdiff --git a/tests/fixtures/golden_prompts/agents/instruction_critic_agent.md b/tests/fixtures/golden_prompts/agents/instruction_critic_agent.mdindex f096286..81abac6 100644--- a/tests/fixtures/golden_prompts/agents/instruction_critic_agent.md+++ b/tests/fixtures/golden_prompts/agents/instruction_critic_agent.md@@ -31,6 +31,11 @@ hand findings to the patcher (Layer 6). You do NOT modify the draft.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.This is THE primary input for you — your critiques are measured byhow the draft maps to THIS text, in THIS shape, with THESE named@@ -266,6 +271,11 @@ let these crowd out core instruction-following findings. Use- **Keep recommendations surgical.** Same discipline as the other critics —your recommendation should describe a minimal change that addressesthe atomic item.+- **Register-conditional.** When the Run directives block sets teach or+ survey register, do not emit findings demanding a committed ranking or+ verdict the user's prompt did not itself name — coverage-shaped+ delivery is correct in those registers. Format cues the prompt names+ explicitly always win, regardless of register.- **For `wrong-format` findings**, a full format change (ranked-list→ FAQ) is structural — flag `severity: critical` with a descriptionin `issue`. These escalate to the orchestrator, not the revisor.diff --git a/tests/fixtures/golden_prompts/agents/loci_analyst_agent.md b/tests/fixtures/golden_prompts/agents/loci_analyst_agent.mdindex e240c08..f3ecb42 100644--- a/tests/fixtures/golden_prompts/agents/loci_analyst_agent.md+++ b/tests/fixtures/golden_prompts/agents/loci_analyst_agent.md@@ -39,6 +39,11 @@ depth packet becomes a weak draft section.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: the user's original question, verbatim. GOSPEL.This is the north star for every decision you make. If a locus doesn'tserve the research_query, reject it — no matter how interesting it is.diff --git a/tests/fixtures/golden_prompts/agents/readability_reformatter_agent.md b/tests/fixtures/golden_prompts/agents/readability_reformatter_agent.mdindex c6ea513..5cf90cd 100644--- a/tests/fixtures/golden_prompts/agents/readability_reformatter_agent.md+++ b/tests/fixtures/golden_prompts/agents/readability_reformatter_agent.md@@ -41,6 +41,11 @@ apply. You are advisory.## Inputs (from the orchestrator)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL.- **draft_path**: `research/notes/final_report_<vault_tag>.md` — the polished report.- **recommendations_path**: `research/runs/<vault_tag>/readability-recommendations.json`diff --git a/tests/fixtures/golden_prompts/agents/researcher_agent.md b/tests/fixtures/golden_prompts/agents/researcher_agent.mdindex 2924c00..ee892e2 100644--- a/tests/fixtures/golden_prompts/agents/researcher_agent.md+++ b/tests/fixtures/golden_prompts/agents/researcher_agent.md@@ -15,6 +15,11 @@ You are a research fetcher with agency to chase primary sources. Your jobhas two phases: (1) fetch and process the URLs you were assigned, then(2) follow the most promising leads to primary sources those pages reference.+Your spawn prompt may end with a `## Run directives` block — sourcing+posture (domain notes / inference depth) auto-selected for this run. It+is BINDING and wins wherever it adjusts a default in this prompt. No+block = this prompt's defaults apply unchanged.+## Period-pinned filings (READ FIRST)When the parent agent's research_query names a specific historical reportingdiff --git a/tests/fixtures/golden_prompts/agents/width_critic_agent.md b/tests/fixtures/golden_prompts/agents/width_critic_agent.mdindex 9d8bd48..360524d 100644--- a/tests/fixtures/golden_prompts/agents/width_critic_agent.md+++ b/tests/fixtures/golden_prompts/agents/width_critic_agent.md@@ -27,6 +27,11 @@ because the orchestrator's structural choices buried them.## Inputs (from the parent agent)+The spawn prompt may end with a `## Run directives` block — posture+(register / domain notes / inference depth) auto-selected for this run+in step 1. It is BINDING and wins wherever it adjusts a default in this+prompt. No block = this prompt's defaults apply unchanged.+- **research_query**: verbatim user question. GOSPEL. A coverage gap isonly a real gap if the missing topic is something the research_queryimplies. Don't flag orthogonal material that happens to be in thediff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-10-triple-draft.md b/tests/fixtures/golden_prompts/skills/hyperresearch-10-triple-draft.mdindex ce21c8a..3c97e9c 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-10-triple-draft.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-10-triple-draft.md@@ -173,6 +173,8 @@ prompt: |- citation_style: "<wikilink|inline|none>"- modality: "<collect|synthesize|compare|forecast>"+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/drafting.md here, verbatim.+Read every note on must_read_note_ids before writing. Do NOT surveythe vault — your reading list is curated. Do NOT fetch new sources.Write your draft from your assigned angle, citing your curated sources.diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-13-gap-fetch.md b/tests/fixtures/golden_prompts/skills/hyperresearch-13-gap-fetch.mdindex 9812e67..63e6ebb 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-13-gap-fetch.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-13-gap-fetch.md@@ -62,6 +62,8 @@ Read these inputs:- vault_tag: <vault_tag>- urls: [<gap-targeted URLs>]- extra_tags: ["post-critic-fill"]++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```Each fetcher: fetches, quality-checks, summarizes, extracts claims (same procedure as step 2). Tags notes with `vault_tag` + `post-critic-fill`. Writes claims to `research/runs/<vault_tag>/temp/claims-<note-id>.json`.diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-16-readability-audit.md b/tests/fixtures/golden_prompts/skills/hyperresearch-16-readability-audit.mdindex 56053fa..03e1a01 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-16-readability-audit.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-16-readability-audit.md@@ -57,6 +57,8 @@ prompt: |- draft_path: research/notes/final_report_<vault_tag>.md- recommendations_path: research/runs/<vault_tag>/readability-recommendations.json+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/polish.md here, verbatim.+Write recommendations as a JSON array per the schema in your agentprompt. Cap at 50 recommendations, prioritized by impact.```diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-2-width-sweep.md b/tests/fixtures/golden_prompts/skills/hyperresearch-2-width-sweep.mdindex f27e726..3a9a606 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-2-width-sweep.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-2-width-sweep.md@@ -150,6 +150,8 @@ prompt: |- vault_tag: <vault_tag>- urls: [<batch URLs, exactly as assigned — with each URL's utility score when scored, e.g. "https://... (utility: 14)">]- batch_id: <number>++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```**CRITICAL: no token waste.** Each fetcher gets ONLY its batch. No fetcher searches for new URLs or duplicates another fetcher's work. If a fetcher finishes early, it's done.@@ -263,6 +265,8 @@ prompt: |YOUR INPUTS:- vault_tag: <vault_tag>- drain up to 10 items (claim via `$HPR escalation claim --tag <vault_tag>`)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```**When the browser-fetcher returns with `needs_human` items** (CAPTCHAs, logins, 2FA — it NEVER solves these itself):@@ -315,6 +319,8 @@ prompt: |- source_note_id: <vault note id of the long source>- output_path: research/runs/<vault_tag>/temp/source-analysis-<source_note_id>.md- vault_tag: <vault_tag>++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```---diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-4-loci-analysis.md b/tests/fixtures/golden_prompts/skills/hyperresearch-4-loci-analysis.mdindex 5ab2913..122c1a1 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-4-loci-analysis.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-4-loci-analysis.md@@ -52,6 +52,8 @@ Survey the corpus: `$HPR note list --tag <vault_tag> --all -j` to confirm width- corpus_tag: <vault_tag>- analyst_id: "a" (for one) / "b" (for the other)- output_path: research/runs/<vault_tag>/loci-a.json (or research/runs/<vault_tag>/loci-b.json)++ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.```2. **Wait for both.** If one fails, proceed with the single successful output. If both fail (empty loci lists), tell the user the width sweep was too thin and stop — do not force depth on a weak corpus.@@ -101,6 +103,14 @@ Survey the corpus: `$HPR note list --tag <vault_tag> --all -j` to confirm width6. **Decide investigator count.** Spawn ONE depth-investigator (in step 5) per locus with `source_budget > 0`, capped at 6. If only 1 locus passes scoring, spawn 1.+7. **Reconsider `inference_depth` against the actual corpus.** Step 1 set it provisionally from the query alone; you have now seen what the surface web actually holds. Upgrade to `deep` when the corpus shows the load-bearing questions are underdetermined by clearly-published sources — high-uncertainty loci where the missing evidence is gray literature, filings, or unpublished figures rather than papers nobody fetched yet. Downgrade to `surface` only if step 1 chose `deep` and the corpus turned out rich and univocal. To change it:++ ```bash+ $HPR levers set <vault_tag> inference_depth=deep --rerender -j+ ```++ The `--rerender` refreshes the shim files so step 5's investigators inherit the new posture. If the step-1 value still fits, do nothing.+**INVARIANT:** at least one `flavor: "dialectical"` locus must be present unless an analyst's `skip_loci` justifies its absence with specific evidence of a univocal corpus. No dialectical locus + no justification = re-spawn the loci-analyst with a tighter prompt.**Placeholder-breadcrumb ban:** depth investigators will fetch sources; do not hand them breadcrumb placeholders like `hyperresearch-locus-seed` — use real source note ids from the vault or omit `--suggested-by` entirely.diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch-5-depth-investigation.md b/tests/fixtures/golden_prompts/skills/hyperresearch-5-depth-investigation.mdindex 8dbb873..202c2b6 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch-5-depth-investigation.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch-5-depth-investigation.md@@ -57,6 +57,8 @@ Read these inputs:- locus_name: <locus name>- source_budget: <hard cap on additional sources you can fetch>+ RUN DIRECTIVES: append the FULL contents of research/runs/<vault_tag>/shims/research.md here, verbatim.+CRITICAL: Read the full source text of relevant vault notes (via`hyperresearch note show <id1> <id2> ... -j`) BEFORE writing yourinterim note. Drafting from summaries alone produces paraphrase;diff --git a/tests/fixtures/golden_prompts/skills/hyperresearch.md b/tests/fixtures/golden_prompts/skills/hyperresearch.mdindex 3e0b314..7ae0483 100644--- a/tests/fixtures/golden_prompts/skills/hyperresearch.md+++ b/tests/fixtures/golden_prompts/skills/hyperresearch.md@@ -172,6 +172,8 @@ When a step skill instructs you to spawn a subagent, the prompt you pass MUST in3. **The subagent's specific inputs** (vault_tag, output_path, locus, etc.). Each step skill's spawn template documents the required fields.+4. **The run's shim file, pasted VERBATIM.** Step 1 renders posture shims (register / domain notes / inference depth) to `research/runs/<vault_tag>/shims/{research,drafting,critics,polish}.md`. Each step skill's spawn template names which shim its subagents receive; append that file's FULL contents to the end of the spawn prompt, unedited. You never write, summarize, or trim shim text — the file is the single source of truth. The cite-checker receives NO shim (verification is register-independent). If the shims directory is missing, run `$HPR levers render <vault_tag> -j` before spawning.+Skipping any of these in a Task prompt is a process violation.---@@ -260,6 +262,7 @@ Ship only after `run finish` reports `"passed": true`: the final report lives at12. **Subagents read full source text.** Draft sub-orchestrators MUST batch-read every note in their `must_read_note_ids` list before writing. Fetchers MUST chase 3-8 primary sources via citation chains.13. **NEVER emit a bare text response while subagent tasks are in flight.**14. **A run is complete ONLY when `run finish` reports `passed: true`.** Gate failures are fixed by changing the report, never by re-interpreting, downgrading, or memo-ing away the checks. If 3 fix rounds don't clear the gate, the run stays `blocked` and you say so.+15. **Shim files are pasted verbatim.** The lever shims under `research/runs/<vault_tag>/shims/` go into spawn prompts whole and unedited, per the spawn contract. The orchestrator never composes, summarizes, or omits shim text, and never gives the cite-checker one.---diff --git a/tests/test_core/test_levers.py b/tests/test_core/test_levers.pynew file mode 100644index 0000000..888223b--- /dev/null+++ b/tests/test_core/test_levers.py@@ -0,0 +1,217 @@+"""Run levers: shim composition, rendering CLI, and the verify gate check.++Levers own posture, profiles own numbers: the profile-number guard here is+the drift-proofing that keeps shim text from ever restating a numeric+budget (which would fight the install-time profile/golden machinery).+"""++from __future__ import annotations++import json+import re++import pytest++from hyperresearch.core.levers import (+ DEFAULT_LEVERS,+ INFERENCE_DEPTHS,+ REGISTERS,+ ROLES,+ LeverError,+ compose_shims,+ render_shims,+ set_levers,+)+from hyperresearch.core.runs import init_run, load_manifest, verify_run+++def _write_decomposition(vault, tag: str, levers: dict | None) -> None:+ run_dir = vault.run_dir(tag)+ run_dir.mkdir(parents=True, exist_ok=True)+ decomp: dict = {+ "response_format": "short",+ "required_section_headings": ["## Findings"],+ }+ if levers is not None:+ decomp["levers"] = levers+ (run_dir / "prompt-decomposition.json").write_text(+ json.dumps(decomp), encoding="utf-8"+ )+++class TestCompose:+ def test_all_combinations_compose_nonempty(self):+ for register in REGISTERS:+ for depth in INFERENCE_DEPTHS:+ shims = compose_shims({"register": register, "inference_depth": depth})+ assert set(shims) == set(ROLES)+ for role, text in shims.items():+ assert text.strip(), f"{role} empty for {register}/{depth}"+ assert "<<" not in text and ">>" not in text+ assert text.startswith("## Run directives")+ assert f"register: {register}" in text+ assert f"inference depth: {depth}" in text++ def test_profile_numbers_stay_out_of_shims(self):+ # Posture, not numbers: a shim restating a numeric budget would+ # fight the profile system that owns every count.+ budget_range = re.compile(+ "\\d+\\s*[-\u2013]\\s*\\d+\\s*(sources|words|fetchers|loci|searches)"+ )+ for register in REGISTERS:+ for depth in INFERENCE_DEPTHS:+ shims = compose_shims({"register": register, "inference_depth": depth})+ for role, text in shims.items():+ assert not budget_range.search(text), (register, depth, role)++ def test_unknown_register_rejected(self):+ with pytest.raises(LeverError, match="unknown register"):+ compose_shims({"register": "poetic"})++ def test_unknown_inference_depth_rejected(self):+ with pytest.raises(LeverError, match="unknown inference_depth"):+ compose_shims({"inference_depth": "bottomless"})++ def test_domain_notes_land_verbatim_in_research_and_drafting(self):+ notes = "Sourcing: court filings first; recency window is the last two terms."+ shims = compose_shims({**DEFAULT_LEVERS, "domain_notes": notes})+ assert notes in shims["research"]+ assert notes in shims["drafting"]+ assert notes not in shims["polish"]++ def test_register_semantics_reach_the_right_roles(self):+ survey = compose_shims({"register": "survey"})+ assert "Do not flag the absence of a committed thesis" in survey["critics"]+ assert "Do NOT strike hedges" in survey["polish"]+ teach = compose_shims({"register": "teach"})+ assert "non-specialist" in teach["drafting"]+ # Research shims carry no register posture at all.+ assert "Register posture" not in teach["research"]++ def test_deep_inference_licenses_provenance_discipline(self):+ deep = compose_shims({"inference_depth": "deep"})+ assert "provenance" in deep["drafting"].lower()+ assert "audited absences" in deep["research"].lower()+++class TestRenderCli:+ def test_render_writes_files_and_manifest(self, tmp_vault, monkeypatch):+ from typer.testing import CliRunner++ from hyperresearch.cli import app++ init_run(tmp_vault, "lv-01", profile="light")+ _write_decomposition(+ tmp_vault, "lv-01",+ {"register": "survey", "inference_depth": "deep", "domain_notes": "Filings first."},+ )+ monkeypatch.chdir(tmp_vault.root)+ r = CliRunner().invoke(app, ["levers", "render", "lv-01", "--json"])+ assert r.exit_code == 0+ for role in ROLES:+ assert (tmp_vault.run_dir("lv-01") / "shims" / f"{role}.md").exists()+ manifest = load_manifest(tmp_vault, "lv-01")+ assert manifest["levers"]["register"] == "survey"+ assert manifest["levers"]["inference_depth"] == "deep"++ def test_render_defaults_when_levers_absent(self, tmp_vault, monkeypatch):+ from typer.testing import CliRunner++ from hyperresearch.cli import app++ init_run(tmp_vault, "lv-02", profile="light")+ _write_decomposition(tmp_vault, "lv-02", levers=None)+ monkeypatch.chdir(tmp_vault.root)+ r = CliRunner().invoke(app, ["levers", "render", "lv-02", "--json"])+ assert r.exit_code == 0+ research = (tmp_vault.run_dir("lv-02") / "shims" / "research.md").read_text(+ encoding="utf-8"+ )+ assert "register: analyze" in research+ assert "inference depth: standard" in research++ def test_render_rejects_unknown_enum_via_cli(self, tmp_vault, monkeypatch):+ from typer.testing import CliRunner++ from hyperresearch.cli import app++ init_run(tmp_vault, "lv-03", profile="light")+ _write_decomposition(tmp_vault, "lv-03", {"register": "poetic"})+ monkeypatch.chdir(tmp_vault.root)+ r = CliRunner().invoke(app, ["levers", "render", "lv-03", "--json"])+ assert r.exit_code == 1++ def test_set_rerender_updates_shims_and_decomposition(self, tmp_vault, monkeypatch):+ from typer.testing import CliRunner++ from hyperresearch.cli import app++ init_run(tmp_vault, "lv-04", profile="light")+ _write_decomposition(tmp_vault, "lv-04", {"register": "analyze"})+ monkeypatch.chdir(tmp_vault.root)+ runner = CliRunner()+ assert runner.invoke(app, ["levers", "render", "lv-04", "--json"]).exit_code == 0+ before = (tmp_vault.run_dir("lv-04") / "shims" / "research.md").read_text(+ encoding="utf-8"+ )++ r = runner.invoke(+ app, ["levers", "set", "lv-04", "inference_depth=deep", "--rerender", "--json"]+ )+ assert r.exit_code == 0+ after = (tmp_vault.run_dir("lv-04") / "shims" / "research.md").read_text(+ encoding="utf-8"+ )+ assert before != after+ assert "DEEP inference" in after+ decomp = json.loads(+ (tmp_vault.run_dir("lv-04") / "prompt-decomposition.json").read_text(+ encoding="utf-8"+ )+ )+ assert decomp["levers"]["inference_depth"] == "deep"++ def test_set_rejects_invalid_value_without_writing(self, tmp_vault):+ init_run(tmp_vault, "lv-05", profile="light")+ _write_decomposition(tmp_vault, "lv-05", {"register": "analyze"})+ with pytest.raises(LeverError):+ set_levers(tmp_vault, "lv-05", {"register": "poetic"})+ decomp = json.loads(+ (tmp_vault.run_dir("lv-05") / "prompt-decomposition.json").read_text(+ encoding="utf-8"+ )+ )+ assert decomp["levers"]["register"] == "analyze"+++class TestVerifyGate:+ def _report(self, vault, tag: str) -> None:+ report = vault.root / "research" / "notes" / f"final_report_{tag}.md"+ report.write_text(+ "## Findings\n\n" + ("Evidence-bearing sentence [[src]]. " * 80),+ encoding="utf-8",+ )++ def test_declared_levers_without_shims_fails(self, tmp_vault):+ init_run(tmp_vault, "lv-06", profile="light")+ _write_decomposition(tmp_vault, "lv-06", {"register": "survey"})+ self._report(tmp_vault, "lv-06")+ result = verify_run(tmp_vault, "lv-06")+ by_name = {c["name"]: c for c in result["checks"]}+ assert not by_name["levers-rendered"]["ok"]++ def test_declared_levers_with_shims_passes(self, tmp_vault):+ init_run(tmp_vault, "lv-07", profile="light")+ _write_decomposition(tmp_vault, "lv-07", {"register": "survey"})+ render_shims(tmp_vault, "lv-07")+ self._report(tmp_vault, "lv-07")+ result = verify_run(tmp_vault, "lv-07")+ by_name = {c["name"]: c for c in result["checks"]}+ assert by_name["levers-rendered"]["ok"]++ def test_leverless_run_skips_the_check(self, tmp_vault):+ init_run(tmp_vault, "lv-08", profile="light")+ _write_decomposition(tmp_vault, "lv-08", levers=None)+ self._report(tmp_vault, "lv-08")+ result = verify_run(tmp_vault, "lv-08")+ assert "levers-rendered" not in {c["name"] for c in result["checks"]}diff --git a/tests/test_core/test_prompt_golden.py b/tests/test_core/test_prompt_golden.pyindex cc60a5b..51ae221 100644--- a/tests/test_core/test_prompt_golden.py+++ b/tests/test_core/test_prompt_golden.py@@ -63,6 +63,16 @@ Deliberate deviations already folded into the goldens (2026-07-19):end placement, run consolidation with number-bearing anchors kept), andregister discipline (meta-discourse ban, hedging discipline, kickerrationing) distilled from the humanize-ai-text skill.+ - Run levers (2026-07-20): step 1 now auto-selects register / domain+ notes / inference depth and renders them to shim files via `hpr levers+ render`; the router's spawn contract gained item 4 (paste the role's+ shim verbatim) and invariant 15; every spawning skill's spawn template+ gained a RUN DIRECTIVES paste line (research/drafting/critics/polish+ roles); every shim-receiving agent gained a Run-directives acceptance+ paragraph; the dialectic and instruction critics gained+ register-conditional standards. The cite-checker and+ 9-evidence-digest are deliberately untouched (no shim: verification+ is register-independent; step 9 spawns nothing)."""from __future__ import annotations@@ -318,3 +328,38 @@ def test_rendered_agents_have_no_cost_or_model_claims(const_name, ctx):rendered = render_prompt(getattr(hooks, const_name), ctx)assert not _DOLLAR_RANGE.search(rendered), f"dollar-cost range in {const_name}"assert not _MODEL_CLAIM.search(rendered), f"hardcoded model claim in {const_name}"+++# ---------------------------------------------------------------------------+# Lever shims: every spawning skill pastes its role's shim file; the+# cite-checker gets none (verification is register-independent).+# ---------------------------------------------------------------------------++_SKILL_SHIM_ROLES = {+ "hyperresearch-2-width-sweep": "research",+ "hyperresearch-4-loci-analysis": "research",+ "hyperresearch-5-depth-investigation": "research",+ "hyperresearch-8-corpus-critic": "research",+ "hyperresearch-13-gap-fetch": "research",+ "hyperresearch-10-triple-draft": "drafting",+ "hyperresearch-11-synthesize": "drafting",+ "hyperresearch-12-critics": "critics",+ "hyperresearch-14-patcher": "critics",+ "hyperresearch-15-polish": "polish",+ "hyperresearch-16-readability-audit": "polish",+}++[email protected]("skill_name,role", sorted(_SKILL_SHIM_ROLES.items()))+def test_spawning_skills_carry_their_shim_paste_line(skill_name, role, ctx):+ rendered = render_prompt(_read_skill_source(f"{skill_name}.md"), ctx)+ assert f"shims/{role}.md" in rendered, (+ f"{skill_name} spawn template lost its shims/{role}.md paste line"+ )+++def test_cite_check_skill_gets_no_shim(ctx):+ rendered = render_prompt(+ _read_skill_source("hyperresearch-14-5-cite-check.md"), ctx+ )+ assert "shims/" not in rendered