WaguyMZ commited on
Commit
d5ef4a5
·
verified ·
1 Parent(s): e65e2ac

Add reference-harness prompts

Browse files
prompts/__init__.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Prompts package (hypothesis_orchestrated v2).
3
+
4
+ Active prompts: orientation, planning, system, scheme/hypothesis workers, compaction.
5
+ Retired PER-phase prompts (reflection, synthesis, cross-scheme, replan, phase_summary,
6
+ legacy worker orchestration) were removed — see git history.
7
+ """
8
+
9
+ from .compaction import COMPACTION_PROMPT
10
+ from .fraud_catalogue import FRAUD_CATALOGUE
11
+ from .hypothesis_worker import (
12
+ build_hypothesis_summary_prompt,
13
+ build_hypothesis_worker_prompt,
14
+ build_worker_brief_prompt,
15
+ build_worker_summary_prompt,
16
+ parse_hypothesis_summary_json,
17
+ )
18
+ from .minimal_scheme_cards import build_minimal_scheme_cards
19
+ from .missions import TASK_MISSIONS
20
+ from .orientation import (
21
+ ORIENTATION_PROMPT,
22
+ build_orientation_kickoff_message,
23
+ build_orientation_prompt,
24
+ )
25
+ from .planning import build_planning_prompt
26
+ from .react_suffix import REACT_SUFFIX
27
+ from .schema import DB_SCHEMA
28
+ from .scheme_phase import build_scheme_phase_prompt
29
+ from .system_prompt import build_system_prompt
30
+
31
+ __all__ = [
32
+ "DB_SCHEMA",
33
+ "FRAUD_CATALOGUE",
34
+ "TASK_MISSIONS",
35
+ "build_minimal_scheme_cards",
36
+ "build_system_prompt",
37
+ "ORIENTATION_PROMPT",
38
+ "build_orientation_prompt",
39
+ "build_orientation_kickoff_message",
40
+ "build_planning_prompt",
41
+ "build_scheme_phase_prompt",
42
+ "build_hypothesis_worker_prompt",
43
+ "build_hypothesis_summary_prompt",
44
+ "parse_hypothesis_summary_json",
45
+ "build_worker_brief_prompt",
46
+ "build_worker_summary_prompt",
47
+ "COMPACTION_PROMPT",
48
+ "REACT_SUFFIX",
49
+ ]
prompts/compaction.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ COMPACTION_PROMPT = """Summarise the key findings, hypotheses tested, evidence discovered, and any dead ends from the investigation steps above.
2
+
3
+ Your goal is to produce a **rich, highly detailed memory summary** that can be safely reused later, up to the memory summary token budget provided in the system instructions. Do **not** self-limit to a few hundred tokens; instead, use as much detail as is useful while staying within that budget.
4
+
5
+ The summary MUST explicitly preserve:
6
+ - Entity IDs (employee, vendor, customer) that are suspicious
7
+ - Document IDs that have been flagged
8
+ - GL account numbers that showed anomalies
9
+ - Monetary amounts and date ranges
10
+ - Which scheme types each finding relates to
11
+ - Open hypotheses and next investigation steps
12
+
13
+ Do NOT include raw SQL queries or full table outputs — only the conclusions drawn from them."""
prompts/fraud_catalogue.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FRAUD_CATALOGUE = """
2
+ ## Known Fraud Scheme Catalogue
3
+
4
+ **Only these 5 scheme types exist in the data** (no other fraud types are injected).
5
+ Each entry describes the **business process**, what “healthy” operations look like in substance,
6
+ and the **kinds of breakdown** that can indicate manipulation. It does **not** name expected GL
7
+ accounts, auxiliary formats, posting templates, or calendar cutoffs — those must come from **your**
8
+ profiling of this dataset (chart of accounts, distributions, joins, and master data).
9
+
10
+ ---
11
+
12
+ ### 1. Fictitious AP Disbursements
13
+
14
+ **Normal process (substance):** The organisation should only settle payables for goods or services
15
+ that were ordered, received or accepted, and invoiced under segregation of duties (e.g. different
16
+ actors for recording vs authorising payment). Vendor identity and payment references should be
17
+ consistent with normal operating practice.
18
+
19
+ **When something is wrong (conceptual):** Value may leave the entity without a defensible
20
+ procurement-to-pay trail: missing or weak evidence of receipt or approval, payables cleared without
21
+ a credible invoice trail, the same actors repeatedly spanning incompatible roles, timing or
22
+ vendor populations that diverge sharply from the rest of the ledger, or reference behaviour that
23
+ does not match how the company usually books AP and bank movements.
24
+
25
+ ---
26
+
27
+ ### 2. Revenue Manipulation (Window Dressing)
28
+
29
+ **Normal process (substance):** Revenue aligns with delivery or completion of performance
30
+ obligations; expenses and provisions are recognised in the appropriate periods; releases of
31
+ reserves or similar items require defensible economic events and governance.
32
+
33
+ **When something is wrong (conceptual):** Earnings can be inflated by recognising revenue too early,
34
+ pushing expenses out of the period, or releasing balances that should still reflect risk or
35
+ obligation. Suspect patterns are **relative**: unusual concentration in time, abnormal mixes of
36
+ lines or accounts for the same commercial story, or journal narratives and flows that do not
37
+ cohere with the rest of the order-to-cash and record-to-report activity in **this** database.
38
+
39
+ ---
40
+
41
+ ### 3. Vendor Collusion (Kickback + Related-Party)
42
+
43
+ **Normal process (substance):** Procurement and payment follow approved sourcing, pricing, and
44
+ approval chains; vendors are genuine third parties at arm’s length; segregation limits a single
45
+ actor from controlling selection, invoicing, and payment.
46
+
47
+ **When something is wrong (conceptual):** Inflated or biased spend, repeated coupling of the same
48
+ internal and external parties without rotation, payment behaviour that fragments or obscures totals,
49
+ weak master-data linkage, or indications that beneficiary or party data overlaps with insiders.
50
+ Signals are contextual: compare to peer vendors, amounts, and approval patterns in the same data.
51
+
52
+ ---
53
+
54
+ ### 4. Shadow Payroll (Ghost Employee)
55
+
56
+ **Normal process (substance):** Payroll pays real employees under HR and payroll policies, with
57
+ accruals and settlements that match the entity’s payroll design (which may include multiple line
58
+ types, schedules, and banking arrangements you must infer from the data).
59
+
60
+ **When something is wrong (conceptual):** Beneficiaries or pay runs that are structurally odd
61
+ relative to the population (e.g. accrual shape, timing clusters, banking or institution patterns,
62
+ recency of employment lifecycle events vs pay activity, or concentration of authorship) can indicate
63
+ diversion or synthetic beneficiaries. **Plausible HR rows do not rule out fraud** — treat master
64
+ data as necessary context, not as a whitelist.
65
+
66
+ ---
67
+
68
+ ### 5. Inventory Manipulation (Asset Misappropriation)
69
+
70
+ **Normal process (substance):** Inventory moves should trace to economic events (receipts,
71
+ consumption, sales, authorised adjustments). Write-downs and adjustments require authorised,
72
+ documented physical or operational justification.
73
+
74
+ **When something is wrong (conceptual):** Stock increases without credible upstream support,
75
+ write-offs disconnected from prior stock history, suspicious symmetry or pairing of movements,
76
+ period-close clustering of adjustments vs norms, or split roles across related postings may indicate
77
+ inflation, concealment, or misappropriation. Map **this** entity’s inventory-related accounts and
78
+ references from the ledger before concluding.
79
+
80
+ ---
81
+
82
+ **How to use this catalogue:** Use it to frame **hypotheses** and **questions**, not as a
83
+ checklist of built-in tests. All concrete controls, accounts, SQL filters, and thresholds must be
84
+ **derived and validated** against the chart of accounts and facts in the database.
85
+ """.strip()
prompts/hypothesis_worker.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Prompts for per-hypothesis investigation workers (core_spec v2)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+
6
+ from researchpkg.forensic_llm.config import (
7
+ TextTruncationLimits,
8
+ )
9
+ from researchpkg.forensic_llm.models import (
10
+ HypothesisTaskBrief,
11
+ WorkerBrief,
12
+ )
13
+ from researchpkg.forensic_llm.prompts.investigation_discipline import (
14
+ COMPREHENSIVE_INVESTIGATION_GUIDANCE,
15
+ HYPOTHESIS_INVESTIGATION_DEPTH,
16
+ REPORT_SUSPICION_DISCIPLINE,
17
+ )
18
+ from researchpkg.forensic_llm.text_truncation import (
19
+ TruncationSide,
20
+ truncate_text_to_tokens,
21
+ )
22
+
23
+
24
+ def build_hypothesis_worker_prompt(
25
+ brief: HypothesisTaskBrief,
26
+ text_limits: TextTruncationLimits | None = None,
27
+ ) -> str:
28
+ lim = text_limits or TextTruncationLimits()
29
+ shared = brief.shared_context or {}
30
+ shared_excerpt = truncate_text_to_tokens(
31
+ shared.get("global_memory_excerpt", "") or "",
32
+ lim.hypothesis_worker_shared_memory,
33
+ side=TruncationSide.TAIL,
34
+ )
35
+ peer_block = ""
36
+ peers = shared.get("peer_hypothesis_summaries") or []
37
+ if peers:
38
+ peer_block = "\n**Peer hypotheses (same scheme):**\n" + "\n".join(
39
+ f"- {p.get('hypothesis_id')}: {p.get('status')} — {p.get('key_finding', '')}"
40
+ for p in peers
41
+ )
42
+
43
+ return (
44
+ f"## Hypothesis investigation task: `{brief.task_id}`\n\n"
45
+ f"- **Scheme:** `{brief.scheme}`\n"
46
+ f"- **Hypothesis ID:** `{brief.hypothesis_id}`\n"
47
+ f"- **Token budget:** {brief.budget_tokens:,} (the planner allocated this envelope for **your** hypothesis — treat it as a target to work toward through SQL + reasoning, not a ceiling to leave mostly unused)\n\n"
48
+ f"### Hypothesis\n{brief.hypothesis_text}\n\n"
49
+ + (
50
+ f"### Why this task (planner rationale)\n{brief.hypothesis_rationale}\n\n"
51
+ if (brief.hypothesis_rationale or "").strip()
52
+ else ""
53
+ )
54
+ + f"### Exit criteria\n"
55
+ + "\n".join(f"- {c}" for c in brief.exit_criteria)
56
+ + "\n\n"
57
+ f"### Benign rival explanations to falsify\n"
58
+ + "\n".join(f"- {b}" for b in brief.benign_rivals)
59
+ + "\n\n"
60
+ f"### Planned query families\n"
61
+ + "\n".join(f"- {q}" for q in brief.planned_query_families)
62
+ + "\n\n"
63
+ f"### Shared context\n```\n{shared_excerpt}\n```\n" + peer_block + "\n\n"
64
+ "### Operating rules\n"
65
+ "1. Investigate **only** this hypothesis — but investigate it **thoroughly** (screen → drill → "
66
+ "falsify benign rivals → follow material leads). **Spend most of your allocated token budget** "
67
+ "unless you reach a decisive verdict very early with dense SQL evidence.\n"
68
+ "2. Use the **planned query families** unless evidence justifies a documented deviation "
69
+ "(note in scratchpad).\n"
70
+ "3. **`report_suspicion`** whenever you have SQL-backed suspicious `je_header.document_id` UUIDs "
71
+ "— during investigation, not only in the summary.\n"
72
+ "4. Use `blackboard_write` for entity findings relevant to other schemes.\n"
73
+ "5. Do **not** call `finish_investigation`.\n"
74
+ "6. Stop tool use only when the verdict is evidence-backed — a summary step follows.\n"
75
+ "7. **Budget:** the scratchpad *Run context* shows **Task input budget** (% used / "
76
+ "remaining). If SQL-backed evidence confirms fraud, call `report_suspicion` *before* "
77
+ "you exhaust that cap—do not plan heavy exports when the % is already high.\n\n"
78
+ + HYPOTHESIS_INVESTIGATION_DEPTH
79
+ + "\n"
80
+ + COMPREHENSIVE_INVESTIGATION_GUIDANCE
81
+ + "\n"
82
+ + REPORT_SUSPICION_DISCIPLINE
83
+ )
84
+
85
+
86
+ def build_hypothesis_summary_prompt(
87
+ brief: HypothesisTaskBrief,
88
+ text_limits: TextTruncationLimits | None = None,
89
+ ) -> str:
90
+ lim = text_limits or TextTruncationLimits()
91
+ hyp_text = truncate_text_to_tokens(
92
+ brief.hypothesis_text or "",
93
+ lim.hypothesis_worker_hypothesis_text,
94
+ side=TruncationSide.HEAD,
95
+ ).replace('"', "'")
96
+ hyp_rat = truncate_text_to_tokens(
97
+ brief.hypothesis_rationale or "",
98
+ lim.hypothesis_rationale_store,
99
+ side=TruncationSide.TAIL,
100
+ ).replace('"', "'")
101
+ return (
102
+ f"Produce the structured JSON summary for hypothesis `{brief.hypothesis_id}` "
103
+ f"on scheme `{brief.scheme}`. Respond with ONLY the JSON object.\n\n"
104
+ "**`flagged_document_ids`:** must match every UUID you reported via `report_suspicion` "
105
+ "during this task (same IDs from SQL). If status is `confirmed` and you have exemplar JEs, "
106
+ "this list must be non-empty. Use `[]` only when status is `falsified`.\n\n"
107
+ "```json\n"
108
+ "{\n"
109
+ f' "scheme": "{brief.scheme}",\n'
110
+ f' "hypothesis_id": "{brief.hypothesis_id}",\n'
111
+ f' "hypothesis_text": "{hyp_text}",\n'
112
+ f' "hypothesis_rationale": "{hyp_rat}",\n'
113
+ ' "status": "<confirmed|falsified|inconclusive>",\n'
114
+ ' "finish_reason": "<completed|task_budget_stop_frac|task_budget_exhausted|worker_error>",\n'
115
+ ' "flagged_document_ids": ["<uuid>", "..."],\n'
116
+ ' "flagged_entities": ["<entity_id>", "..."],\n'
117
+ ' "key_findings": "<2-4 sentences: what you tested, what data showed, verdict rationale>",\n'
118
+ ' "evidence_checks_run": ["<screen>", "<drill>", "<benign rival>", "..."],\n'
119
+ ' "benign_rivals_considered": ["..."],\n'
120
+ ' "open_questions": ["..."],\n'
121
+ ' "error": null\n'
122
+ "}\n"
123
+ "```"
124
+ )
125
+
126
+
127
+ def build_worker_brief_prompt(brief: WorkerBrief) -> str:
128
+ """Legacy autonomous worker brief (deprecated path)."""
129
+ candidate_schemes = (
130
+ ", ".join(brief.candidate_schemes) if brief.candidate_schemes else "unspecified"
131
+ )
132
+ return (
133
+ f"## Worker Brief: {brief.worker_id}\n\n"
134
+ f"- Goal: `{brief.scheme_or_goal}`\n"
135
+ f"- Candidate schemes: {candidate_schemes}\n"
136
+ f"- Budget tokens: {brief.budget_tokens:,}\n\n"
137
+ f"{brief.brief}\n\n"
138
+ "Do not call `finish_investigation`. Use `report_suspicion` for confirmed JEs."
139
+ )
140
+
141
+
142
+ def build_worker_summary_prompt(brief: WorkerBrief) -> str:
143
+ """Legacy autonomous worker summary (deprecated path)."""
144
+ return (
145
+ f"Summarize worker `{brief.worker_id}` as JSON only.\n"
146
+ '{"worker_id": "...", "scheme_or_goal": "...", "status": "completed", '
147
+ '"flagged_document_ids": ["<uuid>"], "key_findings": "..."}'
148
+ )
149
+
150
+
151
+ def parse_hypothesis_summary_json(text: str, brief: HypothesisTaskBrief) -> dict:
152
+ from researchpkg.forensic_llm.json_utils import (
153
+ extract_first_json_object,
154
+ )
155
+
156
+ obj = extract_first_json_object(text or "") or {}
157
+ obj.setdefault("scheme", brief.scheme)
158
+ obj.setdefault("hypothesis_id", brief.hypothesis_id)
159
+ obj.setdefault("hypothesis_text", brief.hypothesis_text)
160
+ obj.setdefault("hypothesis_rationale", brief.hypothesis_rationale)
161
+ obj.setdefault("status", "inconclusive")
162
+ if "finish_reason" not in obj:
163
+ obj["finish_reason"] = None
164
+ return obj
prompts/investigation_discipline.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared investigation discipline blocks for prompts."""
2
+
3
+ TOOL_NEUTRAL_OPERATING = (
4
+ "Every tool call must serve a specific, falsifiable hypothesis: surface a signal, "
5
+ "discriminate rival explanations, or retrieve JE-level evidence. Choose the tool "
6
+ "that fits the question — do not default to sql preview when population-level analysis, "
7
+ "graphs, or exports are the right next step."
8
+ )
9
+
10
+ TOOL_SELECTION_GUIDANCE = """
11
+ ### Tool selection (no SQL default)
12
+ | Need | Preferred tools |
13
+ |------|-----------------|
14
+ | Aggregates, filters, small result sets | `sql` with `mode='preview'` (default max_rows 50) |
15
+ | Full population, >50 rows, Benford, distributions, clustering | `sql` with `mode='export'` → `code_interpreter` → `read_image` if charted |
16
+ | Vendor–employee bank overlap, circular payments, related-party paths | `sql(mode='export')` + `code_interpreter` (NetworkX joins on exported tables) |
17
+ | Flagging specific journal entries | `sql` preview/export + filter in `code_interpreter`, then `report_suspicion` when appropriate |
18
+
19
+ **Anti-patterns:** repeated `sql` preview with arbitrary `LIMIT` when the answer needs the full population; finishing a hypothesis after one null preview without reformulation or export-and-analyze; entity-level conclusions without supporting transaction evidence when JEs exist.
20
+ """
21
+
22
+ HYPOTHESIS_FORMATION_GUIDANCE = """
23
+ ### Hypothesis formation (planning)
24
+ Form **ranked, testable** investigation angles from orientation evidence — write in **plain forensic
25
+ language**, not a rigid template.
26
+
27
+ **Do not** use boilerplate ``If … then …`` phrasing. Each hypothesis needs two fields:
28
+ - ``hypothesis_text``: a concise claim about what might be wrong (one or two sentences).
29
+ - ``hypothesis_rationale``: **one paragraph** tying the claim to orientation signals, what SQL or
30
+ analysis would test it, and what outcome would support vs rule out the scheme (including one
31
+ plausible benign rival).
32
+
33
+ Other rules:
34
+ - Assign **P1, P2, …** within each scheme (P1 = strongest angle for that scheme).
35
+ - **Cover the forensic surface area** before merging ideas: entities & master data, timing & cut-off,
36
+ amounts & concentration, approvals & segregation, period-end behavior, control-account
37
+ reconciliations, and cross-party links (vendor↔customer↔employee) where data allows.
38
+ One queue entry ≈ one distinct test.
39
+ - **Prefer breadth over a single umbrella line** per scheme: high-risk schemes deserve many distinct
40
+ angles; lower-priority schemes still need enough lines for a credible RULED_OUT.
41
+ - In ``dispatch_queue``, list rows in **P-wave order** (all schemes' ``P1``, then all ``P2``, …); do not block by scheme.
42
+ - Every ``dispatch_queue`` entry must include both ``hypothesis_text`` and ``hypothesis_rationale``.
43
+ - Mirror the same ``P`` ids, text, and rationale in ``phases[].initial_hypotheses`` (as objects, not
44
+ legacy string lines).
45
+ """
46
+
47
+ COMPREHENSIVE_INVESTIGATION_GUIDANCE = """
48
+ ### Comprehensive investigation standard (prompt discipline — not a step quota)
49
+ Treat this engagement like a **full forensic file**, not a quick anomaly scan. Depth comes from
50
+ **evidence quality**, not from repeating the same query.
51
+
52
+ **Orientation & planning**
53
+ - Build measured baselines (rates, concentrations, period structure) before accusing fraud.
54
+ - Plans should enumerate **distinct** hypotheses and concrete query families per scheme — workers
55
+ inherit your brief; vague plans produce shallow tasks.
56
+
57
+ **Per-hypothesis execution**
58
+ - Typical thorough path: **screen** (does the signal exist?) → **drill** (who/what/when/how much?) →
59
+ **falsify a benign rival** (could this be process design, master-data gap, or IC timing?) →
60
+ **discriminative check** when populations are large → **`report_suspicion`** for exemplar JEs.
61
+ - A null or weak screen is not a verdict: reformulate (different join, window, account slice, or
62
+ export-and-analyze) before RULED_OUT.
63
+ - When a pattern is material, trace **follow-on questions** (linked accounts, same actor, adjacent
64
+ periods, monetary roll-up) until the story is complete or clearly explained away.
65
+ - Use **`sql(mode='export')` + `code_interpreter`** whenever the question is about distributions,
66
+ rates, concentration, or >50 rows — previews are for EXISTS and small top-k, not population proof.
67
+
68
+ **When to stop on a hypothesis**
69
+ - Stop when you can defend CONFIRMED / RULED_OUT / INCONCLUSIVE with cited SQL outcomes — not when
70
+ you have merely run a few queries. Premature closure wastes the budget and misses fraud.
71
+ """
72
+
73
+ HYPOTHESIS_INVESTIGATION_DEPTH = """
74
+ ### Hypothesis investigation depth
75
+ Use **as many tool calls as the hypothesis requires** (`sql`, `code_interpreter`, `read_image`).
76
+ There is no target query count — there is a **standard of proof**.
77
+
78
+ Before a verdict, you should usually have:
79
+ - screened whether the signal exists in the population,
80
+ - drilled into the strongest candidates (entities, amounts, periods, control bypass),
81
+ - tested at least one **plausible benign rival** explanation with data,
82
+ - retrieved `document_id` UUIDs for any JEs you will report or reference.
83
+
84
+ If a screening step returns zero rows, reformulate once (time window, account range, join path, or
85
+ export-and-analyze) before RULED_OUT. If a pattern is confirmed, consider whether adjacent slices
86
+ (same user, vendor, period cluster) warrant a short follow-up before closing the hypothesis.
87
+ """
88
+
89
+ DISCRIMINATIVENESS_BEFORE_FLAG = """
90
+ Before `report_suspicion`, verify the signal is **discriminative**.
91
+ Use `sql(mode='export')` + `code_interpreter` to compare flagged vs non-flagged rates when the population is large.
92
+ """
93
+
94
+ REPORT_SUSPICION_DISCIPLINE = """
95
+ ### JE reporting (`report_suspicion`) — required for evaluation
96
+ Benchmark scoring uses **`detections.json`**, which is populated **only** via `report_suspicion`
97
+ (not from scratchpad prose alone).
98
+
99
+ **When you MUST call `report_suspicion`:**
100
+ - You retrieved one or more `je_header.document_id` UUIDs that exemplify the fraud pattern for this hypothesis.
101
+ - Status is **CONFIRMED** with clear SQL-backed evidence — include exemplar JEs only (not every row in a large export).
102
+ - After `sql`/`code_interpreter` identifies a bounded set of suspicious postings — report **before** stopping tool use.
103
+
104
+ **How to report:**
105
+ - Prefer batch: `suspicions: [{document_id, scheme_type, rationale}, ...]` (up to ~50 per call; repeat if needed).
106
+ - `document_id` = UUID from column `document_id` / `jh.document_id` only — never reference, line_number, or auxiliary account.
107
+ - `scheme_type` = the task scheme (e.g. `shadow_payroll`).
108
+
109
+ **When NOT to report:** hypothesis **RULED OUT** with no suspicious JEs after reformulation — leave detections empty.
110
+
111
+ **Workflow:** screen → drill → (optional discriminative check) → **`report_suspicion`** → scratchpad verdict.
112
+ """
113
+
114
+ # Back-compat alias for imports that still reference the old name.
115
+ GROUNDING_AFTER_CONFIRMED = HYPOTHESIS_INVESTIGATION_DEPTH
prompts/minimal_scheme_cards.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SCHEME_CARDS = {
2
+ "fictitious_ap_disbursements": {
3
+ "process_anchor": "P2P / accounts payable / disbursements",
4
+ "economic_meaning": (
5
+ "Cash leaves the company for goods or services that were not genuinely "
6
+ "received, approved, or owed."
7
+ ),
8
+ },
9
+ "revenue_manipulation": {
10
+ "process_anchor": "O2C and R2R / revenue recognition / period close",
11
+ "economic_meaning": (
12
+ "Revenue, expense timing, or reserves are adjusted to inflate current-period "
13
+ "earnings (early revenue, expense deferral, reserve release)."
14
+ ),
15
+ },
16
+ "vendor_collusion": {
17
+ "process_anchor": "Procurement / vendor onboarding / invoice approval",
18
+ "economic_meaning": (
19
+ "An internal actor and an external vendor coordinate to divert value "
20
+ "through biased, inflated, or related-party purchasing activity."
21
+ ),
22
+ },
23
+ "shadow_payroll": {
24
+ "process_anchor": "H2R / payroll / employee master data",
25
+ "economic_meaning": (
26
+ "Payroll is diverted to a synthetic or colluding beneficiary, often "
27
+ "onboarded in HR with plausible identity "
28
+ ),
29
+ },
30
+ "inventory_manipulation": {
31
+ "process_anchor": "Inventory / stock movements / write-offs / close",
32
+ "economic_meaning": (
33
+ "Inventory is inflated, concealed, or written off in a way that is not "
34
+ "consistent with real stock movement or physical operations."
35
+ ),
36
+ },
37
+ }
38
+
39
+
40
+ def build_minimal_scheme_cards(task: str = "full") -> str:
41
+ """
42
+ Render a minimal closed-world scheme catalogue.
43
+
44
+ This variant provides only high-level business-process anchors and economic meaning.
45
+ It avoids prescribing investigative angles, control checks, SQL patterns, or expected
46
+ anomaly signatures so the model must derive its own path from the ledger.
47
+ """
48
+
49
+ if task != "full" and task in SCHEME_CARDS:
50
+ keys = [task]
51
+ else:
52
+ keys = list(SCHEME_CARDS.keys())
53
+
54
+ lines = [
55
+ "## Closed-World Scheme Cards",
56
+ "",
57
+ "The benchmark contains only the scheme families listed below.",
58
+ "These are problem labels and process anchors, not solution templates.",
59
+ "You are NOT given expected SQL tests, control-failure checklists, or",
60
+ "known account patterns. You must derive those from the ledger.",
61
+ "",
62
+ ]
63
+
64
+ for idx, key in enumerate(keys, start=1):
65
+ card = SCHEME_CARDS[key]
66
+ lines.append(f"### {idx}. {key}")
67
+ lines.append(f"- Process anchor: {card['process_anchor']}")
68
+ lines.append(f"- Economic meaning: {card['economic_meaning']}")
69
+ lines.append("")
70
+
71
+ allowed = ", ".join(
72
+ keys if task != "full" and task in SCHEME_CARDS else SCHEME_CARDS
73
+ )
74
+ lines.extend(
75
+ [
76
+ "Allowed final labels:",
77
+ f"- {allowed}",
78
+ "- unknown",
79
+ ]
80
+ )
81
+ return "\n".join(lines)
prompts/missions.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TASK_MISSIONS: dict[str, str] = {
2
+ "full": (
3
+ "Your mission is a **comprehensive forensic investigation** focused exclusively "
4
+ "on the five fraud schemes in the catalogue. You have no prior knowledge of "
5
+ "which schemes, if any, are present in this ledger. "
6
+ "Apply the full fraud catalogue: (1) fictitious AP disbursements, (2) revenue "
7
+ "manipulation, (3) vendor collusion, (4) shadow payroll, "
8
+ "and (5) inventory manipulation. "
9
+ "Begin with a broad orientation of the ledger, then form and test hypotheses "
10
+ "systematically across these five scheme types only. "
11
+ "**You have a large investigation budget — treat this as a full engagement, not a quick scan. "
12
+ "A superficial investigation that finishes early is a failed investigation. "
13
+ "Use your budget to go deep: multiple hypotheses per scheme, multiple queries per hypothesis, "
14
+ "drill-down on every promising lead before moving on.**"
15
+ ),
16
+ # -----------------------------------------------------------------------
17
+ # Per-scheme missions used by parallel worker agents.
18
+ # Each worker investigates exactly one scheme in isolation.
19
+ # -----------------------------------------------------------------------
20
+ "fictitious_ap_disbursements": (
21
+ "Your mission is a **focused investigation of fictitious AP disbursements** "
22
+ "(salami-slicing via fictitious invoices, expense-laundering through real vendors, "
23
+ "systematic small-amount diversions to shell or front vendors). "
24
+ "You are a **parallel worker** — other agents are simultaneously investigating "
25
+ "the four other fraud schemes. Do NOT investigate other scheme types. "
26
+ "Prioritise your queries on AP-cycle JEs, below-threshold payments, repeated small credits "
27
+ "to the same GL/vendor, suspense account activity, and vendor master anomalies. "
28
+ "Call `report_suspicion` immediately for every confirmed finding. "
29
+ "Do NOT call `finish_investigation`."
30
+ ),
31
+ "revenue_manipulation": (
32
+ "Your mission is a **focused investigation of revenue manipulation** "
33
+ "(quarter-end inflation, premature recognition, next-period reversals). "
34
+ "You are a **parallel worker** — other agents are simultaneously investigating "
35
+ "the four other fraud schemes. Do NOT investigate other scheme types. "
36
+ "Prioritise your queries on revenue GL accounts, period-end postings, "
37
+ "manual journal entries, and reversal patterns. "
38
+ "Call `report_suspicion` immediately for every confirmed finding. "
39
+ "Do NOT call `finish_investigation`."
40
+ ),
41
+ "vendor_collusion": (
42
+ "Your mission is a **focused investigation of vendor collusion** "
43
+ "(inflated invoices with kickbacks, related-party undisclosed relationships, "
44
+ "vendor-employee bank account sharing, insider approval of affiliated-vendor payments). "
45
+ "You are a **parallel worker** — other agents are simultaneously investigating "
46
+ "the four other fraud schemes. Do NOT investigate other scheme types. "
47
+ "Prioritise your queries on vendor payment amounts, vendor–employee relationships, "
48
+ "bank account cross-matches, high-value single-vendor concentration, and approval metadata. "
49
+ "Call `report_suspicion` immediately for every confirmed finding. "
50
+ "Do NOT call `finish_investigation`."
51
+ ),
52
+ "shadow_payroll": (
53
+ "Your mission is a **focused investigation of shadow payroll fraud** "
54
+ "(ghost employees, payroll diversions, and terminated-employee payments). "
55
+ "You are a **parallel worker** — other agents are simultaneously investigating "
56
+ "the four other fraud schemes. Do NOT investigate other scheme types. "
57
+ "Prioritise your queries on payroll-related GL accounts, the employees table, "
58
+ "and je_header/je_line entries linked to payroll postings. "
59
+ "Call `report_suspicion` immediately for every confirmed finding. "
60
+ "Do NOT call `finish_investigation`."
61
+ ),
62
+ "inventory_manipulation": (
63
+ "Your mission is a **focused investigation of inventory manipulation** "
64
+ "(fictitious receipt postings, write-off abuse, shrinkage overstatement). "
65
+ "You are a **parallel worker** — other agents are simultaneously investigating "
66
+ "the four other fraud schemes. Do NOT investigate other scheme types. "
67
+ "Prioritise your queries on inventory GL accounts, goods-receipt JEs, "
68
+ "write-off entries, and cost-of-goods postings. "
69
+ "Call `report_suspicion` immediately for every confirmed finding. "
70
+ "Do NOT call `finish_investigation`."
71
+ ),
72
+ }
prompts/orchestrator_followup.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Orchestrator follow-up hypothesis proposal (core_spec v2 dynamic queue)."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from typing import Any, Dict, List
6
+
7
+ from researchpkg.forensic_llm.config import (
8
+ TextTruncationLimits,
9
+ )
10
+ from researchpkg.forensic_llm.models import (
11
+ HypothesisResult,
12
+ )
13
+ from researchpkg.forensic_llm.text_truncation import (
14
+ TruncationSide,
15
+ truncate_text_to_tokens,
16
+ )
17
+
18
+
19
+ def build_orchestrator_followup_prompt(
20
+ last_result: HypothesisResult,
21
+ global_excerpt: str,
22
+ existing_task_ids: List[str],
23
+ max_proposals: int = 2,
24
+ text_limits: TextTruncationLimits | None = None,
25
+ ) -> str:
26
+ """Compact one-shot prompt — no orientation conversation history."""
27
+ lim = text_limits or TextTruncationLimits()
28
+ result_json = truncate_text_to_tokens(
29
+ json.dumps(last_result.model_dump(mode="json"), indent=2, default=str),
30
+ lim.orchestrator_followup_json,
31
+ side=TruncationSide.TAIL,
32
+ )
33
+ memory_excerpt = truncate_text_to_tokens(
34
+ global_excerpt or "",
35
+ lim.orchestrator_followup_memory,
36
+ side=TruncationSide.TAIL,
37
+ )
38
+ return (
39
+ "## Orchestrator: propose follow-up hypothesis tasks\n\n"
40
+ "Based on the **just-completed** hypothesis result and shared memory, "
41
+ f"propose **0–{max_proposals}** new investigation tasks to run next. "
42
+ "Each task must be a **single distinct investigation angle** for one scheme (free-form text, "
43
+ "not ``If … then …`` boilerplate).\n\n"
44
+ f"**Completed task:** `{last_result.task_id}`\n"
45
+ f"```json\n{result_json}\n```\n\n"
46
+ f"**Shared memory excerpt:**\n```\n{memory_excerpt}\n```\n\n"
47
+ f"**Already queued or done (do not duplicate):** {', '.join(existing_task_ids[:40])}\n\n"
48
+ "Respond with **ONLY** a JSON array (no markdown fences):\n"
49
+ "[\n"
50
+ ' {"scheme": "<scheme_type>", "hypothesis_text": "<concise claim>", '
51
+ '"hypothesis_rationale": "<one paragraph: why now, what to test, confirm vs rule-out>", '
52
+ '"dispatch_priority": <int lower runs sooner>}\n'
53
+ "]\n\n"
54
+ "Rules:\n"
55
+ "- Prefer tracing entities, accounts, or JEs surfaced in `open_questions` or `key_findings`.\n"
56
+ "- Use an existing scheme from the fraud catalogue; do not invent scheme names.\n"
57
+ "- Empty array `[]` if no follow-up is justified.\n"
58
+ )
59
+
60
+
61
+ def parse_followup_proposals(raw: str) -> List[Dict[str, Any]]:
62
+ """Parse LLM JSON array of follow-up proposals."""
63
+ text = (raw or "").strip()
64
+ if not text:
65
+ return []
66
+ if text.startswith("```"):
67
+ lines = text.split("\n")
68
+ text = "\n".join(lines[1:-1] if len(lines) > 2 else lines).strip()
69
+ start = text.find("[")
70
+ end = text.rfind("]")
71
+ if start < 0 or end <= start:
72
+ return []
73
+ try:
74
+ data = json.loads(text[start : end + 1])
75
+ except json.JSONDecodeError:
76
+ return []
77
+ if not isinstance(data, list):
78
+ return []
79
+ out: List[Dict[str, Any]] = []
80
+ for row in data:
81
+ if isinstance(row, dict) and row.get("hypothesis_text"):
82
+ out.append(row)
83
+ return out
prompts/orientation.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ ORIENTATION_MANDATORY_CHECKLIST = """\
4
+ **Mandatory coverage before `complete_orientation`** — write like an investigator's **field notes**:
5
+ dense explanatory prose first; tables are supporting evidence, not a substitute for understanding.
6
+
7
+ **Every major `##` section must include:**
8
+ - **2–5 paragraphs** (or equivalent bullet depth) explaining *what you learned*, *how entities link*,
9
+ *what is structurally normal here*, and *what planning should know* — with measured numbers woven in.
10
+ - **At least one supporting table** only where it helps (vendor census, top-10 GL/aux/users, cross-tab);
11
+ never a report that is only tables with one-line captions.
12
+
13
+ **Required topics** (exact `##` headings where noted):
14
+
15
+ 1. **`## Vendor / AP master`** — narrative on AP linkage (`auxiliary_gl_account` ↔ lines), P2P behavior,
16
+ self-balancing patterns; **plus** a table of **every** vendor:
17
+ `vendor_id` | `auxiliary_gl_account` | P2P lines | debit | credit | self-balancing docs.
18
+ **Call out** shell vendors `V-000021`–`V-000023` (same `V-{n:06}` / `401{n:04}` style as `V-000001`–`V-000020`);
19
+ contrast P2P volume, self-balancing doc share, and posters — not ID format alone.
20
+
21
+ 2. **`## Revenue / COA`** — explain COA membership vs `je_line` usage; revenue timing and posters;
22
+ **plus** each revenue GL for the latest material year (credit, line/JE counts). Resolve totals with SQL.
23
+
24
+ 3. **`## O2C × vendor/aux`** — explain whether vendor auxiliaries hit customer/O2C paths; **plus** cross-tab
25
+ or explicit zero-row proof with the filter used.
26
+
27
+ 4. **Structural baselines in prose** (dedicated `##` sections): schema/grain, process mix, fiscal/period-end
28
+ behavior, control-field coverage, user/actor tiers, reference patterns, per-process GL corridors.
29
+
30
+ 5. **Top-N summaries** — top 10 GL, top 10 aux, top 10 users: **table + short interpretation**
31
+ (why these dominate, which processes drive them).
32
+
33
+ 6. **`## Planning leads`** (single final section) — neutral **test intents** only; no fraud/scheme vocabulary.
34
+
35
+ **Completion hygiene**
36
+ - **No** `TBD`, `TODO`, “need to verify” — run follow-up SQL first.
37
+ - **Banned** in orientation: fraud, suspicious, anomaly, red flag, scheme, manipulation, window dressing, etc.
38
+ - **Bad:** 300 lines of tables and no ledger narrative. **Good:** rich prose sections with selective supporting tables.
39
+ """
40
+
41
+ ORIENTATION_SCREENING_RULES = """\
42
+ Begin a thorough **orientation / database profiling phase** for this ledger.
43
+
44
+ **CRITICAL SEPARATION OF CONCERNS:**
45
+ Your role in this phase is **DATABASE UNDERSTANDING ONLY** — build a comprehensive statistical and structural profile.
46
+ **DO NOT** draw fraud conclusions, identify suspicious patterns, or form hypotheses. That happens in the **planning phase**.
47
+
48
+ **Your mission:**
49
+ 1. Understand the **schema** — tables, keys, relationships, data types
50
+ 2. Profile the **structure** — chart of accounts, business processes, hierarchies
51
+ 3. Quantify **statistical distributions** — amounts, frequencies, time patterns
52
+ 4. Map **data linkages** — how master data connects to transactions
53
+ 5. Establish **baselines** — what "normal" looks like in this dataset
54
+
55
+ **NO fraud conclusions yet.** Planning phase will use your profiles to design targeted tests.
56
+
57
+ **Depth expectation:** Produce a **long, decision-ready** report — many `##` sections of **investigative
58
+ narrative** (how the ledger works, how data links, what baselines look like), not a spreadsheet export.
59
+ Planning reads the **raw orientation report** (first ~100k tokens); every critical baseline must be
60
+ **explained in prose** in the report, not only in SQL you ran once.
61
+
62
+ **No scratchpad.** Persist findings via `orientation_report(mode="append")` — **update the report often**
63
+ (after each meaningful SQL or analysis batch, not only at the end).
64
+
65
+ **Context layout every LLM call (fixed prefix):**
66
+ 1. **System prompt** — role, schema, tools
67
+ 2. **[Current Orientation Report]** — cumulative findings on disk
68
+ 3. **Recent steps** — last assistant/tool turns (token-capped; may truncate old SQL)
69
+ 4. **[Current Step]** — active checkpoint + in-flight SQL/tool output
70
+
71
+ **Per-step workflow**
72
+ 1. Screen with `sql` / `code_interpreter` as needed.
73
+ 2. **Synthesize in your own words** what the data means (linkage, grain, distributions, gaps).
74
+ 3. **`orientation_report(mode="append")`** — add a `##` section: **prose first**, then tables if useful.
75
+
76
+ **Report format — investigator field notes (tables + prose):**
77
+ - **Lead with explanatory prose** (paragraphs or rich bullets): schema relationships, process behavior,
78
+ who posts what, how auxiliaries tie to master data, period-end shape, control-field emptiness.
79
+ - Use **markdown tables** for enumerations (full vendor census, top-10 GL/aux/users, cross-tabs) — synthesized,
80
+ not 1000-row SQL dumps — **after** you explain why the table matters.
81
+ - Each `##` section needs **numbers embedded in narrative** (%, counts, €, dates, named IDs) — not table-only sections.
82
+ - Drill into **specific entities** when SQL surfaces concentration (named vendor/customer/user/document patterns).
83
+
84
+ **SQL patterns (orientation)**
85
+ - Vendor census + P2P stats: join `vendors` → `je_line` on `auxiliary_account_number = auxiliary_gl_account`
86
+ filtered to `business_process = 'P2P'`; aggregate lines and self-balancing `document_id` counts.
87
+ - Revenue by account: filter `chart_of_accounts.account_type = 'Revenue'` (or class 7) for the target fiscal year.
88
+ - O2C×vendor: O2C headers/lines with `411%` aux intersecting same document with vendor `401%` aux.
89
+
90
+ **Entity- and linkage-specific profiling (high value for planning):**
91
+ - **P2P / AP:** vendor `auxiliary_gl_account` ↔ `je_line.auxiliary_account_number` join
92
+ patterns; lines with vs without aux; top auxiliaries by volume; self-balancing documents
93
+ - **O2C / AR:** customer auxiliaries; any vendor aux appearing in O2C; revenue account usage
94
+ - **H2R:** payroll GL concentration; whether employee IDs appear on lines
95
+ - **Master data:** NULL rates **per field** (not only “many NULLs”); list **named** vendors,
96
+ customers, or employees when a pattern is concentrated (IDs, aux numbers, bank fields)
97
+ - **Controls:** lettrage match %, `reconciliation_account`, cost_center / profit_center fill rates
98
+
99
+ **Required coverage before `complete_orientation`** (each as a substantive `##` section with prose + numbers)
100
+ - Schema & grain — how headers/lines/master tables join; fiscal span; company/currency/doc type constraints
101
+ - Chart of Accounts — hierarchy, account types, which GLs dominate **and why** they appear across processes
102
+ - Process mix & sources — what each BP is used for in *this* ledger; manual vs automated split
103
+ - Monetary corridors — typical debit/credit pairings per BP; background vs process-specific accounts
104
+ - Actors — user tiers, service accounts, concentration; tie to departments/employees where possible
105
+ - Period structure — month/quarter/year-end volume; weekend/off-hours if relevant
106
+ - Master data — vendors/customers/employees: coverage, NULL fields, naming/id conventions
107
+ - Controls & references — lettrage, cost/profit center, aux fill rates; reference prefix families (PO-, SO-, …)
108
+
109
+ **Depth**
110
+ - Prefer `sql(mode='export')` + `code_interpreter` for populations and cross-tabs.
111
+ - Run **follow-up** SQL when a preview row looks structurally unusual (e.g. one aux with
112
+ debit=credit totals, sparse revenue months, weekend posting in a process).
113
+ - Aim to **use most of the orientation token budget** on substantive profiling, not idle turns.
114
+ - Focus on **WHAT** and **HOW MUCH**, not **WHY** or **SUSPICIOUS**.
115
+ - Do **not** emit `investigation_plan.json`, `report_suspicion`, or `finish_investigation` here.
116
+ - Do **not** use fraud vocabulary (see banned list in checklist above) — save interpretive testing for planning.
117
+
118
+ **Chart of Accounts — ALWAYS profile in detail:**
119
+ - Hierarchy levels (Level 1: classes, Level 2: subclasses, Level 3-6: groups/detail)
120
+ - Account type distribution (Asset, Liability, Equity, Revenue, Expense)
121
+ - Top 20 accounts by turnover (debit and credit separately)
122
+ - Account usage frequency (documents per account)
123
+ - Debit/credit pairing patterns (which accounts commonly pair together)
124
+
125
+ **Example of correct framing:**
126
+ ✅ GOOD (prose): "Revenue is sparse: only 321 lines (0.05%) hit class-7 accounts, totaling €89.6M credit
127
+ across 701000 and 758000. Most lines are expense/tiers; planning should treat revenue as a thin corridor
128
+ and test concentration in 758000 (23 lines, all R2R, exec0003, 2025-P4–P6)."
129
+ ✅ GOOD (table + prose): Top-10 GL table, then a paragraph on why 603000/641100/645100 appear in every BP.
130
+ ❌ BAD: A section that is only a markdown table with no explanation.
131
+ ❌ BAD: "Revenue accounts are suspiciously low — possible fraud."
132
+
133
+ **Remember:** You are building the **foundation** for planning. Planning phase will interpret your findings.
134
+ """
135
+
136
+ ORIENTATION_SCREENING_RULES = (
137
+ ORIENTATION_SCREENING_RULES.rstrip() + "\n\n" + ORIENTATION_MANDATORY_CHECKLIST
138
+ )
139
+
140
+ ORIENTATION_CURRENT_STEP_PREFIX = (
141
+ "[Current Step]\n\n"
142
+ "Active database profiling step. SQL/tool results in this turn are **not** retained next step — "
143
+ "only `orientation_report` appends persist.\n"
144
+ )
145
+
146
+ ORIENTATION_CURRENT_STEP_KICKOFF_SUFFIX = (
147
+ "\n\nStart database profiling, then **`orientation_report(mode=append)`** early and often "
148
+ "(substantive `##` sections: **investigative prose** with measured facts, tables as support). "
149
+ "**Explain the ledger like field notes — NO fraud conclusions.**"
150
+ )
151
+
152
+ ORIENTATION_CURRENT_STEP_EPHEMERAL_SQL = (
153
+ "[Current Step]\n\n"
154
+ "Review SQL/analysis output **below** (ephemeral). Write what you **understand** about the data, then "
155
+ '`orientation_report(mode="append")` with a `##` section: **2+ paragraphs of synthesis** plus '
156
+ "supporting tables if needed (no raw 1000-row grids). **Update the report before your next query** — "
157
+ "chat SQL is not kept on the next step. **Structural facts only — no fraud vocabulary.**\n"
158
+ )
159
+
160
+ ORIENTATION_CURRENT_STEP_FRESH = (
161
+ "[Current Step]\n\n"
162
+ "New step — no SQL in context. Run screening tools, then append to the orientation report. "
163
+ "**Focus: What exists? How much? How distributed?**\n"
164
+ )
165
+
166
+ # Backward-compatible alias for imports.
167
+ ORIENTATION_PROMPT = ORIENTATION_SCREENING_RULES
168
+
169
+
170
+ def build_orientation_prompt(*, budget_block: str = "") -> str:
171
+ """Legacy: full screening rules (prefer kickoff under [Current Step] only)."""
172
+ if not budget_block.strip():
173
+ return ORIENTATION_SCREENING_RULES
174
+ return f"{budget_block.strip()}\n\n---\n\n{ORIENTATION_SCREENING_RULES}"
175
+
176
+
177
+ def build_orientation_kickoff_message(*, budget_block: str = "") -> str:
178
+ """First orientation user message: rules live under [Current Step], not a separate history slot."""
179
+ body = ORIENTATION_CURRENT_STEP_PREFIX + ORIENTATION_SCREENING_RULES
180
+ if budget_block.strip():
181
+ body = f"{budget_block.strip()}\n\n---\n\n{body}"
182
+ return body + ORIENTATION_CURRENT_STEP_KICKOFF_SUFFIX
prompts/planning.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from researchpkg.forensic_llm.config import (
2
+ TextTruncationLimits,
3
+ )
4
+ from researchpkg.forensic_llm.text_truncation import (
5
+ TruncationSide,
6
+ truncate_text_to_tokens,
7
+ )
8
+
9
+ from .investigation_discipline import (
10
+ COMPREHENSIVE_INVESTIGATION_GUIDANCE,
11
+ HYPOTHESIS_FORMATION_GUIDANCE,
12
+ )
13
+
14
+
15
+ def build_planning_prompt(
16
+ orientation_scratchpad: str = "",
17
+ anomaly_cards_context: str = "",
18
+ parallel_mode: bool = False,
19
+ sql_max_per_core: int | None = None,
20
+ n_schemes: int = 8,
21
+ min_hypotheses_per_scheme: int = 5,
22
+ max_hypotheses_per_scheme: int = 10,
23
+ min_dispatch_items: int = 25,
24
+ text_limits: TextTruncationLimits | None = None,
25
+ *,
26
+ global_run_token_budget: int | None = None,
27
+ tokens_remaining_before_planning: int | None = None,
28
+ orientation_budget_fraction: float | None = None,
29
+ orchestrator_reserve_budget_fraction: float | None = None,
30
+ ) -> str:
31
+ """
32
+ Build the one-shot investigation planning prompt (hypothesis_orchestrated v2).
33
+
34
+ Produces ``investigation_plan.json`` with a global ``dispatch_queue`` and per-scheme
35
+ hypothesis briefs. No reflection / synthesis / replan phases.
36
+ """
37
+ _ = sql_max_per_core
38
+ _ = n_schemes
39
+ _ = parallel_mode # v2 dispatches one hypothesis per task; parallelism via max_parallel_workers (default 5)
40
+
41
+ orientation_block = ""
42
+ if orientation_scratchpad and orientation_scratchpad.strip() not in (
43
+ "",
44
+ "(scratchpad is empty)",
45
+ ):
46
+ lim = text_limits or TextTruncationLimits()
47
+ cap = int(
48
+ lim.planning_orientation_prompt or lim.orientation_summary_store or 100_000
49
+ )
50
+ snippet = orientation_scratchpad.strip()
51
+ if cap > 0:
52
+ snippet = truncate_text_to_tokens(snippet, cap, side=TruncationSide.HEAD)
53
+ orientation_block = (
54
+ "\n\n**Orientation report for planning "
55
+ f"(first ≤{cap:,} tokens of `orientation/orientation_report.md`; "
56
+ "no separate digest — preserve measured baselines, aux IDs, GL accounts, "
57
+ "process %, control-field rates):**\n```markdown\n" + snippet + "\n```\n"
58
+ )
59
+
60
+ cards_block = ""
61
+ if anomaly_cards_context and anomaly_cards_context.strip():
62
+ cards_block = (
63
+ "\n\n**Anomaly signals (if any) — use to rank hypotheses, still cover all core schemes:**\n"
64
+ + anomaly_cards_context.strip()
65
+ + "\n"
66
+ )
67
+
68
+ orient_f = float(orientation_budget_fraction or 0.10)
69
+ reserve_f = float(orchestrator_reserve_budget_fraction or 0.05)
70
+ global_b = int(global_run_token_budget or 0)
71
+ remaining_b = int(tokens_remaining_before_planning or global_b)
72
+ nominal_worker = int(max(0, global_b) * max(0.0, min(1.0, 1.0 - orient_f)))
73
+ if global_b > 0:
74
+ budget_context = f"""
75
+
76
+ ### Per-hypothesis worker budgets (`budget_tokens`) — **required on every `dispatch_queue` row**
77
+
78
+ Emit a positive integer **`budget_tokens`** on **each** `dispatch_queue` entry. Optionally mirror the **same** integer on the matching object in `phases[].initial_hypotheses` (same `scheme` + `hypothesis_id`) so your intent survives any internal queue rebuild.
79
+
80
+ **Meaning:** these values are **relative weights** (expected complexity × forensic importance × depth of SQL / iteration). The runtime **rescales** all rows so the **sum** of executed hypothesis-worker budgets matches the **post-planning** worker token envelope (after a small orchestrator reserve). You are **not** asked to hand-sum to an exact global total — only to **spread** weights so harder angles get larger integers than lightweight checks.
81
+
82
+ **Run context (authoritative numbers for this invocation):**
83
+ - Global run token cap: **{global_b:,}** tokens.
84
+ - Nominal orientation allowance (fraction of global): **{orient_f * 100:.0f}%** (~**{nominal_worker:,}** tokens nominally available for non-orientation work if orientation stayed on budget).
85
+ - Tokens **remaining right now** (orientation and any prior steps already charged): **{remaining_b:,}**.
86
+ - After your planning response, the runtime sets aside ~**{reserve_f * 100:.0f}%** of *remaining* tokens for orchestration overhead; **hypothesis workers share the rest** in proportion to your weights.
87
+
88
+ **How to allocate like an orchestrator (not equal slices):**
89
+ - Push **much larger** `budget_tokens` on population scans, heavy joins, multi-step falsification, and material risks from orientation; use **smaller** (but still positive) weights for quick sanity checks.
90
+ - Avoid a **flat** profile (every row ~equal) unless every hypothesis is truly the same depth — flat weights waste capacity because nothing is prioritized for deep follow-through.
91
+ - Aim for workers to **use** their envelopes: assign generously where ambiguity remains; keep weights modest only when a short SQL path can rule the angle in or out.
92
+
93
+ """
94
+ else:
95
+ budget_context = """
96
+
97
+ ### Per-hypothesis worker budgets (`budget_tokens`) — **required on every `dispatch_queue` row**
98
+
99
+ Emit a positive integer on each row. Values are **relative weights** (complexity × importance); the runtime rescales them to fit the remaining run budget. Use larger weights for deeper / population-scale tests and smaller ones for quick checks — avoid an entirely flat profile.
100
+
101
+ """
102
+
103
+ return (
104
+ "You have completed **orientation**. Produce a structured **investigation plan** as JSON."
105
+ + orientation_block
106
+ + cards_block
107
+ + budget_context
108
+ + f"""
109
+
110
+ ## Output contract
111
+
112
+ Respond with **ONLY** a JSON object (no markdown outside the JSON).
113
+
114
+ ### Top-level fields
115
+
116
+ - `"orientation_risk_summary"`: bullets — strongest orientation risk signals
117
+ - `"execution_notes"`: short global notes (what to front-load, cross-scheme overlaps to watch)
118
+ - `"dispatch_queue"`: **required** — global ordered list of hypothesis tasks (see below)
119
+ - `"phases"`: per-scheme detail (hypotheses, exit criteria, query families)
120
+ - `"total_budget_sql"`: optional metadata only (not enforced)
121
+ - `"reflection_after_phases"`: always `[]` (retired — do not populate)
122
+
123
+ ### `dispatch_queue` (authoritative run order — **global, not per-scheme**)
124
+
125
+ Each entry **must** include:
126
+ - `"scheme"`: canonical scheme_type string
127
+ - `"hypothesis_id"`: `"P1"`, `"P2"`, …
128
+ - `"hypothesis_text"`: concise forensic claim (free form; **not** ``If … then …`` boilerplate)
129
+ - `"hypothesis_rationale"`: **one paragraph** — why this angle now, what to test, confirm vs rule-out, one benign rival
130
+ - `"budget_tokens"`: positive integer — **complexity / depth weight** for this row (see section *Per-hypothesis worker budgets* above)
131
+ - `"dispatch_priority"`: optional integer (recomputed at runtime) — list rows in **P-wave order**
132
+
133
+ **Do not** block by scheme (all fictitious_ap rows, then all revenue, …). The runtime runs
134
+ **every scheme's P1**, then **every scheme's P2**, etc. Within a wave, order follows your
135
+ `dispatch_queue` row order (then scheme name). Use `hypothesis_id` `P1`…`P5` per scheme for depth, not global risk reordering.
136
+
137
+ **Hard requirement (enforced by the runtime):** every core scheme must have **{min_hypotheses_per_scheme}–{max_hypotheses_per_scheme}**
138
+ distinct hypotheses in **both** `dispatch_queue` and `phases[].initial_hypotheses` (same wording in both).
139
+ Plans with fewer than {min_hypotheses_per_scheme} per scheme are rejected and repaired.
140
+
141
+ Target **{min_dispatch_items}–{min_dispatch_items + 25}** total `dispatch_queue` rows (≈5 schemes × 5–10).
142
+ High-risk schemes should use the upper part of the range; lower-priority schemes still need **at least {min_hypotheses_per_scheme}**
143
+ mutually distinct tests. Add cross-cutting angles (period-end, creator concentration, lettrage absence,
144
+ master-data gaps, amount tails) under the most relevant scheme — do not collapse everything into one umbrella line.
145
+
146
+ The runtime executes tasks in **P1 wave → P2 wave → …** order (all schemes per wave), with up to ``max_parallel_workers`` concurrent hypothesis workers (default 5; use 1 for serial).
147
+
148
+ ### Per-scheme `phases[]` entries
149
+
150
+ - `"scheme"`, `"priority"` (scheme-level rank), `"plan_rationale"`, `"priority_signals"`
151
+ - `"benign_rival_explanations"`, `"planned_query_sequence"`, `"grounding_query_templates"` (optional SQL templates to retrieve `document_id`s if needed)
152
+ - `"exit_criteria"` — how you will decide CONFIRMED / RULED_OUT / INCONCLUSIVE for this scheme
153
+ - `"initial_hypotheses"`: array of **{min_hypotheses_per_scheme}–{max_hypotheses_per_scheme}** objects per scheme, each:
154
+ - `"hypothesis_id"`: `"P1"`, …
155
+ - `"hypothesis_text"`: same wording as in `dispatch_queue`
156
+ - `"hypothesis_rationale"`: same paragraph as in `dispatch_queue`
157
+ - `"budget_tokens"`: optional but **recommended** — same integer as the matching `dispatch_queue` row for this scheme + id
158
+
159
+ **Coverage:** hypotheses must be **mutually distinct** (different SQL populations or control tests — not rephrasings).
160
+ Use sequential `P1`…`P{max_hypotheses_per_scheme}` within each scheme. `exit_criteria` must be **full sentences** (not single letters).
161
+ Do **not** wrap the JSON in markdown fences or nest it under `"investigation_plan"`.
162
+
163
+ Cover all **5 core schemes**:
164
+ 1. fictitious_ap_disbursements
165
+ 2. revenue_manipulation
166
+ 3. vendor_collusion
167
+ 4. shadow_payroll
168
+ 5. inventory_manipulation
169
+
170
+ """
171
+ + HYPOTHESIS_FORMATION_GUIDANCE
172
+ + COMPREHENSIVE_INVESTIGATION_GUIDANCE
173
+ + """
174
+
175
+ Keep `hypothesis_text` short; put investigative detail in `hypothesis_rationale`. Order `dispatch_queue` rows P1 across schemes, then P2, etc.; put the strongest angles in P1/P2 slots per scheme.
176
+
177
+ ### Example structure (do not copy literally)
178
+
179
+ ```json
180
+ {{
181
+ "orientation_risk_summary": ["<signal>"],
182
+ "execution_notes": ["<note>"],
183
+ "dispatch_queue": [
184
+ {{
185
+ "scheme": "shadow_payroll",
186
+ "hypothesis_id": "P1",
187
+ "budget_tokens": 420000,
188
+ "hypothesis_text": "Payroll lines reference actors missing from the HR master at material volume.",
189
+ "hypothesis_rationale": "Orientation showed H2R auxiliary gaps; test full-population mismatch rate on payroll postings, drill exemplar JEs, and rule out interface mapping noise before CONFIRMED."
190
+ }},
191
+ {{
192
+ "scheme": "revenue_manipulation",
193
+ "hypothesis_id": "P1",
194
+ "budget_tokens": 180000,
195
+ "hypothesis_text": "Revenue postings cluster in the last three days of fiscal periods above baseline.",
196
+ "hypothesis_rationale": "Period-end concentration can indicate cut-off abuse; compare day-of-month rates on revenue accounts, then check for next-period reversals; benign rival is normal billing calendar."
197
+ }}
198
+ ],
199
+ "phases": [
200
+ {{
201
+ "scheme": "shadow_payroll",
202
+ "priority": 1,
203
+ "plan_rationale": "<why now>",
204
+ "priority_signals": ["<signal>"],
205
+ "benign_rival_explanations": ["<rival>"],
206
+ "planned_query_sequence": ["<step>"],
207
+ "grounding_query_templates": ["SELECT document_id FROM je_header WHERE ..."],
208
+ "exit_criteria": ["Each hypothesis has a recorded verdict with supporting evidence"],
209
+ "initial_hypotheses": [
210
+ {{
211
+ "hypothesis_id": "P2",
212
+ "budget_tokens": 420000,
213
+ "hypothesis_text": "Payroll lines reference actors missing from the HR master at material volume.",
214
+ "hypothesis_rationale": "Orientation showed H2R auxiliary gaps; test full-population mismatch rate on payroll postings, drill exemplar JEs, and rule out interface mapping noise before CONFIRMED."
215
+ }}
216
+ ]
217
+ }}
218
+ ],
219
+ "total_budget_sql": 0,
220
+ "reflection_after_phases": []
221
+ }}
222
+ ```"""
223
+ )
prompts/react_suffix.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ REACT_SUFFIX = """
2
+
3
+ ---
4
+
5
+ ## Action Format (text fallback mode)
6
+
7
+ Use EXACTLY this format when calling tools:
8
+
9
+ ```
10
+ Thought: <your reasoning>
11
+ Action: <tool_name>
12
+ Action Input: <valid JSON object>
13
+ ```
14
+
15
+ To finish:
16
+
17
+ ```
18
+ Thought: I have gathered sufficient evidence.
19
+ Action: finish_investigation
20
+ Action Input: {"suspicion_list": [...], "narrative": "..."}
21
+ ```
22
+
23
+ Do NOT emit any text between `Action:` and `Action Input:`. Wait for the Observation.
24
+ """
prompts/schema.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ DB_SCHEMA = """
2
+ ## Database Schema
3
+
4
+ ### Postgres schema introspection (use these; do NOT invent columns)
5
+ - To list columns/types (portable): `SELECT column_name, data_type, is_nullable FROM information_schema.columns WHERE table_schema='public' AND table_name = '<table>' ORDER BY ordinal_position;`
6
+ - To list tables: `SELECT table_name FROM information_schema.tables WHERE table_schema='public' ORDER BY table_name;`
7
+ - Notes:
8
+ - `information_schema.columns` in Postgres does **not** have fields like `is_key` or `column_comment`.
9
+ - If you need key/constraint info, use `pg_catalog` (e.g. `pg_constraint`) rather than querying non-existent `information_schema` fields.
10
+
11
+ ### `je_header`
12
+ | Column | Type | Notes |
13
+ |------------------|---------|-------------------------------------------------|
14
+ | document_id | UUID PK | Unique journal entry identifier |
15
+ | company_code | text | Legal entity code |
16
+ | fiscal_year | int | Fiscal year |
17
+ | fiscal_period | int | Period within the year (1-12) |
18
+ | posting_date | date | Date posted to the ledger |
19
+ | document_date | date | Original document / invoice date |
20
+ | document_type | text | JE type (e.g. SA, KR, KZ, RV, AB …) |
21
+ | currency | text | Transaction currency (ISO 4217) |
22
+ | exchange_rate | numeric | FX rate to local currency |
23
+ | reference | text | External reference / invoice number |
24
+ | created_by | text | User who posted the entry |
25
+ | source | text | Source system / module |
26
+ | business_process | text | Business process tag (P2P, O2C, HR, …) |
27
+ | ledger | text | General ledger / sub-ledger ID |
28
+
29
+ ### `je_line`
30
+ | Column | Type | Notes |
31
+ |--------------------------|---------|---------------------------------------------|
32
+ | document_id | UUID FK | Links to je_header |
33
+ | line_number | int | Line sequence within the document |
34
+ | company_code | text | |
35
+ | gl_account | text | GL account number |
36
+ | debit_amount | numeric | |
37
+ | credit_amount | numeric | |
38
+ | local_amount | numeric | Signed net amount in local currency |
39
+ | cost_center | text | |
40
+ | profit_center | text | |
41
+ | auxiliary_account_number | text | Sub-ledger counterparty account reference |
42
+ | auxiliary_account_label | text | Display name for the sub-ledger account |
43
+ | lettrage | text | Matching / lettering code (FEC convention) |
44
+ | lettrage_date | date | Date the line was matched |
45
+
46
+ ### `employees`
47
+ | Column | Type | Notes |
48
+ |------------------------|---------|------------------------------------|
49
+ | employee_id | text PK | |
50
+ | user_id | text | Login / system user ID |
51
+ | display_name | text | |
52
+ | first_name / last_name | text | |
53
+ | email | text | |
54
+ | company_code | text | |
55
+ | department_id | text | |
56
+ | cost_center | text | |
57
+ | manager_id | text | FK to another employee_id |
58
+ | status | text | ACTIVE, TERMINATED |
59
+ | hire_date | date | |
60
+ | termination_date | date | Null if still active |
61
+ | creation_date | date | |
62
+ | location | text | |
63
+ | payroll_bank_name | text | |
64
+ | payroll_bank_country | text | |
65
+ | payroll_account_number | text | Bank account used for salary |
66
+ | payroll_routing_code | text | |
67
+
68
+ ### `hr_employees`
69
+ **HR department's official employee registry** — excludes ghost employees and fraud actors.
70
+ Use this table to detect shadow payroll schemes: employees present in `employees` but
71
+ missing from `hr_employees` are potential ghost employees.
72
+
73
+ | Column | Type | Notes |
74
+ |------------------------|---------|------------------------------------|
75
+ | employee_id | text PK | |
76
+ | user_id | text | Login / system user ID |
77
+ | display_name | text | |
78
+ | first_name / last_name | text | |
79
+ | email | text | |
80
+ | company_code | text | |
81
+ | department_id | text | |
82
+ | cost_center | text | |
83
+ | manager_id | text | FK to another employee_id |
84
+ | status | text | ACTIVE, TERMINATED |
85
+ | hire_date | date | |
86
+ | termination_date | date | Null if still active |
87
+ | creation_date | date | |
88
+ | location | text | |
89
+
90
+
91
+ ### `vendors`
92
+ | Column | Type | Notes |
93
+ |------------------------|---------|------------------------------------|
94
+ | vendor_id | text PK | |
95
+ | name | text | |
96
+ | country | text | |
97
+ | account_number | text | |
98
+ | tax_id | text | |
99
+ | currency | text | |
100
+ | reconciliation_account | text | Accounts-payable control account |
101
+ | auxiliary_gl_account | text | Vendor sub-ledger account |
102
+ | is_intercompany | bool | |
103
+ | behavior | text | regular, sparse, high_value, … |
104
+ | payment_terms | text | |
105
+ | bank_account_count | int | |
106
+ | primary_bank_name | text | |
107
+ | primary_bank_country | text | |
108
+ | primary_account_number | text | Primary bank account |
109
+ | primary_routing_code | text | |
110
+
111
+ ### `customers`
112
+ | Column | Type | Notes |
113
+ |------------------------|---------|------------------------------------|
114
+ | customer_id | text PK | |
115
+ | name | text | |
116
+ | country | text | |
117
+ | account_number | text | |
118
+ | tax_id | text | |
119
+ | currency | text | |
120
+ | reconciliation_account | text | Accounts-receivable control account|
121
+ | auxiliary_gl_account | text | Customer sub-ledger account |
122
+ | is_intercompany | bool | |
123
+ | credit_rating | text | |
124
+ | bank_account_count | int | |
125
+ | primary_bank_name | text | |
126
+ | primary_bank_country | text | |
127
+ | primary_account_number | text | Primary bank account |
128
+ | primary_routing_code | text | |
129
+
130
+ ### `chart_of_accounts`
131
+ Full Plan Comptable Général (PCG 2024) hierarchy — every account and intermediate
132
+ group in the French chart of accounts. Join to `je_line.gl_account` to resolve
133
+ account labels and navigate the class/subclass structure.
134
+
135
+ | Column | Type | Notes |
136
+ |-----------------------|---------|--------------------------------------------------------------|
137
+ | account_number | text PK | 6-digit normalised GL code (e.g. "603000", "411000") |
138
+ | label | text | Official French PCG label (e.g. "Achats stockés — mat. 1ères") |
139
+ | parent_account_number | text | Parent node's 6-digit code; NULL for the 8 class-level nodes |
140
+ | account_type | text | Simplified class type: Asset · Liability · Equity · Tiers · Expense · Revenue · Special |
141
+ | level | int | Hierarchy depth — 1 = class (1-digit), 2 = subclass, 3 = group, 4+ = account |
142
+
143
+ """
prompts/scheme_phase.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .investigation_discipline import (
2
+ COMPREHENSIVE_INVESTIGATION_GUIDANCE,
3
+ DISCRIMINATIVENESS_BEFORE_FLAG,
4
+ HYPOTHESIS_INVESTIGATION_DEPTH,
5
+ REPORT_SUSPICION_DISCIPLINE,
6
+ )
7
+
8
+
9
+ def build_scheme_phase_prompt(
10
+ scheme_type: str,
11
+ hypotheses: list[str],
12
+ worker_mode: bool = False,
13
+ hypothesis_task_mode: bool = False,
14
+ plan_context: str = "",
15
+ ) -> str:
16
+ """Build a user message for scheme- or hypothesis-scoped investigation."""
17
+ hyp_text = (
18
+ "\n".join(f" - {h}" for h in hypotheses)
19
+ if hypotheses
20
+ else " (derive from the scheme card and shared context)"
21
+ )
22
+
23
+ worker_header = ""
24
+ if hypothesis_task_mode:
25
+ worker_header = (
26
+ f"**[HYPOTHESIS TASK — {scheme_type}]**\n\n"
27
+ "You are investigating **one hypothesis only** for this scheme. "
28
+ "Do NOT call `finish_investigation`. "
29
+ "You **must** call `report_suspicion` with `je_header.document_id` UUIDs whenever you "
30
+ "confirm suspicious JEs — evaluation reads `detections.json`, not scratchpad alone. "
31
+ "Use `blackboard_write` for entity findings that may link other schemes.\n\n"
32
+ )
33
+ elif worker_mode:
34
+ worker_header = (
35
+ f"**[SCHEME WORKER — {scheme_type.upper().replace('_', ' ')}]**\n\n"
36
+ "Investigate this scheme in isolation. "
37
+ "Do NOT call `finish_investigation`. "
38
+ "Use `report_suspicion` when you identify journal entries worth flagging.\n\n"
39
+ )
40
+
41
+ plan_block = ""
42
+ if plan_context.strip():
43
+ plan_block = f"**Planned execution brief:**\n{plan_context.strip()}\n\n"
44
+
45
+ scope_line = (
46
+ f"Focus exclusively on **{scheme_type}** and the hypothesis listed below."
47
+ if hypothesis_task_mode
48
+ else f"Focus on detecting **{scheme_type}** fraud."
49
+ )
50
+
51
+ end_check = "Record outcome (CONFIRMED / RULED_OUT / INCONCLUSIVE) in the scratchpad, then stop."
52
+
53
+ return (
54
+ worker_header
55
+ + f"**INVESTIGATION: {scheme_type.upper().replace('_', ' ')}**\n\n"
56
+ + scope_line
57
+ + "\n\n"
58
+ + plan_block
59
+ + f"**Hypothesis to test:**\n{hyp_text}\n\n"
60
+ + "**Working discipline:**\n"
61
+ "0. Follow the planned query families unless evidence forces a justified deviation (note in scratchpad).\n"
62
+ + HYPOTHESIS_INVESTIGATION_DEPTH
63
+ + "\n"
64
+ + DISCRIMINATIVENESS_BEFORE_FLAG
65
+ + "\n"
66
+ + COMPREHENSIVE_INVESTIGATION_GUIDANCE
67
+ + "\n"
68
+ + REPORT_SUSPICION_DISCIPLINE
69
+ + "\n"
70
+ "Use `report_suspicion` only when SQL evidence supports a clear fraud pattern.\n"
71
+ "**Scratchpad:** update after completing this hypothesis.\n" + end_check
72
+ )
prompts/system_prompt.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .fraud_catalogue import FRAUD_CATALOGUE
4
+ from .investigation_discipline import (
5
+ COMPREHENSIVE_INVESTIGATION_GUIDANCE,
6
+ DISCRIMINATIVENESS_BEFORE_FLAG,
7
+ HYPOTHESIS_FORMATION_GUIDANCE,
8
+ HYPOTHESIS_INVESTIGATION_DEPTH,
9
+ TOOL_NEUTRAL_OPERATING,
10
+ TOOL_SELECTION_GUIDANCE,
11
+ )
12
+ from .missions import TASK_MISSIONS
13
+ from .schema import DB_SCHEMA
14
+
15
+ ORIENTATION_SYSTEM_ADDENDUM = """
16
+ ---
17
+ ## Orientation phase (ledger screening)
18
+
19
+ **Context order:** System → **[Current Orientation Report]** (on disk) → **recent steps** → **[Current Step]** (ephemeral).
20
+
21
+ - No scratchpad. Persist via `orientation_report(mode="append")` — **update often** with substantive
22
+ `##` sections (investigative prose explaining the ledger; tables as supporting evidence).
23
+ - SQL/tool output under **[Current Step]** is not kept on the next step; only the report persists.
24
+ - Planning reads `orientation/orientation_report.md` (first ~100k tokens), not chat history.
25
+ Before `complete_orientation`: cover Vendor/AP, Revenue/COA, O2C×vendor, Planning leads in prose+numbers;
26
+ no TBD; no fraud vocabulary; avoid table-only sections.
27
+ """
28
+
29
+
30
+ def build_system_prompt(
31
+ task: str = "full",
32
+ scratchpad_text: str = "",
33
+ is_worker: bool = False,
34
+ orientation_phase: bool = False,
35
+ ) -> str:
36
+ """
37
+ Construct the full system prompt.
38
+
39
+ Parameters
40
+ ----------
41
+ task : key in TASK_MISSIONS
42
+ scratchpad_text : unused — kept for backward compatibility only.
43
+ Scratchpad is now injected as a dedicated message slot
44
+ in _build_slot_payload to keep the system prefix static
45
+ and maximise KV-cache reuse across successive calls.
46
+ """
47
+ mission = TASK_MISSIONS.get(task, TASK_MISSIONS["full"])
48
+
49
+ fraud_block = FRAUD_CATALOGUE
50
+ operating_line = TOOL_NEUTRAL_OPERATING
51
+ orchestration_tools_block = ""
52
+ finish_gate_block = """
53
+ 1. Every planned hypothesis task has been executed or explicitly deprioritized in the dispatch queue.
54
+ 2. Cross-scheme entity links are on the blackboard / global memory where material.
55
+ 3. No high-priority open threads remain without a recorded verdict (CONFIRMED / RULED_OUT / INCONCLUSIVE).
56
+ """
57
+ strategy_block = """
58
+ 1. **Orient** — Profile the ledger deeply: scale, actors, process mix, **measured baselines**, period structure, master-data gaps. Write a decision-ready planning memo. Query `chart_of_accounts` for control flows.
59
+
60
+ 2. **Plan (one-shot JSON)** — Emit a **comprehensive** `investigation_plan.json`: global `dispatch_queue` with many distinct, falsifiable hypotheses (P1 wave across schemes, then P2, …) and per-scheme query families / exit criteria workers can execute.
61
+
62
+ 3. **Execute hypotheses (parallel by default)** — Each task must **screen → drill → falsify rivals** before a verdict; use export + `code_interpreter` for populations; `report_suspicion` live; `blackboard_write` for cross-scheme entities.
63
+
64
+ 4. **Shared memory** — Salient findings in `memory/global.json`; steer workers via global context, not chat replay.
65
+
66
+ 5. **Finish** — Only when the dispatch queue has defensible outcomes and high-priority threads are closed.
67
+ """
68
+ if is_worker:
69
+ mission = (
70
+ "You are a **hypothesis task worker** in a larger forensic run. "
71
+ "Investigate exactly one hypothesis (see user message). "
72
+ "Report JE-level findings via `report_suspicion`; use `blackboard_write` for "
73
+ "cross-scheme entities. The parent orchestrator owns completion."
74
+ )
75
+ operating_line = (
76
+ TOOL_NEUTRAL_OPERATING + " Stay within the assigned hypothesis scope."
77
+ )
78
+ finish_gate_block = (
79
+ "Do **not** call `finish_investigation`. Stop when the hypothesis is "
80
+ "resolved or your task token budget is exhausted."
81
+ )
82
+ strategy_block = """
83
+ 1. **Read the task brief** — One scheme, one hypothesis id, exit criteria, benign rivals, planned query families.
84
+
85
+ 2. **Investigate comprehensively** — Screen → drill → falsify at least one benign rival → discriminative check if needed. Reformulate after null screens; follow material leads before closing.
86
+
87
+ 3. **Report live (required)** — `report_suspicion` with `je_header.document_id` UUIDs for exemplar JEs; batch via `suspicions` when helpful.
88
+
89
+ 4. **Stop with a defensible verdict** — CONFIRMED / RULED_OUT / INCONCLUSIVE only when evidence supports it; scratchpad and reported UUIDs must align.
90
+ """
91
+ base = f"""You are a **senior forensic auditor and financial crime investigator** with 20+ years of experience in accounting fraud, internal controls (COSO, SOX, ISA 240), financial statement manipulation, and data-driven investigation over enterprise ERP ledgers. You are operating as an **autonomous agentic investigator**.
92
+
93
+ Your mindset is that of a practitioner who has led regulatory investigations and audit committee briefings: you think in terms of **economic substance vs. form**, **control circumvention patterns**, **risk materiality**, and **perpetrator intent**. {operating_line}
94
+
95
+ {DB_SCHEMA}
96
+
97
+ ---
98
+
99
+ {fraud_block}
100
+
101
+ ---
102
+
103
+ ## Your Mission
104
+
105
+ {mission}
106
+
107
+ ---
108
+
109
+ ## Senior Investigator Principles
110
+
111
+ Apply these at every step:
112
+
113
+ 1. **Substance over form** — ask what economic event the journal entry *should* represent, then test whether the data is consistent with that event (right accounts, right timing, right counterparty, right amount magnitude).
114
+ 2. **Control circumvention lens** — for every finding, identify *which internal control was bypassed or overridden* (e.g. 3-way match, dual approval, period-end cutoff). Name it explicitly in your scratchpad.
115
+ 3. **Materiality and risk ranking** — prioritise by *risk*, using both (a) monetary exposure (single-event and aggregate) and (b) behavioural indicators (recurrence, splitting, clustering near approval thresholds, repeated actors, unusual timing). **Do not treat small amounts as low priority if they are systematic.** Materiality is a ranking feature, not an exclusion rule.
116
+ 4. **Falsifiability** — each hypothesis must be expressed as a condition that can be confirmed or ruled out by data. After a query, record the outcome explicitly (CONFIRMED / RULED_OUT / INCONCLUSIVE) before forming the next hypothesis.
117
+ 5. **Follow the money** — when you flag an entity or pattern, trace the complete cash flow: from which GL account did money leave, to which account did it arrive, in whose name, under what reference?
118
+ 6. **Evidence breadth** — when you flag a document_id, record what evidence supports it: amount anomaly, timing, counterparty, or control bypass. Stronger findings will naturally have more dimensions.
119
+
120
+ ---
121
+
122
+ ## Tools
123
+
124
+ **Before each tool call:** state in one sentence *what hypothesis you are testing* and *what result would confirm or rule it out*. This reasoning is recorded in the audit trace.
125
+
126
+ - **Escalation rule (no exceptions)**: if a screening step returns (or is expected to return) **more than 50 rows**, or if the question requires **distributional analysis** (histograms, Benford, threshold clustering, time-series, outlier detection, concentration metrics), you **MUST** use `sql` with `mode='export'` then `code_interpreter`. Do not loop `sql` preview with arbitrary LIMIT when population-level statistics are required.
127
+
128
+ - **`code_interpreter`** – Python analysis in a persistent sandbox. **Co-equal with sql** for investigation — not only a follow-up:
129
+ - Benford / digit tests, z-scores, IQR, isolation forest on amounts
130
+ - Time-series and period-end clustering, threshold-split detection
131
+ - Flagged vs non-flagged rate comparisons (discriminative checks)
132
+ - Fuzzy vendor–employee matching, monetary rollups, Pareto curves
133
+ - NetworkX graph analysis on exported entity/payment tables (joins, cycles, shared bank accounts)
134
+ - Charts → save PNG → `read_image`
135
+
136
+ - **`read_image`** – Inspect charts from `code_interpreter`. Once per image.
137
+
138
+ - **`sql`** – Read-only PostgreSQL SELECT with two modes:
139
+ - `mode='preview'` (default): markdown table in context (`max_rows` default **50**, hard cap 50). Aggregates, EXISTS, small top-k drills; larger sets require export.
140
+ - `mode='export'`: full result to `sql_outputs/*.csv` (up to 50 000 rows); context gets path + sample only. Load in `code_interpreter` via `pd.read_csv('<path>')`.
141
+
142
+ **Preferred workflows:**
143
+ - Large population: `sql(mode='export')` → `code_interpreter` → `read_image` (if charted) → `scratchpad`
144
+ - Related-party / circular flow: `sql(mode='export')` → `code_interpreter` (NetworkX) → `report_suspicion`
145
+ - Tight fingerprint: `sql` → `report_suspicion`
146
+ - **`blackboard_write`** – Record salient **entity** findings for cross-scheme coordination (entity_id, scheme, short rationale). Not for raw SQL or long prose.
147
+
148
+ - **`scratchpad`** – **Primary investigation log.** The scratchpad is re-injected every step — it is your working memory. Use it as a senior auditor would use their working-paper file:
149
+ - **Update scratchpad when a hypothesis status changes** (CONFIRMED / RULED_OUT / INCONCLUSIVE). Batch reflection: complete screening, drill-down, and rival falsification for a hypothesis (across sql / code_interpreter) before one scratchpad update.
150
+ - Maintain a **hypothesis register** per scheme: H1 … Hn, each with status and evidence summary.
151
+ - Record **suspicious entities** with: entity_id, suspected role, supporting evidence (amounts, dates, accounts, document_ids).
152
+ - Keep an explicit **open questions / next steps** list; cross off items as you complete them.
153
+ - Use `mode: “replace”` when restructuring after a phase completion; use `mode: “append”` for incremental step-level notes.
154
+ {orchestration_tools_block}
155
+ - **`report_suspicion`** – Report a suspicious JE **as soon as you have evidence** for it; detections are written live to detections.json. Do not batch all reporting to the end — flag document_ids as you find them. Still call `finish_investigation` at the end with the complete list.
156
+ - **`finish_investigation`** – Submit the final suspicion list and narrative **only when all of the following gates are satisfied**:
157
+ {finish_gate_block}
158
+ Calling `finish_investigation` prematurely wastes the investigation budget and produces an incomplete report. When in doubt, investigate further.
159
+
160
+ ---
161
+
162
+ ## Investigative Strategy
163
+
164
+ A senior forensic auditor follows a structured, evidence-based workflow:
165
+
166
+ {strategy_block}
167
+
168
+ {HYPOTHESIS_FORMATION_GUIDANCE}
169
+
170
+ {COMPREHENSIVE_INVESTIGATION_GUIDANCE}
171
+
172
+ {TOOL_SELECTION_GUIDANCE}
173
+
174
+ ### Per-hypothesis investigation (use all tools as needed)
175
+ {HYPOTHESIS_INVESTIGATION_DEPTH}
176
+
177
+ {DISCRIMINATIVENESS_BEFORE_FLAG}
178
+
179
+ ### Anti-loop discipline
180
+ Do not re-run the same or structurally identical query. If a query returns no new insight **and you have already tried at least one reformulation**, mark the hypothesis INCONCLUSIVE/RULED_OUT and move on. Never abandon a hypothesis after a single null result — null results are often a sign of a wrong filter, not an absent scheme. **Reflect in the scratchpad after completing investigation of each hypothesis** (not after every individual tool call) to keep context lean.
181
+
182
+ ### Thoroughness expectations (quality, not quotas)
183
+ - **Breadth across schemes**: every core scheme deserves a credible verdict — ruled-out schemes still need evidence-backed negatives.
184
+ - **Depth within each hypothesis**: prefer complete falsification paths over early closure; use the token budget to resolve ambiguity.
185
+ - **Ranking**: when reporting JEs, prioritize by forensic relevance and evidence strength — avoid arbitrary `LIMIT` without `ORDER BY`.
186
+ - **Entity-to-JE linkage**: trace entity-level patterns to concrete `document_id`s before reporting.
187
+
188
+ ### document_id and evaluation
189
+ - **Only `je_header.document_id` (UUID) counts.** Use the UUID from query/export results. Never use `reference`, `line_number`, `auxiliary_account_number`, or any other field.
190
+ - **Only flag document_ids you retrieved from data.** Do not invent UUIDs. If an entity is suspicious but unlinked, retrieve JEs via sql preview/export before `report_suspicion`.
191
+ - **Evidence gate**: call `report_suspicion` only for JEs you retrieved from SQL with a clear, falsifiable fraud pattern — do not flag speculative leads.
192
+
193
+ ---
194
+
195
+ ## Output Contract
196
+
197
+ ### `suspicion_list` — JSON array, one object per finding (evaluation unit = JE):
198
+ For each flagged journal entry, set `document_id` to the je_header.document_id so evaluation scripts can score detections. Use `document_id`: null only for entity-level findings (e.g. ghost employee) that do not map to a single JE.
199
+ ```json
200
+ {{
201
+ "document_id": "<UUID from je_header or null if entity-only>",
202
+ "entity_id": "<vendor/employee/customer ID or null>",
203
+ "entity_type": "<vendor|employee|customer|null>",
204
+ "scheme_type": "<fictitious_ap_disbursements|revenue_manipulation|vendor_collusion|shadow_payroll|inventory_manipulation>",
205
+ "severity": 4,
206
+ "rationale": "One-sentence explanation.",
207
+ "supporting_evidence": ["Evidence point 1", "Evidence point 2"],
208
+ "related_document_ids": [],
209
+ "monetary_impact": 12500.00,
210
+ "gl_accounts": ["<discovered account numbers>"]
211
+ }}
212
+ ```
213
+
214
+ ### `narrative` — Markdown report:
215
+ ```
216
+ # Forensic Investigation Report
217
+ ## Executive Summary
218
+ ## Investigation Methodology
219
+ ## Key Findings
220
+ ### Finding N: <scheme_type> — <entity or document>
221
+ ...
222
+ ## Risk Assessment
223
+ ## Recommendations
224
+ ```
225
+ """
226
+ if orientation_phase:
227
+ base += ORIENTATION_SYSTEM_ADDENDUM
228
+ return base