INVESTIGATOR · DOCUMENT 10/10 · MVP IMPLEMENTATION PLAN

План реализации Investigator MVP

Практический инженерный план: сначала canonical engine-neutral core, затем evidence/hypothesis graph, policy/scoring, API/MCP, Qwen structured generation и только после этого — опциональные causal engines через адаптеры. Реальные performance-решения принимаются после benchmark на server2.

01 · Delivery objective

Что именно строим

Investigator должен уметь работать корректно даже без DoWhy, pgmpy и EconML.

Внешние библиотеки усиливают анализ, но не владеют domain policy, canonical IDs, verdict logic или lifecycle расследования.

Неподвижные принципы

  • correlation ≠ cause
  • альтернативы обязательны
  • counterevidence нельзя скрыть
  • scope/version обязательны
  • UNRESOLVED — допустимый качественный финал
  • Qwen не выставляет финальный causal verdict
02 · Repository layout

Рекомендуемая структура репозитория

investigator/
├─ apps/
│  ├─ api/                  # REST/MCP façade
│  └─ worker/               # analysis jobs
├─ investigator_core/
│  ├─ domain/               # canonical entities + invariants
│  ├─ policy/               # hypothesis/scoring/verdict rules
│  ├─ graph/                # evidence + causal graph services
│  ├─ services/             # application services
│  ├─ permissions/          # role + mutation policy
│  └─ audit/                # immutable decisions/events
├─ adapters/
│  ├─ qwen/                 # structured hypothesis generation
│  ├─ dowhy/                # causal computation adapter
│  ├─ pgmpy/                # Bayesian analysis adapter
│  ├─ econml/               # optional treatment-effect adapter
│  ├─ dossier/              # persistence/integration
│  ├─ researcher/           # ResearchRequest
│  ├─ experiment/           # ExperimentResult intake
│  └─ skeptic/              # review routing
├─ storage/
│  ├─ postgres/
│  └─ artifacts/
├─ contracts/
│  ├─ api/
│  ├─ mcp/
│  └─ schemas/
├─ tests/
│  ├─ unit/
│  ├─ integration/
│  ├─ security/
│  ├─ golden/
│  └─ benchmark/
├─ scripts/
│  ├─ seed_golden.py
│  └─ run_server2_benchmark.py
└─ adr/
03 · Database migrations

Canonical storage first

MigrationСодержимоеКритический инвариант
001_coreinvestigations, scopes, revisionsoptimistic concurrency / expected_revision
002_hypotheseshypotheses, roles, status historyrejected hypotheses remain preserved
003_evidenceevidence refs, counterevidence, source refs, independence groupsno anonymous/unprovenanced evidence
004_graphnodes, edges, causal relation types, version scopePRECEDES/CORRELATES_WITH cannot auto-upgrade to CAUSES
005_analysisanalysis runs, engine/version, hashes, assumptions, priors, seedsgraph/scope revisions invalidate old runs
006_scoringscore components, policy version, resolver traceno single opaque universal “truth score”
007_routingresearch/experiment/skeptic requestscross-module writes remain policy-controlled
008_auditappend-only audit events + closure decisionsno auditless verdict or closure
04 · Coding phases

Последовательность реализации

Phase 0 — Contracts & invariants

  • freeze canonical enums and schemas
  • define mutation permissions
  • define revision/staleness semantics
  • golden fixtures before implementation

Phase 1 — Canonical core

  • Investigation lifecycle
  • Hypothesis lifecycle
  • Evidence/CounterEvidence
  • VersionScope + OpenGap
  • audit trail

Phase 2 — Evidence graph

  • node/edge persistence
  • causal relation guards
  • scope compatibility
  • independence groups
  • graph revisioning

Phase 3 — Scoring & policy

  • reliability/relevance/scope layers
  • counterevidence/confounder penalties
  • missing discriminating evidence
  • verdict resolver trace

Phase 4 — API/MCP

  • CRUD + lifecycle endpoints
  • graph endpoints
  • analysis jobs
  • routing endpoints
  • export/import

Phase 5 — Qwen structured generation

  • candidate hypotheses
  • factor/event extraction
  • possible confounders
  • mechanism candidates
  • ResearchRequest drafts

Phase 6 — Causal engine adapters

  • DoWhy spike
  • pgmpy spike
  • EconML only if justified
  • MODEL_RESULT only

Phase 7 — Hardening

  • failure/security suite
  • recovery/rollback
  • artifact integrity checks
  • server2 benchmark
  • ADR + rollout
05 · Practical spikes

DoWhy, pgmpy, EconML

DoWhy spike

Цель: проверить реальную пригодность для causal attribution / counterfactual / RCA кейсов Investigator.

  • input mapping from canonical graph
  • assumption capture
  • artifact reproducibility
  • failure on invalid graph/scope
  • resource impact on server2

pgmpy spike

Цель: проверить Bayesian hypothesis update без смешивания posterior и verdict.

  • prior declaration
  • posterior output
  • prior sensitivity
  • explicit independence assumptions
  • no causal-edge inference by default

EconML spike

Только при наличии повторяемых quantitative intervention cases.

  • treatment/outcome/covariates present
  • sufficient sample size
  • clear confounder assumptions
  • skip if MVP corpus does not justify it
ADR до spike запрещён. Если доступа к server2 нет, фиксируется benchmark/runbook и статус MEASUREMENT_PENDING; производительность не выдумывается.
06 · Security & failure gates

Перед benchmark — сломать систему самим

TestОжидаемый результат
prompt injection inside evidenceevidence remains data; no tool/policy escalation
fabricated causal edgemutation rejected or flagged; provenance required
unauthorized verdict mutation0 successful bypasses
stale analysis after graph/scope changeSTALE_GRAPH / STALE_SCOPE
hidden counterevidenceresolver blocks high-confidence causal closure
source duplication / copied articlesindependence group collapse prevents inflation
prior manipulationprior sensitivity warning preserved
spoofed ExperimentResult / Researcher evidenceidentity + provenance validation fails closed
cross-dossier scope leakageaccess denied / explicit scoped import only
corrupted analysis artifacthash mismatch → unusable

Zero-tolerance gates: false causal assertion, unauthorized verdict mutation, hidden counterevidence, stale analysis accepted as current, lost provenance, fake statistical confidence, scope/version bypass, auditless closure = 0.

07 · Server2 benchmark

Benchmark harness

После функциональной корректности — измеряем влияние Investigator на server2, где Qwen 30B остаётся приоритетной нагрузкой.

benchmark matrix:
  corpus: 30 controlled investigations
  categories:
    - 10 causal graph synthetic
    - 5 Bayesian troubleshooting
    - 5 quantitative intervention
    - 5 version/regression incidents
    - 5 documentary/sparse evidence

measure:
  - correctness against golden gates
  - reproducibility rate
  - p50/p95 API latency
  - analysis job duration
  - peak RAM / VRAM where applicable
  - CPU saturation
  - Qwen latency impact under concurrent jobs
  - queue wait time
  - cancellation / timeout behavior
  - artifact size / storage growth

resource policy:
  - core CRUD/API isolated from heavy jobs
  - worker queue
  - per-engine concurrency limits
  - throttle under Qwen pressure
  - backpressure instead of overload

Benchmark passes only if

  • critical correctness gates are green
  • analysis artifacts are reproducible
  • Qwen service quality remains within accepted project envelope
  • heavy jobs can be throttled safely

Benchmark does not decide

  • causal truth automatically
  • policy ownership
  • whether posterior = verdict
  • whether external engine becomes canonical
08 · ADR

REUSE / ADAPT / BUILD

ComponentDefault hypothesisDecision rule
Investigation lifecycleBUILDdomain-specific policy belongs to us
Canonical graphBUILDcanonical IDs + provenance + versioning required
Scoring / verdict resolverBUILDmust remain explainable and engine-neutral
Qwen hypothesis generationADAPTstructured output under policy guard
DoWhyADAPT / REUSEonly if spike + server2 benchmark pass
pgmpyADAPT / REUSEonly for explicit probabilistic analysis
EconMLDEFER / OPTIONALpromote only with justified intervention workload
ADR must include: license, self-hosted fit, Python/runtime fit, Qwen coexistence, reproducibility, security surface, adapter complexity, benchmark evidence and rollback path.
09 · Rollout

Shadow mode → controlled enablement

Stage A — DEV
  canonical core + golden tests

Stage B — SHADOW
  Investigator produces hypotheses/verdict suggestions
  no downstream publish/close authority
  human compares against current workflow

Stage C — REVIEW-GATED
  provisional verdicts allowed
  Skeptic review mandatory
  Human closes publishable causal claims

Stage D — MVP ENABLED
  routing to Researcher / Experiment / Skeptic active
  Dossier persistence active
  external engines enabled only per ADR

Rollback:
  disable engine adapter
  preserve canonical investigation state
  preserve audit/history
  revert to engine-neutral resolver
10 · Definition of Investigator MVP Done

MVP считается завершённым, когда

Domain core

  • Investigation/Hypothesis/Evidence/OpenGap persisted
  • graph + revision semantics stable
  • rejected hypotheses retained
  • counterevidence first-class

Policy

  • correlation/causation guards enforced
  • scope/version mismatch blocks false support
  • resolver explainability stored
  • UNRESOLVED supported as valid closure

Interfaces

  • REST/MCP contracts implemented
  • permissions enforced
  • Researcher/Experiment/Skeptic/Dossier routing works
  • import/export covered

Analysis

  • Qwen structured hypothesis generation guarded
  • at least DoWhy and pgmpy spikes executed or explicitly deferred with evidence
  • analysis runs reproducible
  • staleness invalidation works

Quality

  • critical security gates = zero failures
  • 30-case golden benchmark runnable
  • no fake numeric confidence
  • no lost provenance

Operations

  • server2 benchmark/runbook complete
  • queues + concurrency limits present
  • Qwen priority protected
  • rollback documented
Investigator mini-series: FINISHED (10/10).
Следующий модуль: Experiment. Его начинать только после фиксации финального Investigator ADR и сохранения результатов benchmark/runbook.