PlotDirector/Tools/WritingSolver/build-dead-end-repair.py

131 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Repair evidence-bearing dead ends without changing diagnosis coefficients/thresholds.
Original Stage 1 is retained as an immutable regression/publication baseline.
"""
import ast,copy,json
from pathlib import Path
r=Path(__file__).resolve().parents[2];base=r/'PlotLine/Content/WritingSolver/Candidates'
g=json.loads((base/'curated-v2-stage1/writing-solver-curated-v2-stage1.json').read_text())
g.update(requireCorroboratedResults=True,version='writing-solver-curated-v2-stage1-repair',changeNote='Repair confirmed-but-unscored observations and reserve the last two answers for corroboration/intention; preserve diagnosis coefficients, thresholds and evidence gates.')
original=json.loads((base/'curated-v2/writing-solver-curated-v2.json').read_text());oldids={n['id'] for n in original['nodes']};nodes={n['id']:n for n in g['nodes']}
# Literal editorial map from the prior assembly, not production code special cases.
tree=ast.parse((r/'Tools/WritingSolver/build-stage1.py').read_text())
families=next(ast.literal_eval(n.value) for n in tree.body if isinstance(n,ast.Assign) and any(isinstance(t,ast.Name) and t.id=='family_nodes' for t in n.targets))
# Each observation supplies the core facts it explicitly asserts, using the existing signal vocabulary.
# No threshold, coefficient or negative/penalty weight is changed. Competing diagnoses still need their own observation gate.
weights={
'threads':{'multiple-threads':6,'overwhelm':4,'scale':1},'dormancy':{'plot-dormancy':6},'connection':{'plot-connection':6},'purpose':{'scene-purpose':5},'payoff':{'setup-payoff':6},'causality':{'causality':5},
'cast':{'large-cast':6},'roles':{'role-overlap':5},'presence':{'character-presence':6},'proportions':{'character-presence':6,'distribution':4},'pov':{'pov':5,'distribution':1},'character-facts':{'character-facts':6,'continuity-conflict':2},'whereabouts':{'location':6,'character-presence':2},
'relationship-network':{'relationship':6,'overwhelm':3},'relationship-state':{'relationship-state':4,'relationship':2},'relationship-speed':{'relationship':4,'abrupt-progression':6},'relationship-stall':{'relationship':4,'flat-progression':5},'relationship-perspective':{'relationship':4,'perspective':5},'relationship-event':{'relationship':6,'dependency':5,'overwhelm':3},
'premature-knowledge':{'knowledge':5,'continuity-conflict':3},'knowledge-source':{'knowledge-origin':5,'knowledge':1},'pov-knowledge':{'knowledge':4,'pov':4},'reveal':{'revelation-order':5,'knowledge':2},'clues':{'clues':5,'knowledge':2},'reader-reveal':{'revelation-order':5,'setup-payoff':3,'distribution':1},
'calendar':{'chronology':6,'continuity-conflict':2},'elapsed':{'duration':5,'chronology':1},'age':{'character-facts':4,'chronology':4},'nonlinear':{'nonlinear':5,'chronology':1},'parallel':{'simultaneous-events':5,'chronology':1},'fixed':{'fixed-date':5,'chronology':1},
'scene-volume':{'scale':6,'overwhelm':2,'checking':2},'scene-position':{'scene-order':5},'chapters':{'chapter-structure':5},'repetition':{'repetition':5},'experiment':{'experiment':5,'revision':1},'movement':{'movement':6,'duration':2,'location':2},'place-state':{'location':5,'state-history':3},'object-track':{'object':6,'checking':2},'custody':{'object':2,'possession':5},'object-history':{'object':2,'state-history':5},
'story-stall':{'flat-progression':5},'pace':{'distribution':5},'tension':{'tension':5,'distribution':3},'arc':{'character-arc':6,'flat-progression':2},'late':{'late-concentration':6,'distribution':2},'dependencies':{'revision':3,'dependency':4},'versions':{'alternative-versions':5,'experiment':2},'series-memory':{'series':4},'series-thread':{'series':5,'multiple-threads':4},'whole-load':{'overwhelm':6,'scale':4}}
# Paired observations use their specific primary evidence, not the union of every diagnosis's
# weight map. Example: an age conflict does not add generic fact inconsistency points;
# a changed house is not given portable-object evidence; one pair is not a cast/network.
paired_primary={('cast','same-job'):'roles',('facts','age'):'age',('structure','volume'):'scene-volume',('whereabouts','journey'):'movement',('place','facts'):'place-state',('progression','tension'):'tension',('progression','late'):'late',('change','versions'):'versions',('relationships','ripples'):'relationship-event',('purpose','thread'):'purpose',('series','both'):'series-thread'}
changed=[]
for node in g['nodes']:
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1]
for choice in node['choices']:
observed=[k[9:] for k,v in choice['weights'].items() if k.startswith('observed-') and v>0]
if not observed:continue
key=paired_primary.get((family,choice['id']),observed[0]);assert key in weights,(node['id'],choice['id'],key)
before=copy.deepcopy(choice['weights'])
# Replace only the new Stage 1 corroboration contributions, never original symptom weights.
choice['weights']={k:v for k,v in choice['weights'].items() if k.startswith('observed-') or k in ['concern-confirmed','creative-concern']}
choice['weights'].update(weights[key])
changed.append(dict(node=node['id'],choice=choice['id'],before=before,after=choice['weights'],evidence=choice['text']))
# Restore full family follow-ups when a late focus answer must skip redundant navigation.
def check(family):
id='check-'+family
if id not in nodes:
variants=[n for n in g['nodes'] if n['id'].startswith(id+'-')];assert variants,id
node=copy.deepcopy(variants[0]);node['id']=id;node['choices']=[];node['routes']=[]
for variant in variants:
for c in variant['choices']:
if not any(v['id']==c['id'] for v in node['choices']):node['choices'].append(copy.deepcopy(c))
for route in variant['routes']:
if route not in node['routes']:node['routes'].append(copy.deepcopy(route))
nodes[id]=node;g['nodes'].append(node)
return id
# A useful non-fault observation should not fall through to generic insufficient evidence.
neutral={
('cast','none'):dict(title='An intentional gap does not need fixing.',summary='You have described a deliberate absence with nothing important missing. Keep the gap if it serves the role you want the character to play.',advice=[],feature='characters'),
('relationships','moving'):dict(title='Slow progress is still progress.',summary='You are seeing small changes. Follow those changes across the scenes before deciding that the relationship is stuck.',advice=['Compare what the characters can say or do at the beginning and end of the stretch.'],feature='relationships'),
('arc','steady'):dict(title='A steady character can still move a story.',summary='You have described a deliberately steady character whose events still have consequences. Follow those choices without assuming they need a transformation.',advice=[],feature='character-development')}
for node in g['nodes']:
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1]
for choice in node['choices']:
if (family,choice['id']) in neutral:
assert not choice['weights'];choice['reassurance']=neutral[(family,choice['id'])];node['allowNeutralChoices']=True
node['routes']=[v for v in node['routes'] if v.get('choice')!=choice['id']]
# A few prior follow-ups asked about a different concern than the symptom selected.
# Route to an existing relevant discriminator; do not infer a diagnosis from the redirect.
redirects={('track-people','where-everyone-is'):'whereabouts',('continuity-character','where'):'whereabouts',('continuity-character','knowledge'):'knowledge',('continuity-character','presence'):'cast',('flow-character','disappears'):'cast',('flow-thread','no-movement'):'causality',('flow-thread','scenes-advance'):'purpose'}
for (nid,cid),family in redirects.items():
assert any(c['id']==cid for c in nodes[nid]['choices']),(nid,cid)
nodes[nid]['routes']=[v for v in nodes[nid]['routes'] if v.get('choice')!=cid]
nodes[nid]['routes'].append(dict(target=check(family),choice=cid,priority=110,allowCycle=False))
# Keep optional old navigation only while two answer slots remain for proof and intention.
# Neutral adoption routing is deliberately unchanged.
for node in list(g['nodes']):
if node['id'] not in oldids:continue
additions=[]
for route in node['routes']:
if route['target'] not in oldids or route['target'] in ['existing-stage','existing-barrier']:continue
target_family=families.get(route['target'])
if not target_family:continue
fallback=copy.deepcopy(route);fallback['target']=check(target_family);fallback['fromAnswers']=4;fallback['priority']=route['priority']
route['beforeAnswers']=4;additions.append(fallback)
node['routes']+=additions
# Finish a corroboration question in the last slot by asking explicitly about the author's
# concern in the question itself; do not silently treat an observation as unwanted.
titles={'threads':'What is getting in the way of the work you want these storylines to do?','purpose':'Which of these makes the scene difficult to justify or keep track of?','causality':'What about the consequences is not working as you want?','payoff':'Which gap between preparation and payoff would you like help with?','cast':'What about these characters’ roles or appearances would you like help putting right?','relationships':'Which relationship pattern is not working as you want?','knowledge':'Which information problem would you like help untangling?','time':'Which timing problem would you like help putting right?','whereabouts':'What makes the characters’ movements difficult to follow or fit together?','structure':'Which part of the scene arrangement is getting in your way?','object':'Which problem with the object would you like help putting right?','place':'What about the place is no longer working consistently?','progression':'Which pattern is weakening the movement you want?','arc':'What effect on the character would you like to make clearer?','change':'Which consequence of the change would you like help with?','series':'Which cross-book difficulty would you like to get out of your head?','overload':'What is the organisation making harder than it needs to be?','facts':'Which established fact would you like help reconciling?'}
for node in list(g['nodes']):
if not node['id'].startswith('check-'):continue
family=node['id'].split('-')[1];final=copy.deepcopy(node);final['id']='final-'+node['id'][6:];final['title']=titles[family];final['help']='Choose what is getting in the way of what you want. A deliberate choice that is working does not need correcting.';final['routes']=[];final['allowNeutralChoices']=True
for choice in final['choices']:
if any(k.startswith('observed-') and v>0 for k,v in choice['weights'].items()):choice['weights'].update({'concern-confirmed':1,'creative-concern':1})
final['choices'].append(dict(id='deliberate',text='This is deliberate and working as I want',active=True,fallback=False,weights={},order=100,reassurance=dict(title='A deliberate choice does not need correcting.',summary='Keep the choice that serves your story. There is no reason to call it a fault just because its shape is unusual.',advice=[])))
nodes[final['id']]=final;g['nodes'].append(final)
for node in g['nodes']:
new=[]
for route in node['routes']:
if not route['target'].startswith('check-'):continue
last=copy.deepcopy(route);last['target']='final-'+route['target'][6:];last['fromAnswers']=5;last.pop('beforeAnswers',None);new.append(last)
route['beforeAnswers']=5
node['routes']+=new
# A late dominance route must not spend its final answer merely requesting another question.
# Collect the concrete concern and intended main-plot role together, with honest neutral options.
final=copy.deepcopy(nodes['dominance-intention']);final['id']='final-dominance';final['title']='If this is meant to be the main storyline, what would you like to put right?';final['help']='Choose the specific difficulty. A strong main plot is not a problem on its own.';final['routes']=[]
keep=[copy.deepcopy(c) for c in final['choices'] if c['id']!='main']
for cid,text,key in [
('disappears','The supporting threads disappear while this one is prominent, and I want those gaps addressed','dormancy'),
('connect','The other threads are present but do not clearly affect the main plot; I want that connection clearer','connection'),
('lost','I want to keep the main plot central, but I keep losing track of the supporting threads','threads')]:
w=dict(weights[key]);w.update({'observed-'+key:1,'concern-confirmed':1,'creative-concern':1})
keep.insert(1,dict(id=cid,text=text,active=True,fallback=False,order=len(keep),weights=w))
for i,choice in enumerate(keep):choice['order']=i
final['choices']=keep;g['nodes'].append(final);nodes[final['id']]=final
for node in g['nodes']:
additions=[]
for route in node['routes']:
if route['target']!='dominance-intention':continue
last=copy.deepcopy(route);last['target']='final-dominance';last['fromAnswers']=5;last.pop('beforeAnswers',None);additions.append(last);route['beforeAnswers']=5
node['routes']+=additions
# Optional assembly pruning is based on a complete actual-engine audit. Original 44 nodes
# and all diagnoses are protected; only unreachable new confirmation variants are omitted.
prune_file=r/'Docs/WritingSolver/CuratedV2/DeadEndRepair/unused-variants.json'
if prune_file.exists():
omit=set(json.loads(prune_file.read_text()));assert not omit.intersection(oldids),omit.intersection(oldids)
g['nodes']=[n for n in g['nodes'] if n['id'] not in omit]
for n in g['nodes']:n['routes']=[v for v in n['routes'] if v['target'] not in omit]
folder=base/'curated-v2-stage1-repair';folder.mkdir(exist_ok=True)
(folder/'writing-solver-curated-v2-stage1-repair.json').write_text(json.dumps(g,ensure_ascii=False,indent=2)+'\n')
(r/'Docs/WritingSolver/CuratedV2/DeadEndRepair/evidence-decisions.json').write_text(json.dumps(changed,ensure_ascii=False,indent=2)+'\n')