diff --git a/pyproject.toml b/pyproject.toml index 7e7b719..beac636 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "insight-kit" -version = "0.1.5" +version = "0.1.6" description = "Provenance-first agent insights kit — Run + Claim + DAG primitives for traceable analyst/critic loops." readme = "README.md" license = { text = "MIT" } diff --git a/src/insight_kit/narrative/__init__.py b/src/insight_kit/narrative/__init__.py new file mode 100644 index 0000000..0304f08 --- /dev/null +++ b/src/insight_kit/narrative/__init__.py @@ -0,0 +1,15 @@ +"""insight_kit.narrative — reusable prompt skeletons for analyst/critic runs. + +Public surface: + from insight_kit.narrative.analyst_prompt import ( + ANALYST_PROMPT_TEMPLATE, render_analyst_prompt, + ) +""" +from __future__ import annotations + +from insight_kit.narrative.analyst_prompt import ( + ANALYST_PROMPT_TEMPLATE, + render_analyst_prompt, +) + +__all__ = ["ANALYST_PROMPT_TEMPLATE", "render_analyst_prompt"] diff --git a/src/insight_kit/narrative/analyst_prompt.py b/src/insight_kit/narrative/analyst_prompt.py new file mode 100644 index 0000000..aa6cdc8 --- /dev/null +++ b/src/insight_kit/narrative/analyst_prompt.py @@ -0,0 +1,115 @@ +"""analyst_prompt.py — render the standard analyst run header. + +Captures the parts of the analyst prompt that recur across every consumer +project (claim schema, query_path rules, output file list, headings). Project- +specific bits (founder context, data scope description) are runtime params so +consumers like growth_insights inject their own without forking the template. + +Append persona instructions to the rendered string yourself — they vary per +council member and live in the consumer repo. + +History: +- Original lived inline at growth_insights/src/growth_insights/analyst/runner.py + as `_ANALYST_HEADER` from 2026-04-24 through 2026-06-09. +- 2026-06-09: extracted to insight-kit (B3 of eval-harness extraction). +- `query_path` rules block was hardened 2026-06-09 (PR #8 on growth_insights) + after omp drift emitted multi-source concatenated paths. +""" +from __future__ import annotations + +from pathlib import Path + +ANALYST_PROMPT_TEMPLATE = """\ +# Analyst run: {goal_slug} + +**Goal question:** {question} +{founder_context_block} +## Data scope + +{data_scope} + +## Your task + +Apply your Analytical Method (from your identity file) to answer the goal question. + +For each finding, emit a derived claim in `claims.jsonl` with the following fields: + +```json +{{ + "claim_id": "", + "tier": "derived", + "goal": "{goal_slug}", + "statement": "", + "query_path": "queries/.sql", + "result_snapshot": "", + "interpretation": "", + "confidence": "High | Med | Low", + "confidence_reason":"", + "cites": ["", ...] +}} +``` + +**`query_path` rules — strict, no exceptions:** +- Exactly ONE path. Single string. No spaces, no concatenation. +- Format MUST be `queries/.sql` (full `.sql` extension required). +- For composite/derived claims that build on upstream queries, reference + those upstream claim_ids in the `cites` array — NOT in `query_path`. +- Every claim writes its own SQL to `queries/.sql` even if that + SQL only re-derives a small slice from upstream data. + +Archive each SQL query to `queries/.sql`. + +Write the narrative to `findings_analyst.md` — lead with the highest-leverage +finding, then support findings, then limitations. + +Output files (relative to your run dir `{run_dir}`): +- `findings_analyst.md` +- `claims.jsonl` (append — file is pre-created with header comment) +- `queries/.sql` for each query + +## Persona instructions +""" + + +def render_analyst_prompt( + *, + goal_slug: str, + question: str, + run_dir: Path | str, + data_scope: str = "*(no data scope provided)*", + founder_context: str = "", +) -> str: + """Render the analyst prompt header. + + Args: + goal_slug: short kebab/snake identifier for the analyst run. + Used in the title heading + claim `goal` field. + question: the analyst's goal question (one or more paragraphs). + run_dir: path where the analyst should write outputs. Rendered + verbatim into the prompt — accept str or Path. + data_scope: pre-formatted markdown listing the data sources the + analyst should pull from. Consumers format this their + own way (Meta JSON paths, Shopify parquet tables, + prior MD-* claim files, etc.). Default placeholder + flags an unconfigured run. + founder_context: optional one-paragraph business context that biases + the analyst's framing (e.g. "April is the worst + month on record..."). Omit (empty string) to skip + the entire **Founder context:** block. + + Returns: + The full header string. Caller is responsible for appending persona + instructions immediately after (the template ends at + `## Persona instructions\\n`). + """ + founder_block = "" + if founder_context: + founder_block = f"\n**Founder context:** {founder_context}\n" + + return ANALYST_PROMPT_TEMPLATE.format( + goal_slug=goal_slug, + question=question, + run_dir=run_dir, + data_scope=data_scope, + founder_context_block=founder_block, + ) diff --git a/tests/narrative/test_analyst_prompt.py b/tests/narrative/test_analyst_prompt.py new file mode 100644 index 0000000..38ad061 --- /dev/null +++ b/tests/narrative/test_analyst_prompt.py @@ -0,0 +1,138 @@ +"""Tests for insight_kit.narrative.analyst_prompt. + +Covers: + - Required structural pieces of the rendered prompt + - Founder context: included when set, completely omitted when empty + - JSON literal braces survive .format() (the `{{` / `}}` escapes) + - run_dir accepts str + Path interchangeably + - data_scope default vs custom + - Strict query_path rules block is present (the omp-drift fix) +""" +from __future__ import annotations + +from pathlib import Path + +from insight_kit.narrative.analyst_prompt import ( + ANALYST_PROMPT_TEMPLATE, + render_analyst_prompt, +) + + +# --------------------------------------------------------------------------- +# Render basics +# --------------------------------------------------------------------------- + +def test_render_includes_goal_and_question() -> None: + out = render_analyst_prompt( + goal_slug="g4f7_attribution", + question="Why did CPA fall?", + run_dir="/app/data/agent_runs/r1", + ) + assert "# Analyst run: g4f7_attribution" in out + assert "**Goal question:** Why did CPA fall?" in out + assert "/app/data/agent_runs/r1" in out + + +def test_render_accepts_path_or_str_for_run_dir(tmp_path: Path) -> None: + out_path = render_analyst_prompt( + goal_slug="g", question="q?", run_dir=tmp_path, + ) + out_str = render_analyst_prompt( + goal_slug="g", question="q?", run_dir=str(tmp_path), + ) + assert str(tmp_path) in out_path + assert str(tmp_path) in out_str + + +# --------------------------------------------------------------------------- +# Founder context +# --------------------------------------------------------------------------- + +def test_founder_context_included_when_set() -> None: + out = render_analyst_prompt( + goal_slug="g", question="q?", run_dir="/r", + founder_context="April is the worst month on record.", + ) + assert "**Founder context:** April is the worst month on record." in out + + +def test_founder_context_block_omitted_when_empty() -> None: + out = render_analyst_prompt( + goal_slug="g", question="q?", run_dir="/r", + ) + assert "**Founder context:**" not in out + + +# --------------------------------------------------------------------------- +# Data scope +# --------------------------------------------------------------------------- + +def test_data_scope_default_placeholder() -> None: + out = render_analyst_prompt(goal_slug="g", question="q?", run_dir="/r") + assert "*(no data scope provided)*" in out + + +def test_data_scope_custom_markdown() -> None: + scope = "### Meta metadata\n- m1: /path/m1.json\n\n### Shopify\n- s1: /path/s1.parquet" + out = render_analyst_prompt( + goal_slug="g", question="q?", run_dir="/r", data_scope=scope, + ) + assert "### Meta metadata" in out + assert "- m1: /path/m1.json" in out + assert "- s1: /path/s1.parquet" in out + + +# --------------------------------------------------------------------------- +# Claim schema + JSON brace escaping +# --------------------------------------------------------------------------- + +def test_claim_schema_json_block_renders_with_real_braces() -> None: + out = render_analyst_prompt(goal_slug="g4", question="q?", run_dir="/r") + # The JSON example block must render with literal { and }, not {{ / }}. + assert '"claim_id":' in out + assert '"goal": "g4"' in out # goal_slug interpolated inside JSON block + assert "{{" not in out # no leftover unescaped placeholder + assert "}}" not in out + + +# --------------------------------------------------------------------------- +# Strict query_path rules (the omp-drift fix) +# --------------------------------------------------------------------------- + +def test_query_path_rules_block_present() -> None: + out = render_analyst_prompt(goal_slug="g", question="q?", run_dir="/r") + assert "`query_path` rules — strict, no exceptions:" in out + assert "Exactly ONE path. Single string. No spaces, no concatenation." in out + assert "Format MUST be `queries/.sql`" in out + assert "those upstream claim_ids in the `cites` array — NOT in `query_path`" in out + + +# --------------------------------------------------------------------------- +# Output file list + persona instructions hook +# --------------------------------------------------------------------------- + +def test_output_files_list_present() -> None: + out = render_analyst_prompt(goal_slug="g", question="q?", run_dir="/r") + assert "Output files (relative to your run dir `/r`):" in out + assert "- `findings_analyst.md`" in out + assert "- `claims.jsonl` (append" in out + assert "- `queries/.sql` for each query" in out + + +def test_prompt_ends_at_persona_instructions_heading() -> None: + """Caller is expected to append persona text after this heading.""" + out = render_analyst_prompt(goal_slug="g", question="q?", run_dir="/r") + assert out.rstrip().endswith("## Persona instructions") + + +# --------------------------------------------------------------------------- +# Template surface +# --------------------------------------------------------------------------- + +def test_template_constant_exposes_named_placeholders() -> None: + """The exported template must declare every kwarg render_analyst_prompt uses.""" + for placeholder in [ + "{goal_slug}", "{question}", "{run_dir}", + "{data_scope}", "{founder_context_block}", + ]: + assert placeholder in ANALYST_PROMPT_TEMPLATE