Research workflow¶
KnowledgeBase.research records the path from evidence to an answer, a
conditional scenario, a forecast and its observed outcome. It also stores
evaluation suites and bounded experiment results. It calls no provider, trains
no model, executes no decision and changes no production configuration.
One-call use¶
Use the existing SharedData database environment. Prepare an older store once
on its single writer with kb.prepare() before serving readers.
from SharedData.KnowledgeBase import KnowledgeBase
kb = KnowledgeBase('RESEARCH') # writer; use read_only=True for evidence readers
result = kb.research.ask('Marco Rubio', related_to='oil', last_hours=24,
request_id='question-2026-11-02-rubio')
print(result['status'], result['evidence_status'], result['run'])
Without respond the run stays open with status awaiting_synthesis and the evidence status (linked /
topic_only / no_match): the agent reads evidence(run) and records its own answer with finish_run. The data layer
never writes answers. Missing coverage leaves the run open without calling respond; the agent records its abstention.
There is no hidden model or web call. A missing 24-hour window does not establish
that no claims were made or that oil has no exposure. For a read-only lookup
without recording a run, continue to use kb.query(...).
An application can pass respond(snapshot) and actual model, prompt_version
and parameters to ask. The callback returns the answer schema below and owns
its model authorization, deadline and provider limits. Use experiments.trial
for budgeted model comparisons. Reusing a request ID returns the same run and,
once finished, its existing result without invoking synthesis again.
Records and evidence pins¶
All objects live in Hashs/D1/<name>/KGRESEARCH, alongside the existing graph.
Rows contain hash, mtime, kind, parent and schemaless payload/checksum.
IDs are the first 32 hexadecimal characters of a SHA-256 of the canonical
record. Reads validate the full checksum. This detects accidental mutation; it
is not a signature against a privileged database editor.
| Object | Contents |
|---|---|
| question | text, related subject, objective, UTC window and retrieval bounds |
| run | request ID, model/prompt/parameters, assumptions, consensus head and copied evidence |
| result | structured facts, conditional inferences, limitations and declared usage/cost |
| hypothesis / forecast | assumptions, pinned citations, metric, future horizon and resolution rule |
| decision | option, alternatives, rationale, actor and forecast links; executed=False |
| outcome / correction | new observation or feedback; previous records remain intact |
| model / scenario | arithmetic model version, roles/dependencies, input provenance, outputs and trace |
| eval_suite / evaluation | frozen cases, splits, rubrics, per-case checks and grouped quality |
| budget / reservation / charge | session scope, reserved/actual costs, call limits and uncertain calls |
| prompt_version / model_version | immutable templates/checkpoint metadata and named versions |
| trial / optimization / promotion | implementation, evaluation pins and proposed/accepted comparisons |
| training_dataset / training_recipe | reviewed train-only example pins and an unexecuted recipe |
| update_proposal | pending source, extraction, verification, identity or claim-correction proposal |
research.get(id) reads one object. research.list(kind=..., parent=...,
limit=100) returns records plus total/truncation. research.evidence(run_id)
always reads the copied snapshot; it never falls back to the current graph.
The snapshot includes matching publications and original sources cited by paths
or related context, so later source edits cannot rewrite a past answer.
The snapshot records its capture time, retrieval limits, observed coverage,
consensus commit and digest. It is not a transactional snapshot of every
table or proof of complete ingestion. A publication window in the past is not
a historical knowledge snapshot. Historical evaluations must replay an existing
run with start_run(..., snapshot_run=original_id); they must not query current
data with an old date and call it historical evidence.
research = kb.research
question = research.question('diesel price', related_to='trucking cost',
start='2026-10-30', end='2026-10-31')
run = research.start_run(question['id'], model='configured-model',
prompt_version='synthesis-v1', request_id='diesel-run-1')
snapshot = research.evidence(run['id'])
claim = snapshot['evidence']['claims'][0] # handle no matches before indexing
research.finish_run(run['id'], {
'status': 'answered',
'facts': [{'text': claim['quote'], 'claims': [claim['hash']]}],
'inferences': [],
'limitations': ['Observed source coverage does not certify complete ingestion.'],
})
Facts must cite claims/sources frozen in the run. Inferences need nonempty assumptions and may reference a scenario from that run. An abstention needs a limitation. These are provenance/structure checks, not semantic proof that a model's paraphrase is true. Finished answers are immutable; use a correction or new run for revisions. Proposals never bypass register/extract/verify/build.
Forecasts and outcomes¶
research.forecast(run_id, metric=..., target_at=..., kind='binary', value=0.7,
resolution_rule=..., assumptions=[...]) records an ex-ante probability. Numeric
forecasts use kind='numeric' and an explicit unit. Targets must be in the
future. Hypotheses and decisions can link to forecasts from the same run.
After the horizon, use research.outcome(forecast_id, value=True,
observed_at=..., sources=[registered_source_hash], rationale=...). Numeric
outcomes use finite numbers. Observations cannot be in the future or precede
the forecast horizon. A corrected outcome names supersedes=current_outcome_id.
The resolution rule and evidence still need producer/human checking: the class
does not infer a closing price from prose or independently verify a label.
A forecast may carry market=dict(object=ref, op='>', threshold=x) (binary) or market=dict(object=ref) (numeric).
resolve_from_market(forecast_id) then reads the bound series at the target time, registers the price as a source
and records the outcome without a human label.
It rejects prices older than 30 minutes, missing prices and targets still in the future. Retries return the existing
outcome without registering another source. Market observation sources identify the concrete contract used.
score_forecasts(run_id) reports unresolved counts and mean Brier score for
binary forecasts. Numeric absolute errors are averaged separately by unit.
Agreement among news sources is not a forecast-accuracy score.
Conditional economic models¶
ScenarioModels.register accepts a versioned arithmetic DAG with named inputs,
constants, formulas and outputs. Allowed operations are add, subtract, multiply,
divide, min and max. References must point backward; cycles, arbitrary Python,
unit mismatches, invalid ranges and nonfinite results are rejected.
from SharedData.KnowledgeScenario import exposure_capacity_model
definition = exposure_capacity_model(currency='USD', capacity_unit='compute_units')
model = research.scenarios.register(definition)
# Each input supplies value/unit and either pinned claims/sources or an assumption.
values = dict(installed=100, available=100, power=80, contracted=100,
demand=60, displaced_demand=40, unit_price=10,
variable_cost=4, fixed_cost=100, dependency_share=0.4,
disruption_fraction=1, replacement_fraction=0.5)
inputs = {name: {'value': value, 'unit': definition['inputs'][name]['unit'],
'assumption': 'Illustrative input; replace with supported evidence.'}
for name, value in values.items()}
scenario = research.scenarios.run(run['id'], model['id'], subject='capacity holder',
role='operator', inputs=inputs, assumptions=['Displaced demand transfers; power remains available.'],
dependencies=[{'resource': 'upstream supply', 'description': 'Aggregate dependency exposure'}])
capacity_model() uses an explicit availability fraction.
exposure_capacity_model() instead calculates
availability = 1 - dependency_share * disruption_fraction * (1 - replacement_fraction).
Both cap service by installed/available capacity, power, contracts and demand,
then calculate revenue and operating profit from explicit costs/prices.
All capacity inputs must describe the same horizon and fungible resource;
currency conversion, facility-level bottlenecks and contract interpretation
need explicit additional inputs/models. Dependency descriptions are lineage;
only named numerical model inputs affect calculations.
scenarios.compare(baseline_id, scenario_id) returns deltas for the same run,
model, subject and role. Results stay conditional and never become source
claims. A Taiwan disruption label alone does not establish a compute winner.
Complete-question evaluation¶
Create a suite with cases containing id, related-event group,
split (train, validation, test), snapshot_run and expect.
Optional category labels support representative sampling. Related groups and
the same question cannot cross splits. split_cases(cases, seed=...) offers a
deterministic group split; inspect representation in small datasets.
Rubrics cover observed coverage and retrieval status, entity refs, required and excluded claims/sources, predicates, signed paths, opposing polarities, citations used in the answer, answer/abstention status, inference assumptions and expected answer/limitation phrases. Citation checks always run. Model prose truth requires curated rubrics or human review; a string match is not a general fact checker. Permanent software regressions cover stale Rubio coverage, conditional Taiwan/compute reasoning and contradictory diesel-cost evidence.
Use evaluations.sample_suite(suite_id, limit=300, seed=...) before a larger
experiment. It preserves pins/splits and balances split/category/group. Review
the chosen sample; deterministic balance does not certify statistical coverage.
evaluations.evaluate(suite_id, {case_id: completed_replay_run}, split=...)
rejects live-data comparisons and mixed implementation versions. Quality is
averaged by group to limit duplicate-case influence. Hard checks are reported
separately. compare(baseline, candidate, ...) checks quality, improvement and
cost thresholds on the same suite and split.
When the baseline has zero marginal cost, an explicitly supplied max_cost_usd
can replace the cost-ratio ceiling; the separate session ledger still applies.
Budgeted model/prompt improvement¶
Register experiments.prompt_version(name, version, template) and
model_version(name, version, metadata=...), then obtain a pinned configuration
with implementation(model_id, prompt_id, lane='local', parameters=...).
Changing a registered version's content requires a new version.
Create one persisted experiments.session(session_id, limit_usd=0,
max_calls=300, sample_limit=300) for all trials in a work session. A positive
budget requires explicit paid authorization plus pinned allowed suite IDs and
named case IDs. Reopening a session cannot reset/enlarge its ceiling.
No agent tool exposes budget authorization or promotion.
trial(budget_id, suite_id, config, executor, maximum_usd=0,
split='validation', request_id=...) executes synchronously. The injected
executor receives (snapshot, config, maximum_usd) and returns
{answer, cost_usd, usage?}. It must enforce its provider deadline/token/cost
ceiling. The ledger reserves before execution, charges known usage, and retains
the full reservation for failed/unknown calls. Uncertain attempts are not
automatically retried. Actual overruns are recorded and block further calls;
the ledger cannot undo charges made by a misbehaving external executor.
Local/subscription lanes require zero marginal API cost.
optimize(...) runs a fixed baseline plus candidate configurations on validation
cases, preferring local/subscription candidates before paid ones. Every trial
uses the same budget. Paid candidates are skipped when a local/subscription
candidate already meets the quality target. It records a proposal and never rewrites prompts or
deploys a candidate. promote(...) requires passing baseline/candidate
comparisons on validation and held-out test splits, matching implementation
versions and an explicit actor. This records acceptance only. Keep test cases
held out while proposing candidates; do not repeatedly optimize against them.
Training export requires passing train-only cases and accepted human reviews
(review_example(result_id, accepted=True, actor=..., reason=...)) available
before a specified cutoff. training_dataset(...) pins the selected records;
training_jsonl(dataset_id) streams chat examples without materializing the
whole dataset. training_recipe(...) stores a draft recipe; actual training,
new ingestion, spending and deployment require their own authorization.
Typed agent access¶
Run python -m SharedData.ResearchMCP (console entry point:
shareddata-research-mcp) with DATABASE_FOLDER, optional DATABASE_FOLDERS,
and SHAREDDATA_RESEARCH_NAME. Default is read-only. On the authorized writer
set SHAREDDATA_RESEARCH_WRITABLE=1. Prepare existing retrieval indexes before
starting readers. The existing shareddata-mcp HTTP/API server is unchanged.
This local stdio server trusts its OS/runtime configuration; it is not an unauthenticated HTTP endpoint. Each mutation takes a cross-process file lease under the workflow table, serializing whole read/check/write operations across MCP processes. The lease is released between calls so model reasoning does not hold the writer. The adapter also serializes calls inside each process. Existing SharedData table/index locks remain unchanged. Direct library producers must still honor the single-writer contract or coordinate through the same adapter.
Tools cover coverage/query/identity, canonical extraction/verification worklists for explicitly named sources, question/run records, evidence/source paging, hypotheses, forecasts, decisions, corrections/outcomes, scenarios and staged updates. Read tools cannot lazily migrate indexes. There is no direct graph mutation, budget authorization, training, promotion or decision-execution tool. Results over 1 MB fail explicitly; evidence/source text can be paged.
The sharedagents companion adds a strict research profile and a foreground
sharedagents_research.ResearchWorkflow client. Configure this server as knowledge.
Both use this class API through MCP and require no BSON scripts or private wiki.
No production service/configuration changes are made by installing the library.