import sys,os,json,re,collections;sys.path.insert(0,'/home/claude/pkg') os.chdir('/home/claude/pol');sys.path.insert(0,'/home/claude/pol') import compare2 as C from pkgkit import * os.chdir('/home/claude/pkg') P=json.load(open('/home/claude/proto/policy.json'));E=P['events'];L=P['links'] docs=[] for pi,(k,(lab,a,b)) in enumerate(C.PER.items()): trade=C.select([x for x in C.ALL if a<=x['date']<=b],{'Presidential','USTR','BIS'}) for d in trade: docs.append(d|{'period':pi,'term':k}) assert len(docs)==len(E['t']) and all(d['title'][:130]==t for d,t in zip(docs,E['title'])),'document order mismatch' SRC=['Presidential','USTR','BIS'];ISS=['presidential','ustr','bis'] KIND={'EO':'executive_order','PROC':'proclamation','NOTICE':'agency_notice','OTHER':'other_document'} sid='federal_register' ents=[] for i,pl in enumerate(P['places']): ents.append(dict(id=f'topic:{i}',type='topic_region',label=pl['label'],attrs=dict(coords=dict(space='policy_topic_map_tsne_unit',x=pl['x'],y=pl['y']),documents=pl['n']),provenance=dict(source_ids=[],derived=True,method='k-means (k=10, 10 restarts, seed 0) on TF-IDF (8000 features, sublinear tf) reduced by SVD to 50 dimensions of title plus the first 2500 characters of text (scikit-learn); regions named by their top title terms and the majority issuer'))) for k,n in zip(ISS,['Presidential documents','US Trade Representative notices','Bureau of Industry and Security notices']): ents.append(dict(id=f'issuer:{k}',type='issuer',label=n,attrs={},provenance=dict(source_ids=[dict(source=sid,id=f'issuer:{k}')],derived=False))) events=[] for i,d in enumerate(docs): a=dict(document_number=d['id'],term=d['term'],issuer=ISS[E['src'][i]],coords=dict(space='policy_topic_map_tsne_unit',x=P['nodes']['x'][i],y=P['nodes']['y'][i])) if d['num']: a['instrument_number']=d['num'] if d['vol']: a['federal_register_volume']=int(d['vol']);a['start_page']=int(d['sp']) ev=dict(id=d['id'],kind=KIND[d['kind']],title=d['title'].strip() or f"Untitled {d['kind']} {d['id']}",time=dict(start=d['date']+'T00:00:00Z',precision='day',basis='recorded'), refs=[dict(entity=f"topic:{E['pl'][i]}",role='anchor'),dict(entity=f"issuer:{ISS[E['src'][i]]}",role='participant')],attrs=a, provenance=dict(source_ids=[dict(source=sid,id=d['id'])],extraction=dict(method='trade or tariff pattern in the title, or at least three matches in the text',rule_ids=['R_TRADE_TEXT']),confidence=None),link_coverage='complete') if d['url']: ev['url']=d['url'] events.append(ev) links=[];om=[];oc=collections.Counter();seen=set() def clean(s): lead=s.startswith('…');trail=s.endswith('…');w=re.sub(r'\s+',' ',s.strip('…').strip()).split(' ') if lead and len(w)>1: w=w[1:] if trail and len(w)>1: w=w[:-1] return ' '.join(w) for a,b,ty,gap,ev in zip(L['a'],L['b'],L['ty'],L['gap'],L['ev']): f,t=docs[a]['id'],docs[b]['id'];kind='amendment_reference' if ty==0 else 'plain_reference' if gap<0: oc['backward_in_time']+=1;om.append(dict(item_type='link',reason='backward_in_time',id=f'{f}>{t}:{kind}',**{'from':f,'to':t}));continue if (f,t,kind) in seen: continue seen.add((f,t,kind)) rule='R_CITE_NUMBER' if re.search(r'Executive Order|E\.O\.|Proclamation',ev['ref'],re.I) else 'R_CITE_FRPAGE' verb=f" near the verb stem '{ev['verb'].lower()}'" if ev['verb'] else ' with no modifying verb nearby' links.append({'id':f'{f}>{t}:{kind}','from':f,'to':t,'kind':kind,'propagates':ty==0,'direction':'evidence' if gap==0 else 'time','gap_seconds':int(gap)*86400, 'evidence':{'existence':{'level':'rule','basis':'text_pattern','rule_id':rule,'text':f"The later document names {ev['ref']}{verb}: {clean(ev['snip'])}",'source_ref':dict(source=sid,id=f'{t}>{f}')}},'attrs':dict(reference=ev['ref'])}) M=dict(spec_version='0.1',package_id='policy-us-trade-0.1',created_at=CREATED, adapter=dict(name='federal_register_trade_adapter',version='0.1',domain='policy',code_ref=None,produced_by='Claude, from the policy pilot scripts and Federal Register documents'), domain=dict(event_definition='A presidential document, or a USTR or BIS notice, in the Federal Register that concerns tariffs or trade, dated by its publication day',entity_description='Derived topic regions of the document text, and the issuing bodies (presidential documents, USTR, BIS)'), sources=[dict(id=sid,name='Federal Register documents (presidential documents, USTR and BIS rules and notices), document text and metadata',url='https://www.federalregister.gov',accessed_at='2026-10',version='download of October 2026',license='US federal government works; the Federal Register site states no copyright restriction on its documents (to be confirmed before sharing)')], observation_window=dict(start='2017-01-20',end='2026-10-18',collected_at='2026-10',right_censored=True), coverage=dict(procedure='query',description='Documents of the three terms (Trump first term from 2017-01-20, Biden, Trump second term to 2026-10-18) that match a tariff and trade pattern; links are searched only among the selected documents of the same term',seeds=[],depth_limit=None,selection_rules=['R_TRADE_TEXT'], known_gaps=['Documents that concern trade but do not match the pattern are missing','Links are found only by an explicit citation of an executive order or proclamation number or of a Federal Register page; amendments that name neither are missing','Citations are searched inside one term, so no link crosses a change of administration','Other agencies than USTR and BIS are not included','Recent documents have had little time to attract references']), event_kinds=[dict(id='executive_order',label='Executive order',description='Presidential executive order'),dict(id='proclamation',label='Proclamation',description='Presidential proclamation'),dict(id='agency_notice',label='Agency notice',description='USTR or BIS notice or rule'),dict(id='other_document',label='Other document',description='Other presidential document')], entity_types=[dict(id='topic_region',label='Topic region',description='Cluster of documents with similar words in title and text; derived'),dict(id='issuer',label='Issuing body',description='Presidential documents, USTR or BIS')], entity_relation_types=[],roles=[], link_kinds=[dict(id='amendment_reference',core_kind='reference',description='A later document names an earlier executive order or proclamation, or cites its Federal Register page, near a verb such as amend, extend or suspend',propagates_default=True,default_window_seconds=5184000,max_gap_seconds=None,direction_rule='From the cited document to the citing document; documents of the same day use evidence',levels=['rule']), dict(id='plain_reference',core_kind='reference',description='A later document names an earlier executive order or proclamation, or cites its page, without a modifying verb nearby',propagates_default=False,default_window_seconds=None,max_gap_seconds=None,direction_rule='From the cited document to the citing document; documents of the same day use evidence',levels=['rule'])], evidence_bases=[dict(id='text_pattern',label='Text pattern',description='Pattern match in the text of the citing document, with the surrounding words as reason')], rules=[dict(id='R_TRADE_TEXT',description='Title matches the trade pattern, or the text has at least three matches (tariff, ad valorem, harmonized tariff, section 232, section 301, reciprocal, de minimis, duties)',parameters=dict(min_text_matches=3),applies_to='event'), dict(id='R_CITE_NUMBER',description='The text names Executive Order or Proclamation with a number of an earlier selected document',parameters={},applies_to='link'), dict(id='R_CITE_FRPAGE',description='The text cites a Federal Register page (volume FR page) that falls in an earlier selected document',parameters={},applies_to='link')], parameters=dict(time_precision=dict(value='day',description='Documents are dated to the day of publication in the Federal Register; start is midnight UTC of that day and documents of one day are simultaneous'),modifying_verb_pattern=dict(value='amend, modif, supplement, revok, terminat, suspend, extend, continu, replac, rescind, end, adjust, expand, clarif, exempt, reduc, increas, implement, in response, retaliat, further to, exclusion, inclusion',description='Verb stems within 220 characters of the citation that make a link an amendment reference'), default_window_days=dict(value=60,description='Window used in the pilot for amendment references; the percolation sweep showed the steepest growth before it'), coords_space=dict(value='policy_topic_map_tsne_unit',description='attrs.coords hold a t-SNE layout of title and text in the unit square; layout hint only')), limitations=['Relations are typed by a verb pattern, not judged by a reader','The 60-day window of the pilot lies after the steepest growth of the giant component and may be too wide','Documents of one day are simultaneous at day precision; their links carry direction evidence','The topic regions are descriptive and derived from words','Only 601 documents; cascades are few and small'], notes='Hand check: the text of a link quotes the citing document around the citation; the cited number or page identifies the earlier document.') od='/home/claude/pkg/out/policy-us-trade' st=write_package(od,M,events,ents,[],links,om,oc);print(json.dumps(st)[:500]);print(finalize(od))