import sys,json,re,collections,datetime as dt;sys.path.insert(0,'/home/claude/pkg') from pkgkit import * src=open('/home/claude/sw/crawl.py').read();SEEDS=eval(re.search(r'SEEDS=(\[.*?\])\n',src,re.S).group(1)) D=json.load(open('/home/claude/sw/npm_sample.json'));MIN=json.load(open('/home/claude/sw/minv.json')) def norm(u): u=u.lower().strip();u=re.sub(r'^git\+','',u);u=re.sub(r'\.git$','',u);u=re.sub(r'^(ssh://)?git@github\.com[:/]','https://github.com/',u);return u.replace('git://','https://').replace('http://','https://').replace('www.','') LO,HI='2025-01-01','2026-10-01' def secs(t): return int(dt.datetime.fromisoformat(t.replace('Z','+00:00')).timestamp()) def iso(s): return dt.datetime.fromtimestamp(s,dt.timezone.utc).strftime('%Y-%m-%dT%H:%M:%SZ') ev=[];idx={} for p,c in D.items(): rel=sorted([r for r in c['rel'] if '-' not in r['v']],key=lambda r:r['t']);c['_rel']=rel for r in rel: if LO<=r['t']30: continue same=bool(norm(D[a]['repo'])) and norm(D[a]['repo'])==norm(c['repo']) links.append((u,iw,same,dict(pkg=a,rng=rg,prev=pr,min=m))) links=list({(l[0],l[1]):l for l in links}.values());print('events',len(ev),'links',len(links),'packages',len(D)) sid='npm_registry' ents=[dict(id=f'pkg:{p}',type='package',label=p,attrs=dict(latest_version=c['latest']) if c['latest'] else {},provenance=dict(source_ids=[dict(source=sid,id=p)],derived=False)) for p,c in D.items()] rels=[] for p,c in D.items(): for a in c['ldeps']: if a in D and a!=p: rels.append(dict(id=f'dep:{p}>{a}',source=f'pkg:{p}',target=f'pkg:{a}',type='depends_on',directed=True,attrs={},provenance=dict(source_ids=[dict(source=sid,id=p)],derived=False))) events=[dict(id=f'{p}@{v}',kind='release',title=f'{p} {v}',time=dict(start=iso(TS[i]),precision='second',basis='recorded'),refs=[dict(entity=f'pkg:{p}',role='anchor')],attrs=dict(version=v), provenance=dict(source_ids=[dict(source=sid,id=f'{p}@{v}')],extraction=dict(method='stable release (no pre-release suffix) published inside the window',rule_ids=['R_STABLE_RELEASE']),confidence=None),link_coverage='partial') for i,(p,v,t) in enumerate(ev)] L=[] for u,iw,same,a in links: f=f'{ev[u][0]}@{ev[u][1]}';t=f'{ev[iw][0]}@{ev[iw][1]}';gs=TS[iw]-TS[u];days=(TF[iw]-TF[u])/86400 L.append({'id':f'{f}>{t}','from':f,'to':t,'kind':'hand_off' if same else 'dependency','propagates':True,'direction':'evidence' if gs==0 else 'time','gap_seconds':gs, 'evidence':{'existence':{'level':'rule','basis':'manifest_diff','rule_id':'R_MIN_VERSION_RAISED','text':f"{ev[iw][0]} {ev[iw][1]} raises its range for {a['pkg']} from {a['prev']} to {a['rng']}, whose lowest version is {a['min']}; {a['pkg']} {a['min']} was published {days:.2f} days earlier",'source_ref':dict(source=sid,id=f'{ev[iw][0]}@{ev[iw][1]}')}}, 'attrs':dict(dependency=a['pkg'],range_before=a['prev'],range_after=a['rng'],lowest_version=a['min']),**({'flags':['same_owner']} if same else {})}) M=dict(spec_version='0.1',package_id='software-npm-0.1',created_at=CREATED, adapter=dict(name='npm_release_adapter',version='0.1',domain='software',code_ref=None,produced_by='Claude, from the npm release pilot scripts (crawl.py, d_sw.py)'), domain=dict(event_definition='A stable release (a version without a pre-release suffix) of an npm package, published between 2025-01-01 and 2026-09-30, dated by its publish time',entity_description='npm packages; package relations follow the dependencies declared by the latest version'), sources=[dict(id=sid,name='npm registry package documents (versions, publish times, declared dependencies, repository)',url='https://registry.npmjs.org',accessed_at='2026-10',version='crawl of October 2026',license='npm registry metadata; terms not recorded in the pilot, to be filled in before the package is shared',notes='The release rows keep publisher user names out of this package')], observation_window=dict(start='2025-01-01',end='2026-09-30',collected_at='2026-10',right_censored=True), coverage=dict(procedure='snowball',description=f'Breadth-first crawl from {len(SEEDS)} well-known packages along the dependencies of the latest version, capped at 2500 packages (2544 packages reached); all stable releases of these packages in the window are events',seeds=SEEDS,depth_limit=None,selection_rules=['R_STABLE_RELEASE'], known_gaps=['Only packages reached by the capped crawl; dependents outside the sample are not seen, so links of heavily used packages are undercounted','Dependencies are the declared ranges of each release; a bump that happens through a lock file is not seen','Pre-release versions are excluded','The last release before each window start is not an event','The dependency relation among packages uses only the latest version of each package']), event_kinds=[dict(id='release',label='Release',description='A stable release of a package')], entity_types=[dict(id='package',label='Package',description='An npm package')],entity_relation_types=[],roles=[], link_kinds=[dict(id='hand_off',core_kind='hand_off',description='A release raises the minimum version of a dependency to exactly an upstream release of the same repository (release train)',propagates_default=True,default_window_seconds=604800,max_gap_seconds=2592000,direction_rule='From the upstream release to the dependent release in time',levels=['rule']), dict(id='dependency',core_kind='dependency',description='A release raises the minimum version of a declared dependency to exactly an upstream release of another repository',propagates_default=True,default_window_seconds=604800,max_gap_seconds=2592000,direction_rule='From the upstream release to the dependent release in time',levels=['rule'])], evidence_bases=[dict(id='manifest_diff',label='Manifest difference',description='Difference between the declared dependency ranges of consecutive stable releases')], rules=[dict(id='R_STABLE_RELEASE',description='Version without a pre-release suffix published inside the window',parameters=dict(window_start=LO,window_end='2026-10-01'),applies_to='event'), dict(id='R_MIN_VERSION_RAISED',description='A release changes the declared range of a package in the sample so that its lowest version rises and equals an upstream stable release published 0 to 30 days before',parameters=dict(max_gap_days=30),applies_to='link')], parameters=dict(max_gap_days=dict(value=30,description='Longest gap between the upstream release and the dependent release'),default_window_days=dict(value=7,description='Default window of the pilot'),same_repository_flag=dict(value='repository url equal after normalisation',description='Links inside one repository use kind hand_off and the flag same_owner')), limitations=['The sample is a capped snowball and not the whole registry','Only links where the new minimum version equals an upstream release in the sample are emitted','The link states that a release adopted an upstream release, not that it was caused by it','Publish times are the registry time stamps, second precision; two releases in one second would be simultaneous','Mass releases inside one repository create many links of the same pattern','Licence of the registry metadata is not recorded'], notes='Hand check: for any link, open the dependent release manifest and compare the range of the named dependency with the previous release.') od='/home/claude/pkg/out/software-npm' st=write_package(od,M,events,ents,rels,L,[],{},gz=('events.jsonl','links.jsonl','entity_relations.jsonl'));print(json.dumps(st)[:500]);print(finalize(od))