Files
VianoBugAnalysis/src/viano_bug_analysis/analysis/investigation_lean.py
T

144 lines
8.5 KiB
Python

"""Lean transport only: canonical evidence, budget and replay stay in the case."""
import copy
import json
from importlib.resources import files
VERSION = 'investigation_project_v19'
def enabled(context):
return 'lean_session' in context
def checkpoint(context):
from .investigation_compact import preparing_review
return enabled(context) and (context['lean_session']['checkpoint'] or preparing_review(context))
def base_context(context):
result=copy.deepcopy(context)
result.pop('lean_session',None)
return result
def schema(context, *, strict=False):
from .investigation_prompt import output_schema
full=output_schema(base_context(context),strict=strict)
if checkpoint(context):
full['properties']['next']['oneOf']=[b for b in output_schema(base_context(context),strict=True)['properties']['next'].get('oneOf',[])
if b['properties']['kind'].get('const') in {'finish','reject','request_diagnosis','defer','test'}]
# Early review uses an enum contract instead of oneOf.
if not full['properties']['next']['oneOf']:
full['properties']['next']=output_schema(base_context(context),strict=True)['properties']['next']
full['properties']['update']['properties'].pop('next_step',None)
full['properties']['update']['required']=[k for k in full['properties']['update']['required'] if k!='next_step']
return full
actions=[b for b in output_schema(base_context(context),strict=True)['properties']['next']['oneOf']
if b['properties']['kind'].get('const') in {'tool','recall'}]
actions.append({'type':'object','additionalProperties':False,'required':['kind'],
'properties':{'kind':{'const':'checkpoint'}}})
return {'type':'object','additionalProperties':False,'required':['assessment','observation','next'],
'properties':{'assessment':full['properties']['assessment'],
'observation':{'type':'string','maxLength':600},'next':({'oneOf':actions} if strict else {'type':'object','required':['kind'],'properties':{'kind':{'enum':['tool','recall','checkpoint']}}})}}
def build(context):
from .investigation_prompt import build_prompt
from .investigation_compact import model_view, _entry, _schema_catalog
from .model_context import model_json
base=base_context(context)
full=build_prompt(base)
contract=schema(context)
if checkpoint(context):
document=json.loads(full['messages'][1]['content'])
from .investigation_compact import preparing_review
if not preparing_review(base):document['task']='consolidate_investigation_session'
document['input']['session_log']=copy.deepcopy(context['lean_session']['turns'])
# Consolidation sees every result accumulated since the last checkpoint,
# including counterevidence, regardless of current view selection.
ids={t['evidence_id'] for t in context['lean_session']['turns'] if t['evidence_id']}
ids.update(eid for t in context['lean_session']['turns'] for eid in t.get('read_ids',[]))
document['input']['evidence'].update({eid:_entry(context['evidence'][eid]) for eid in ids})
document['input']['evidence_policy']['full_visible_ids']=sorted(document['input']['evidence'])
document['output_schema']=contract
if not preparing_review(base):
full['messages'][0]['content']=files('viano_bug_analysis.llm.prompts').joinpath('investigation_consolidate_v19.txt').read_text(encoding='utf-8')
else:
view=model_view(base);hid=context['selected_hypothesis']
previous=context.get('previous_result')
turns=context['lean_session']['turns']
keep=set(context.get('recalled_evidence',[]))
keep.update(t['evidence_id'] for t in turns if t['evidence_id'])
if previous:keep.add(previous['record']['id'])
# Share the freshest result even if another hypothesis produced it.
if context['evidence']:keep.add(sorted(context['evidence'])[-1])
schemas={eid:({'full_result_in_evidence':eid} if eid in keep else _schema_catalog(context['evidence'][eid]))
for eid in view['known_schemas']}
document={'task':'investigate_one_step','input':{
'case':view['case'],'sources':view['sources'],'interpretation':view['interpretation'],
'tool_schema':view['tool_schema'],
'hypothesis':{'id':hid,'proposal':{k:context['hypotheses'][hid]['proposal'][k] for k in ('title','mechanism')}},
'checkpoint_brief':({'findings':[{'direction':f['direction'],'text':f['text']} for f in view['working_brief']['findings']],
'uncertainties':view['working_brief']['uncertainties'],'next_question':view['working_brief']['next_question']} if view['working_brief'] else None),
'recent_observations':[{k:v for k,v in t.items() if k!='llm_ref'} for t in turns],
'previous_result':previous['record']['id'] if previous else None,
'evidence':{eid:_entry(context['evidence'][eid]) for eid in sorted(keep)},
'known_schemas':schemas,
'evidence_catalog':view['evidence_catalog'],'archive_ids':view['archive_ids'],
'budget':view['budget'],
**{k:view[k] for k in ('shared_metadata','previous_rejection','previous_rejection_details','database_query_failures','database_access') if k in view}},
'output_schema':contract}
# Keep actual argument contracts in the stable prefix, not inferred from
# prose. No arbitrary SQL or shell is added by the lean protocol.
document['input']['tool_schema']['request_contract']=schema(context,strict=True)['properties']['next']
full['messages'][0]['content']=files('viano_bug_analysis.llm.prompts').joinpath('investigation_lean_v19.txt').read_text(encoding='utf-8')
full.update(prompt_version=VERSION,output_schema=contract)
if 'previous_rejection_details' in document['input']:
document['input']['previous_rejection_details']=repair_feedback(document['input']['previous_rejection_details'])
full['messages'][1]['content']=model_json(document)
return full
def normalize(context, reply):
from .investigation_decision import normalize as canonical
base=base_context(context)
if checkpoint(context):
decision=copy.deepcopy(reply)
base['prompt_version']='investigation_project_v17'
return canonical(base,decision)
old=context.get('working_brief',{}).get('brief',{})
decision={'assessment':copy.deepcopy(reply['assessment']),
'next':({'kind':'defer','reason':'Consolidate provisional session.'} if reply['next']['kind']=='checkpoint' else copy.deepcopy(reply['next'])),
'update':{'confidence':context['hypotheses'][context['selected_hypothesis']]['confidence'],
'add_questions':[],'resolve_questions':[],
'working_brief':{'format_version':2,'findings':copy.deepcopy(old.get('findings',[])),
'retired':[],'uncertainties':copy.deepcopy(old.get('uncertainties',[])),
'next_question':reply['observation'] or 'Continue current investigation.'},
}}
# Normalization of a short step does not create a new consolidated brief,
# confidence or causal claim. It only accounts for the result and action.
base['prompt_version']='investigation_project_v17'
result=canonical(base,decision)
result['update'].pop('working_brief',None)
result['update'].pop('next_step',None)
result['update']['confidence']=context['hypotheses'][context['selected_hypothesis']]['confidence']
return result
def repair_feedback(details):
"""Project schema failures to the durable, value-free repair contract."""
result=copy.deepcopy(details)
keyword=result.pop('validation_keyword',None)
path=result.get('validation_path','')
import re
if keyword=='pattern' and re.fullmatch(r'/update/working_brief/findings/[0-9]+/id',path):
result['requirement']='use_stable_finding_ids_B_followed_by_at_least_four_digits_example_B0001_not_case_fact_ids'
elif keyword=='required' and 'path_prefix' in result.get('validation_fields',[]):
result['requirement']='provide_missing_required_fields; path_prefix="" searches_repository_root'
elif keyword is not None:
result.setdefault('requirement',{
'required':'provide_missing_required_fields','additionalProperties':'remove_unrecognized_fields',
'type':'match_expected_type_at_validation_path','enum':'use_allowed_value_at_validation_path',
'const':'use_allowed_value_at_validation_path'}.get(keyword,'match_full_controller_contract_at_validation_path'))
return result