slopie 1.7.0 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/audit-splash.js +147 -0
- package/bin/potsherd.js +2 -0
- package/bin/slopie.js +2 -0
- package/dist/audit-native-worker.js +1265 -743
- package/dist/audit-native-worker.js.map +4 -4
- package/dist/potsherd.js +23658 -16750
- package/dist/potsherd.js.map +4 -4
- package/package.json +2 -6
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../core/src/analytics/
|
|
4
|
-
"sourcesContent": ["import {Worker,parentPort} from 'node:worker_threads';\nimport {serialize,deserialize} from 'node:v8';\nimport {createHash} from 'node:crypto';\nimport {streamNativeFacts,type StreamedNative} from './native-stream.js';\nimport {sourceId} from '../memory/source-identity.js';\nimport {isIgnoredProject} from '../ignore.js';\nexport interface NativeScanPolicy {authorityCommitment:string;ignoredProjects:readonly string[];forgottenSourceIds:readonly string[];project:string|null;eventFrom:string|null;asOf:string|null;}\nexport interface NativeScanJob {jobId:string;ordinal:number;file:string;harness:'claude'|'codex'|'pi';bytes:number;stamp:{dev:string;ino:string;size:number;mtimeNs:string;ctimeNs:string};maxBytes:number;maxRecords?:number;maxPromptBytes:number;policy:NativeScanPolicy;}\nexport interface NativeScanExecutor {scan(job:NativeScanJob,signal:AbortSignal):Promise<StreamedNative>;close():Promise<void>;}\nconst PROTOCOL='audit-native-v1',FRAME=1024*1024;\nconst code=(error:unknown)=>error instanceof Error&&/^(?:[a-z][a-z0-9_]{0,95})$/.test(error.message)?error.message:'native_worker_failed';\ninterface Pending {job:NativeScanJob;signal:AbortSignal;resolve:(v:StreamedNative)=>void;reject:(e:Error)=>void;remove:()=>void;}\ninterface Slot {worker:Worker;ready:boolean;pending:Pending|null;frames:Buffer[];bytes:number;next:number;}\n/** Two owned parser threads; policy authority and ordered aggregation stay in the caller. */\nexport function createNativeScanPool(entry:URL|string,options:{workers?:1|2;maxActiveBytes?:number;maxResultBytes?:number;maxRssBytes?:number}={}):NativeScanExecutor {\n const count=options.workers??2,maxActive=options.maxActiveBytes??256*1024*1024,maxResult=options.maxResultBytes??256*1024*1024,maxRss=options.maxRssBytes??1280*1024*1024;if(![1,2].includes(count)||![maxActive,maxResult,maxRss].every(n=>Number.isSafeInteger(n)&&n>0))throw new Error('native_pool_options_invalid');\n const slots:Slot[]=[],queue:Pending[]=[];let closed=false,failure:string|null=null,activeBytes=0;const terminations:Promise<unknown>[]=[];\n const rejectAll=(reason:string)=>{if(closed)return;failure=reason;closed=true;for(const pending of queue.splice(0)){pending.remove();pending.reject(new Error(reason));}for(const slot of slots){const pending=slot.pending;slot.pending=null;slot.frames=[];if(pending){pending.remove();pending.reject(new Error(reason));}terminations.push(slot.worker.terminate().catch(()=>undefined));}activeBytes=0;clearInterval(monitor);};\n const dispatch=()=>{if(closed)return;for(const slot of slots){if(!slot.ready||slot.pending||!queue.length)continue;const next=queue[0]!;if(next.signal.aborted){queue.shift();next.remove();next.reject(new Error('cancelled'));continue;}if(activeBytes>0&&activeBytes+next.job.bytes>maxActive)continue;queue.shift();slot.pending=next;slot.frames=[];slot.bytes=0;slot.next=0;activeBytes+=next.job.bytes;slot.worker.postMessage({protocol:PROTOCOL,kind:'scan',job:next.job,maxResultBytes:maxResult});}};\n const monitor=setInterval(()=>{if(!closed&&process.memoryUsage().rss>maxRss)rejectAll('native_pool_memory_limit');},250);monitor.unref();\n for(let i=0;i<count;i++){\n const worker=new Worker(entry,{resourceLimits:{maxOldGenerationSizeMb:384},stdout:true,stderr:true}),slot:Slot={worker,ready:false,pending:null,frames:[],bytes:0,next:0};slots.push(slot);worker.stdout?.resume();worker.stderr?.resume();\n worker.on('message',(message:unknown)=>{if(closed||!message||typeof message!=='object')return;const m=message as Record<string,unknown>;if(m.protocol!==PROTOCOL){rejectAll('native_worker_protocol_invalid');return;}if(m.kind==='ready'){slot.ready=true;dispatch();return;}const pending=slot.pending;if(!pending||m.jobId!==pending.job.jobId)return;\n if(m.kind==='frame'){if(m.sequence!==slot.next++||!(m.data instanceof Uint8Array)||m.data.byteLength>FRAME||slot.bytes+m.data.byteLength>maxResult){rejectAll('native_pool_result_bytes_limit');return;}const bytes=Buffer.from(m.data.buffer,m.data.byteOffset,m.data.byteLength);slot.frames.push(bytes);slot.bytes+=bytes.length;return;}\n if(m.kind==='result'||m.kind==='error'){slot.pending=null;activeBytes-=pending.job.bytes;pending.remove();if(m.kind==='error'){slot.frames=[];pending.reject(new Error(typeof m.code==='string'&&/^[a-z][a-z0-9_]{0,95}$/.test(m.code)?m.code:'native_worker_failed'));dispatch();return;}\n try{if(m.authorityCommitment!==pending.job.policy.authorityCommitment||m.bytes!==slot.bytes||typeof m.hash!=='string')throw new Error('native_worker_result_invalid');const buffer=Buffer.concat(slot.frames,slot.bytes);slot.frames=[];if(createHash('sha256').update(buffer).digest('hex')!==m.hash)throw new Error('native_worker_result_invalid');const result=deserialize(buffer) as StreamedNative;if(!result||!Array.isArray(result.usage)||!Array.isArray(result.language)||!Array.isArray(result.facts?.events)||result.bytes!==pending.job.bytes||typeof result.hash!=='string')throw new Error('native_worker_result_invalid');if(pending.signal.aborted)throw new Error('cancelled');pending.resolve(result);}catch(error){pending.reject(new Error(code(error)));}dispatch();\n }\n });worker.on('error',()=>rejectAll('native_worker_failed'));worker.on('exit',()=>{if(!closed)rejectAll('native_worker_exited');});\n }\n return {scan(job,signal){if(!closed&&process.memoryUsage().rss>maxRss)rejectAll('native_pool_memory_limit');if(closed)return Promise.reject(new Error(failure??'native_pool_closed'));if(!Number.isSafeInteger(job.bytes)||job.bytes<0||job.bytes>job.maxBytes)return Promise.reject(new Error('native_usage_total_bytes_limit'));return new Promise((resolve,reject)=>{const abort=()=>rejectAll('cancelled'),pending:Pending={job,signal,resolve,reject,remove:()=>signal.removeEventListener('abort',abort)};signal.addEventListener('abort',abort,{once:true});if(signal.aborted){abort();reject(new Error('cancelled'));return;}queue.push(pending);dispatch();});},async close(){rejectAll('native_pool_closed');await Promise.allSettled(terminations);}};\n}\n/** Minimal published sidecar: no catalogue, semantic provider, UI or database work. */\nexport function runNativeScanWorker():void {\n if(!parentPort)throw new Error('native_worker_requires_port');const port=parentPort;let busy=false;\n port.on('message',async(message:{protocol?:string;kind?:string;job?:NativeScanJob;maxResultBytes?:number})=>{if(message.protocol!==PROTOCOL||message.kind!=='scan'||!message.job||busy)return;busy=true;const job=message.job;\n try{const policy=job.policy,forgotten=new Set(policy.forgottenSourceIds),accept=(project:string|null,time:string|null)=>!(project&&isIgnoredProject(project,policy.ignoredProjects))&&(!policy.project||project===policy.project)&&(!policy.eventFrom||time!==null&&time>=policy.eventFrom)&&(!policy.asOf||time!==null&&time<=policy.asOf);\n const snapshot=await streamNativeFacts(job.file,job.harness,{signal:new AbortController().signal,maxBytes:job.maxBytes,maxRecords:job.maxRecords,maxPromptBytes:job.maxPromptBytes,captureBytes:0,captureFileBytes:job.bytes,expectedIdentity:{dev:job.stamp.dev,ino:job.stamp.ino},sourceAllowed:(id,project)=>!forgotten.has(sourceId(job.harness,id))&&!(project&&isIgnoredProject(project,policy.ignoredProjects)),accept});\n const buffer=serialize(snapshot);if(buffer.length>(message.maxResultBytes??256*1024*1024))throw new Error('native_pool_result_bytes_limit');const hash=createHash('sha256').update(buffer).digest('hex');let sequence=0;for(let at=0;at<buffer.length;at+=FRAME){const chunk=Uint8Array.from(buffer.subarray(at,at+FRAME));port.postMessage({protocol:PROTOCOL,kind:'frame',jobId:job.jobId,sequence:sequence++,data:chunk},[chunk.buffer]);}port.postMessage({protocol:PROTOCOL,kind:'result',jobId:job.jobId,authorityCommitment:policy.authorityCommitment,bytes:buffer.length,hash});\n }catch(error){port.postMessage({protocol:PROTOCOL,kind:'error',jobId:job.jobId,code:code(error)});}finally{busy=false;}\n });port.postMessage({protocol:PROTOCOL,kind:'ready'});\n}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport {createHash} from 'node:crypto';\nimport {extractTypedText,extractTextFromContent,isRecord} from '../parser/content.js';\nimport {hasExclusionMarker} from '../markers.js';\nimport {sourceId} from '../memory/source-identity.js';\nimport {clean,clock,digest,type NativeEvent,type NativeFacts} from './source.js';\nimport {NativeMetadataProjection} from './native-metadata-projection.js';\nimport {createNativeUsageAccumulator} from './native-usage.js';\nimport type {AuditHarness} from './contracts.js';\nimport type {RecordedInference,ContextRecord} from './launch-contracts.js';\nexport interface StreamedNative {facts:NativeFacts;usage:RecordedInference[];language:ContextRecord[];hash:string;bytes:number;stamp:{dev:string;ino:string;size:number;mtimeNs:string;ctimeNs:string};counts:{observed:number;excluded:number;deduplicated:number};}\n/** Full native inference metadata and observed role inputs; no assistant/tool bodies retained. */\nexport async function streamNativeFacts(file:string,harness:Exclude<AuditHarness,'opencode'>,options:{signal:AbortSignal;maxBytes:number;maxRecords?:number;maxPromptBytes?:number;captureBytes?:number;captureFileBytes?:number;expectedIdentity?:{dev:string;ino:string};sourceAllowed?:(nativeId:string,project:string|null)=>boolean;accept:(project:string|null,eventAt:string|null)=>boolean}):Promise<StreamedNative>{\n const before=fs.statSync(file,{bigint:true}),captureSize=options.captureFileBytes??Number(before.size);if(!before.isFile()||!Number.isSafeInteger(captureSize)||captureSize<0||captureSize>options.maxBytes)throw new Error('native_usage_bytes_limit');if(before.size<BigInt(captureSize)||options.expectedIdentity&&(String(before.dev)!==options.expectedIdentity.dev||String(before.ino)!==options.expectedIdentity.ino))throw new Error('source_changed');\n let nativeId=path.basename(file,'.jsonl'),project:string|null=null,parent:string|null=null,records=0,offset=0,promptBytes=0,maintenance=false,programmatic=false,currentModel:string|null=null,currentProvider:string|null=null;const events:NativeEvent[]=[],language:ContextRecord[]=[],gaps=new Set<string>(),seen=new Set<string>(),hash=createHash('sha256');let usage:ReturnType<typeof createNativeUsageAccumulator>|null=null;\n let held:Buffer[]=[],heldBytes=0,projection:NativeMetadataProjection|null=null,projected=false;const turnLimit=options.captureBytes??0,turns:{lines:string[];bytes:number;prefix:string}[]= [];let turnLines:string[]=[],turnBytes=0,turnPrefix='',keptBytes=0,capturedRecords=0,scopeUncertain=false;const finishTurn=()=>{if(!turnLines.length){if(turnLimit>0&&turnBytes>0)gaps.add('context_turn_oversize');turnBytes=0;return;}if(turnBytes+Buffer.byteLength(turnPrefix)<=turnLimit){turns.push({lines:turnLines,bytes:turnBytes,prefix:turnPrefix});keptBytes+=turnBytes;while(turns.length>1&&keptBytes+Buffer.byteLength(turns[0]!.prefix)>turnLimit)keptBytes-=turns.shift()!.bytes;}else gaps.add('context_turn_oversize');turnLines=[];turnBytes=0;};\n const process=(raw:Buffer,end:number)=>{if(++records>(options.maxRecords??1000000)){gaps.add('native_usage_records_limit');return;}const line=raw.toString('utf8');let r:Record<string,unknown>;try{const parsed=JSON.parse(line);if(!isRecord(parsed))return;r=parsed;}catch{gaps.add('malformed_record');return;}\n if(r.entrypoint==='sdk-ts'||r.originator==='codex_exec')programmatic=true;\n const p=isRecord(r.payload)?r.payload:r;if(p.originator==='codex_exec'||p.source==='exec')programmatic=true;const m=isRecord(r.message)?r.message:{};if(typeof r.cwd==='string')project=r.cwd;if(typeof p.cwd==='string')project=p.cwd;\n if(harness==='claude'&&typeof r.sessionId==='string'){if(file.includes(`${path.sep}subagents${path.sep}`)||r.isSidechain===true){parent=r.sessionId;nativeId=`${parent}:${path.basename(file,'.jsonl')}`;}else nativeId=r.sessionId;}\n if(harness==='codex'&&r.type==='session_meta'){nativeId=typeof p.id==='string'?p.id:typeof p.session_id==='string'?p.session_id:nativeId;const source=isRecord(p.source)?p.source:{},sub=isRecord(source.subagent)?source.subagent:{},spawn=isRecord(sub.thread_spawn)?sub.thread_spawn:{};if(typeof spawn.parent_thread_id==='string')parent=spawn.parent_thread_id;}\n if(harness==='pi'&&r.type==='session'){if(typeof r.id==='string')nativeId=r.id;if(typeof r.parentSessionId==='string')parent=r.parentSessionId;}\n if(r.type==='turn_context'||r.type==='session_meta'||r.type==='model_change'){currentModel=typeof p.model==='string'?p.model:typeof r.modelId==='string'?r.modelId:currentModel;currentProvider=typeof p.model_provider==='string'?p.model_provider:typeof r.provider==='string'?r.provider:currentProvider;}\n if(scopeUncertain&&project!==null&&(harness==='claude'&&typeof r.sessionId==='string'||harness==='codex'&&r.type==='session_meta'&&(typeof p.id==='string'||typeof p.session_id==='string')||harness==='pi'&&r.type==='session'&&typeof r.id==='string'))scopeUncertain=false;\n if(options.sourceAllowed&&!options.sourceAllowed(nativeId,project))throw new Error('native_source_policy_excluded');\n if(hasExclusionMarker(extractTypedText(m.content))||typeof p.message==='string'&&hasExclusionMarker(p.message))maintenance=true;\n const isInput=harness==='claude'&&r.type==='user'&&m.role==='user'&&!(Array.isArray(m.content)&&m.content.some(b=>isRecord(b)&&b.type==='tool_result'))||harness==='codex'&&r.type==='event_msg'&&p.type==='user_message'||harness==='pi'&&r.type==='message'&&m.role==='user';\n if(isInput){finishTurn();turnPrefix=JSON.stringify({type:'turn_context',payload:{cwd:project,model:currentModel,model_provider:currentProvider}})+'\\n';}\n if(projected&&turnLimit>0){turnLines=[];turnBytes=turnLimit+1;gaps.add('context_turn_oversize');}\n if(turnLimit>0&&!projected&&turnBytes<=turnLimit){const recordKey=typeof r.uuid==='string'?r.uuid:typeof r.id==='string'?r.id:typeof p.id==='string'?p.id:`record:${records}`;const encoded=JSON.stringify({...r,_auditRecordKey:recordKey})+'\\n';turnBytes+=Buffer.byteLength(encoded);if(turnBytes<=turnLimit)turnLines.push(encoded);else if(turnLines.length)turnLines=[];}\n if(!usage)usage=createNativeUsageAccumulator(harness,sourceId(harness,nativeId),{maxRecords:1000000,acceptRecord:(_r,scope)=>!maintenance&&!scopeUncertain&&options.accept(scope.project,scope.eventAt)});usage.pushRecord(r,{rawStart:offset,rawEnd:end});if(scopeUncertain)return;\n let text='',identity='',origin:NativeEvent['origin']='unknown',eligible=false,excluded:string|null=null;const time=clock(r.timestamp),key=typeof r.uuid==='string'?r.uuid:typeof r.id==='string'?r.id:typeof p.id==='string'?p.id:`record:${records}`;\n if(harness==='claude'&&r.type==='user'&&m.role==='user'){if(Array.isArray(m.content)&&m.content.some(b=>isRecord(b)&&b.type==='tool_result'))return;text=extractTypedText(m.content);identity=typeof r.promptId==='string'?`prompt:${r.promptId}`:`record:${key}`;origin=typeof r.promptId==='string'?'claude_prompt_id':'unknown';eligible=typeof r.promptId==='string'&&!programmatic;}\n else if(harness==='codex'&&r.type==='event_msg'&&p.type==='user_message'){text=typeof p.message==='string'?p.message:'';identity=`marker:${offset}`;origin=programmatic?'unknown':'codex_human_marker';eligible=!programmatic;}\n else if(harness==='pi'&&r.type==='message'&&m.role==='user'){text=extractTypedText(m.content);identity=`node:${key}`;origin='pi_user_projection';}\n else{const info=isRecord(p.info)?p.info:{};const observedModel=typeof m.model==='string'?m.model:typeof p.model==='string'?p.model:typeof r.model==='string'?r.model:typeof info.model==='string'?info.model:currentModel,observedProvider=typeof m.provider==='string'?m.provider:typeof p.model_provider==='string'?p.model_provider:typeof p.provider==='string'?p.provider:typeof r.provider==='string'?r.provider:currentProvider;if((m.role==='assistant'||harness==='codex'&&(r.type==='event_msg'&&p.type==='token_count'||r.type==='response_item'&&p.type==='message'&&p.role==='assistant'))&&observedModel!=='<synthetic>'&&r.isSynthetic!==true&&options.accept(project,time))language.push({id:`metadata:${records}`,conversationId:sourceId(harness,nativeId),parentId:parent,harness,eventAt:time,project,role:'assistant',text:'',model:observedModel==='codex-auto-review'?null:observedModel,provider:observedProvider,directUser:false,route:null});return;}\n if(!text.trim()&&!projected)return;if(hasExclusionMarker(text)){maintenance=true;excluded='maintenance_exclusion_marker';}else if(r.isMeta===true||r.isSynthetic===true||m.isSynthetic===true)excluded='declared_meta_or_synthetic_input';else if(parent&&events.length===0)excluded='child_initialization';else if(typeof r.session_id==='string'&&r.session_id!==nativeId)excluded='inherited_identity_unverified';\n if(seen.has(identity))return;seen.add(identity);if(!options.accept(project,time))return;const redacted=clean(text);if(promptBytes+Buffer.byteLength(redacted)>(options.maxPromptBytes??64*1024*1024)){gaps.add('native_input_text_limit');return;}promptBytes+=Buffer.byteLength(redacted);\n language.push({id:digest(`${sourceId(harness,nativeId)}:${identity}`).slice(0,32),conversationId:sourceId(harness,nativeId),parentId:parent,harness,eventAt:time,project,role:'user',text:'',model:null,provider:null,directUser:excluded===null&&parent===null,route:null});\n const proofRecord={...r};delete proofRecord.sessionId;delete proofRecord.session_id;delete proofRecord.promptId;const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):isRecord(value)?Object.fromEntries(Object.keys(value).sort().map(k=>[k,stable(value[k])])):value;\n events.push({key,rawStart:offset,rawEnd:end,role:'user',text:redacted,eventAt:time,project,origin,eligible:eligible&&excluded===null&&parent===null,languageEligible:parent===null&&!projected,excluded,identity,observed:excluded===null,...(harness==='claude'&&typeof r.uuid==='string'?{nativeRecordId:r.uuid,recordCommitment:digest(JSON.stringify(stable(proofRecord)))}:{}),...(harness==='claude'&&typeof r.session_id==='string'&&r.session_id!==nativeId?{declaredOrigin:r.session_id}:{})});\n };\n const finishLine=(end:number)=>{if(projection){const result=projection.finish();projection=null;gaps.add('native_record_body_omitted');if(result.exclusionMarker)maintenance=true;if(result.record){projected=true;process(Buffer.from(JSON.stringify(result.record)),end);projected=false;}else{turnLines=[];turnBytes=turnLimit+1;records++;gaps.add(result.code??'native_metadata_invalid');gaps.add('native_scope_record_unavailable');usage?.invalidateContext();scopeUncertain=true;project=null;currentModel=null;currentProvider=null;}}else process(held.length===1?held[0]!:Buffer.concat(held,heldBytes),end);held=[];heldBytes=0;offset=end;};\n const stream=fs.createReadStream(file,{highWaterMark:64*1024,...(captureSize>0?{end:captureSize-1}:{})});try{let consumed=0;for await(const chunk of captureSize===0?[]:stream){if(options.signal.aborted){stream.destroy();throw new Error('cancelled');}const bytes=chunk as Buffer;hash.update(bytes);let at=0;while(at<bytes.length){const newline=bytes.indexOf(10,at),end=newline<0?bytes.length:newline,part=bytes.subarray(at,end);if(projection)projection.push(part);else if(heldBytes+part.length>8*1024*1024){projection=new NativeMetadataProjection(undefined,harness);for(const piece of held)projection.push(piece);projection.push(part);held=[];heldBytes=0;}else{held.push(part);heldBytes+=part.length;}if(newline<0)break;finishLine(consumed+newline+1);at=newline+1;}consumed+=bytes.length;}}finally{stream.destroy();}\n if(heldBytes||projection)gaps.add('unfinished_tail');const after=fs.statSync(file,{bigint:true});if(before.dev!==after.dev||before.ino!==after.ino||after.size<BigInt(captureSize))throw new Error('source_changed');if(BigInt(captureSize)!==after.size||before.mtimeNs!==after.mtimeNs||before.ctimeNs!==after.ctimeNs){const verify=createHash('sha256'),fd=fs.openSync(file,'r'),buffer=Buffer.allocUnsafe(65536);try{let at=0;while(at<captureSize){const n=fs.readSync(fd,buffer,0,Math.min(buffer.length,captureSize-at),at);if(!n)throw new Error('source_changed');verify.update(buffer.subarray(0,n));at+=n;}}finally{fs.closeSync(fd);}if(verify.digest('hex')!==hash.copy().digest('hex'))throw new Error('source_changed');gaps.add('native_appended_after_capture');}\n if(maintenance){gaps.add('maintenance_source_excluded');for(const event of events){event.observed=false;event.eligible=false;event.excluded='maintenance_exclusion_marker';}}\n const artifactHash=hash.digest('hex'),acc=usage as ReturnType<typeof createNativeUsageAccumulator>|null,all=acc?.records()??[];finishTurn();const captured=Buffer.from((turns[0]?.prefix??'')+turns.flatMap(t=>t.lines).join(''));capturedRecords=turns.reduce((n,t)=>n+t.lines.length,0);if(turnLimit>0&&capturedRecords<records)gaps.add('context_capture_partial');return {facts:{nativeId,project,parent,child:parent!==null,title:null,events,gaps:[...gaps],hash:artifactHash,consumed:offset,bytes:captured},usage:maintenance?[]:all,language:maintenance?[]:language,hash:artifactHash,bytes:captureSize,stamp:{dev:String(after.dev),ino:String(after.ino),size:Number(after.size),mtimeNs:String(after.mtimeNs),ctimeNs:String(after.ctimeNs)},counts:maintenance?{observed:acc?.counts().observed??0,excluded:acc?.counts().observed??0,deduplicated:0}:acc?.counts()??{observed:0,excluded:0,deduplicated:0}};\n}\n", "/**\n * Content-block helpers.\n *\n * Ported from obra/episodic-memory@1075769 `src/parser.ts`\n * (MIT, (c) 2025 Jesse Vincent) \u2014 `extractTextFromContent`, `safeParseJson`\n * and `stringifyToolOutput` are upstream's, near-verbatim; the strict-mode\n * guards and `filesTouched` are potsherd's.\n *\n * Every harness writes an assistant turn as either a plain string or an array\n * of typed blocks. This module is the only place that knows the block shapes.\n */\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Join every `text` field in a content array. Upstream filters on the presence\n * of a string `text`, which is deliberately loose: it picks up `text`,\n * `input_text` and `output_text` blocks alike, and that is what codex needs.\n */\nexport function extractTextFromContent(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .filter((block): block is Record<string, unknown> => isRecord(block) && typeof block.text === 'string')\n .map((block) => block.text as string)\n .join('\\n');\n}\n\n/** Text blocks only \u2014 used for the claude path, where `type` is reliable. */\nexport function extractTypedText(content: unknown, blockType = 'text'): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return content\n .filter((b): b is Record<string, unknown> => isRecord(b) && b.type === blockType && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('\\n');\n}\n\nexport function safeParseJson(value: string): unknown {\n try {\n return JSON.parse(value) as unknown;\n } catch {\n return value;\n }\n}\n\nexport function stringifyToolOutput(output: unknown): string | undefined {\n if (output === undefined || output === null) return undefined;\n if (typeof output === 'string') return output;\n const text = extractTextFromContent(output);\n if (text.trim()) return text;\n try {\n return JSON.stringify(output);\n } catch {\n return undefined;\n }\n}\n\n/**\n * `Exchange.toolCalls[].input` is a string in `03` \u00A72 (it goes straight into a\n * TEXT column and through the redactor), so structured inputs are stringified\n * here once rather than at every call site.\n */\nexport function stringifyToolInput(input: unknown): string {\n if (input === undefined || input === null) return '';\n if (typeof input === 'string') return input;\n try {\n return JSON.stringify(input);\n } catch {\n return String(input);\n }\n}\n\n/**\n * The tool-input keys that name a file. `03` \u00A72 asks for `filesTouched`\n * \"parsed from Edit/Write/Read tool inputs\"; matching on the key rather than\n * the tool name survives new tools and harness-specific tool naming.\n */\nconst FILE_KEYS = ['file_path', 'filePath', 'notebook_path', 'notebookPath', 'path'] as const;\n\n/** Absolute-ish paths named by a tool input, in first-seen order. */\nexport function filesFromToolInput(input: unknown): string[] {\n if (!isRecord(input)) return [];\n const out: string[] = [];\n for (const key of FILE_KEYS) {\n const value = input[key];\n if (typeof value === 'string' && value.trim()) out.push(value);\n }\n // MultiEdit and friends nest one level: { edits: [{ file_path }] }.\n for (const value of Object.values(input)) {\n if (!Array.isArray(value)) continue;\n for (const item of value) {\n for (const f of filesFromToolInput(item)) out.push(f);\n }\n }\n return out;\n}\n\n/** Dedup preserving order \u2014 `filesTouched` is a set, but a stable one. */\nexport function uniq(values: readonly string[]): string[] {\n const seen = new Set<string>();\n const out: string[] = [];\n for (const v of values) {\n if (seen.has(v)) continue;\n seen.add(v);\n out.push(v);\n }\n return out;\n}\n", "/**\n * Opt-out markers: text that means \"do not index this conversation\".\n *\n * Ported from obra/episodic-memory@1075769 `src/constants.ts` (the summarizer\n * content marker, verbatim) and `src/sync.ts:7-11` (the exclusion list)\n * (MIT, (c) 2025 Jesse Vincent).\n *\n * Two of the three markers are upstream's own product strings and are kept\n * **verbatim on purpose**: a user who has been running episodic-memory has\n * these markers sitting in real transcripts already, and potsherd must honour\n * the opt-out they represent rather than re-indexing what they excluded.\n * potsherd's own marker is added alongside.\n */\n\n/** Upstream's summarizer prompt contains this, so its own runs never index. */\nexport const SUMMARIZER_CONTEXT_MARKER =\n 'Context: This summary will be shown in a list to help users and Claude choose which conversations are relevant';\n\n/** potsherd's equivalent, for the card writer in phase 2. */\nexport const POTSHERD_CARD_MARKER =\n '<INSTRUCTIONS-TO-POTSHERD>DO NOT INDEX THIS CHAT</INSTRUCTIONS-TO-POTSHERD>';\n\nexport const EXCLUSION_MARKERS: readonly string[] = [\n '<INSTRUCTIONS-TO-EPISODIC-MEMORY>DO NOT INDEX THIS CHAT</INSTRUCTIONS-TO-EPISODIC-MEMORY>',\n 'Only use NO_INSIGHTS_FOUND',\n SUMMARIZER_CONTEXT_MARKER,\n POTSHERD_CARD_MARKER,\n];\n\n/** True when a transcript's text opts out of indexing. */\nexport function hasExclusionMarker(text: string): boolean {\n return EXCLUSION_MARKERS.some((marker) => text.includes(marker));\n}\n", "import {createHash} from 'node:crypto';\n/** Stable native source identity, shared with memory without loading its database graph. */\nexport function sourceId(harness:string,nativeSessionId:string):string{return createHash('sha256').update(`source/v1\\0${harness}\\0${nativeSessionId}`).digest('hex');}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport {createHash} from 'node:crypto';\nimport {readJsonlLines,parseJsonLine} from '../parser/jsonl.js';\nimport {isRecord,extractTypedText,extractTextFromContent} from '../parser/content.js';\nimport {redact} from '../redact.js';\nimport {elideBinary} from '../redact-elide.js';\nimport {hasExclusionMarker} from '../markers.js';\nimport type {AuditHarness} from './contracts.js';\n\nexport const digest=(value:string|Buffer):string=>createHash('sha256').update(value).digest('hex');\nexport const clean=(text:string):string=>redact(elideBinary(text)).text;\nexport const clock=(value:unknown):string|null=>typeof value==='string'&&Number.isFinite(Date.parse(value))?new Date(value).toISOString():null;\nexport interface NativeEvent {observed?:boolean;languageEligible?:boolean;key:string;rawStart:number;rawEnd:number;role:'user';text:string;eventAt:string|null;project:string|null;origin:'claude_prompt_id'|'codex_human_marker'|'pi_user_projection'|'opencode_user_projection'|'unknown';eligible:boolean;excluded:string|null;identity:string;evidenceStart?:number;nativeRecordId?:string;recordCommitment?:string;declaredOrigin?:string;}\nexport interface NativeFacts {nativeId:string;project:string|null;parent:string|null;child:boolean;title:string|null;events:NativeEvent[];gaps:string[];hash:string;consumed:number;bytes:Buffer;}\n\n/** A size check and a bounded fd read, with identity rechecked after reading. */\nexport function boundedBytes(file:string,max:number):Buffer {\n const fd=fs.openSync(file,'r');\n try{const before=fs.fstatSync(fd);if(!before.isFile()||before.size>max)throw new Error('source_bytes_limit');\n const bytes=Buffer.alloc(before.size);let offset=0;\n while(offset<bytes.length){const n=fs.readSync(fd,bytes,offset,bytes.length-offset,offset);if(!n)throw new Error('source_changed');offset+=n;}\n const after=fs.fstatSync(fd);if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||before.dev!==after.dev||before.ino!==after.ino)throw new Error('source_changed');\n return bytes;\n }finally{fs.closeSync(fd);}\n}\n\n/** Bounded entry iteration: no adapter discover() array or symlink traversal. */\nexport async function* walk(root:string,maxEntries:number,signal:AbortSignal,maxDepth=8):AsyncGenerator<string> {\n let visited=0;\n async function* visit(dir:string,depth:number):AsyncGenerator<string>{\n if(signal.aborted)return;if(depth>maxDepth)throw new Error('discovery_depth_limit');\n let handle:fs.Dir;try{handle=await fs.promises.opendir(dir);}catch(error){if((error as NodeJS.ErrnoException).code==='ENOENT')return;throw new Error('source_root_unreadable');}\n try{for await(const item of handle){if(signal.aborted)return;if(++visited>maxEntries)throw new Error('discovery_entries_limit');\n const file=path.join(dir,item.name);if(item.isDirectory())yield* visit(file,depth+1);else if(item.isFile())yield file;\n }}finally{try{await handle.close();}catch{/* async iteration already closes it */}}\n }\n yield* visit(root,0);\n}\n\n/** Shares the established JSONL reader and exact content extractors; no exchange folding. */\nexport async function nativeFacts(file:string,harness:Exclude<AuditHarness,'opencode'>,bytes:Buffer,maxRecords:number):Promise<NativeFacts>{\n const events:NativeEvent[]=[];const gaps=new Set<string>();let project:string|null=null,parent:string|null=null,title:string|null=null;\n let nativeId=path.basename(file,'.jsonl'),consumed=0,records=0,turn:string|null=null,programmatic=false;\n const identity=new Map<string,string>();\n const responses:{text:string;cleanText:string;turn:string|null;start:number;end:number;key:string;time:string|null;project:string|null}[]=[];\n const markers:{event:NativeEvent;turn:string|null}[]=[];\n const put=(event:NativeEvent)=>{const previous=identity.get(event.identity);if(previous!==undefined){if(previous!==event.text)gaps.add('native_event_identity_conflict');return;}identity.set(event.identity,event.text);events.push(event);};\n for await(const line of readJsonlLines(file,{snapshot:bytes})){\n if(!line.terminated){gaps.add('unfinished_tail');break;}if(++records>maxRecords){gaps.add('source_records_limit');break;}consumed=line.end;\n const r=parseJsonLine(line.text);if(!isRecord(r)){if(line.text.trim())gaps.add('malformed_record');continue;}\n const p=isRecord(r.payload)?r.payload:r,m=isRecord(r.message)?r.message:{};\n if(typeof r.cwd==='string')project=r.cwd;if(typeof p.cwd==='string')project=p.cwd;\n const key=typeof r.uuid==='string'?r.uuid:typeof p.id==='string'?p.id:`record:${line.lineNumber}`;\n const at=clock(r.timestamp);const base={key,rawStart:line.start,rawEnd:line.end,role:'user' as const,eventAt:at,project};\n const maintenance=(text:string)=>hasExclusionMarker(text);\n if(harness==='claude'){\n if(typeof r.sessionId==='string'&&!file.includes(`${path.sep}subagents${path.sep}`))nativeId=r.sessionId;\n if(typeof r.entrypoint==='string'){if(r.entrypoint==='sdk-ts')programmatic=true;else if(['cli','desktop','vscode'].includes(r.entrypoint))programmatic=false;}\n if(file.includes(`${path.sep}subagents${path.sep}`)||r.isSidechain===true){parent=typeof r.sessionId==='string'?r.sessionId:parent;}\n if(r.type==='ai-title'&&typeof r.aiTitle==='string')title=clean(r.aiTitle);\n if(r.type!=='user'||m.role!=='user'){\n if(m.role==='user'){const text=extractTypedText(m.content);if(text.trim()){gaps.add('unsupported_user_container');put({...base,text:clean(text),origin:'unknown',eligible:false,excluded:'unsupported_user_container',identity:`record:${key}`});}}\n continue;\n }\n const text=extractTypedText(m.content);if(!text.trim())continue;\n const results=Array.isArray(m.content)&&m.content.some(b=>isRecord(b)&&b.type==='tool_result');\n const native=typeof r.promptId==='string'&&r.promptId.length>0&&!results;\n const explicitMeta=r.isMeta===true||r.isSynthetic===true;\n const declared=typeof r.session_id==='string'&&r.session_id!==nativeId?r.session_id:undefined;\n const recordCopy={...r};delete recordCopy.sessionId;delete recordCopy.session_id;delete recordCopy.promptId;\n const stable=(value:unknown):unknown=>Array.isArray(value)?value.map(stable):isRecord(value)?Object.fromEntries(Object.keys(value).sort().map(k=>[k,stable(value[k])])):value;\n const excluded=parent&&events.length===0?'child_initialization':maintenance(text)?'maintenance_exclusion_marker':results?'tool_result':explicitMeta?'declared_meta_or_synthetic_input':declared?'inherited_identity_unverified':programmatic?'programmatic_origin_unattested':native?null:'injected_or_origin_unknown';\n if(programmatic&&!parent&&excluded!=='maintenance_exclusion_marker')gaps.add('human_attestation_unavailable');if(explicitMeta&&!parent)gaps.add('explicit_meta_or_synthetic_origin_unattested');\n put({...base,observed:!results&&!explicitMeta&&!maintenance(text)&&!declared&&!(parent&&events.length===0),text:clean(text),origin:native&&!declared&&!programmatic&&!explicitMeta?'claude_prompt_id':'unknown',eligible:native&&excluded===null,excluded,identity:native&&!explicitMeta?`prompt:${r.promptId}`:`record:${key}`,...(typeof r.uuid==='string'&&r.uuid.length>0?{nativeRecordId:r.uuid,recordCommitment:digest(JSON.stringify(stable(recordCopy)))}:{}),...(declared?{declaredOrigin:declared}:{})});\n }else if(harness==='codex'){\n if(r.type==='session_meta'){\n nativeId=typeof p.session_id==='string'?p.session_id:typeof p.id==='string'?p.id:nativeId;\n if(p.originator==='codex_exec'||p.source==='exec')programmatic=true;\n const source=isRecord(p.source)?p.source:{},sub=isRecord(source.subagent)?source.subagent:{},spawn=isRecord(sub.thread_spawn)?sub.thread_spawn:{};\n if(typeof spawn.parent_thread_id==='string')parent=spawn.parent_thread_id;\n }\n if(typeof p.turn_id==='string')turn=p.turn_id;\n if(r.type==='response_item'&&p.type==='message'&&p.role==='user'){\n const text=extractTextFromContent(p.content);if(text.trim())responses.push({text,cleanText:clean(text),turn,start:line.start,end:line.end,key,time:at,project});\n }\n if(r.type!=='response_item'&&r.type!=='event_msg'&&p.role==='user'){\n const text=extractTextFromContent(p.content);if(text.trim()){gaps.add('unsupported_user_container');put({...base,text:clean(text),origin:'unknown',eligible:false,excluded:'unsupported_user_container',identity:`record:${key}`});}\n }\n if(r.type!=='event_msg')continue;\n const item=isRecord(p.item)?p.item:{};\n const text=p.type==='user_message'&&typeof p.message==='string'?p.message:p.type==='item_completed'&&item.type==='UserMessage'?extractTextFromContent(item.content):'';\n if(!text.trim())continue;\n const id=typeof item.id==='string'?`item:${item.id}`:`marker:${line.start}`;\n const excluded=parent&&events.length===0?'child_initialization':maintenance(text)?'maintenance_exclusion_marker':programmatic?'programmatic_origin_unattested':null;\n if(programmatic&&!parent&&excluded!=='maintenance_exclusion_marker')gaps.add('human_attestation_unavailable');\n const event:NativeEvent={...base,observed:excluded===null||excluded==='programmatic_origin_unattested',text:clean(text),origin:programmatic?'unknown':'codex_human_marker',eligible:excluded===null,excluded,identity:id};\n const before=events.length;put(event);if(events.length>before)markers.push({event,turn});\n }else{\n if(r.type==='session'){if(typeof r.id==='string')nativeId=r.id;if(typeof r.cwd==='string')project=r.cwd;if(typeof r.parentSessionId==='string')parent=r.parentSessionId;continue;}\n if(r.type!=='message'||m.role!=='user')continue;const text=extractTypedText(m.content);if(!text.trim())continue;\n put({...base,observed:r.isMeta!==true&&r.isSynthetic!==true&&!maintenance(text),text:clean(text),origin:'pi_user_projection',eligible:false,excluded:'projection_origin_unverified',identity:`node:${typeof r.id==='string'?r.id:key}`});gaps.add('pi_exchange_projection_fidelity');\n }\n }\n if(harness==='codex'){\n // Markers are the count authority. Pair only unique text candidates inside the\n // explicit turn or nearest marker window; a same-text injection remains ambiguous.\n const used=new Set<number>();\n for(let i=0;i<markers.length;i++){const marker=markers[i]!,prev=markers[i-1]?.event.rawStart??0,next=markers[i+1]?.event.rawStart??consumed;\n const matches=responses.filter(r=>!used.has(r.start)&&r.cleanText.trim()===marker.event.text.trim()&&(marker.turn!==null?r.turn===marker.turn:r.start>=prev&&r.start<=next));\n if(matches.length===1){const response=matches[0]!;used.add(response.start);marker.event.evidenceStart=response.start;}else if(matches.length>1)gaps.add('codex_response_pair_ambiguous');\n }\n for(const response of responses){if(used.has(response.start))continue;const matches=markers.some(m=>m.event.text.trim()===response.cleanText.trim());\n events.push({key:response.key,rawStart:response.start,rawEnd:response.end,role:'user',text:response.cleanText,eventAt:response.time,project:response.project,origin:'unknown',eligible:false,excluded:matches?'unpaired_user_response':'human_marker_missing',identity:`response:${response.start}`});\n if(!markers.length)gaps.add('codex_human_marker_missing');\n }\n }\n if(parent&&harness==='claude')nativeId=`${parent}:${path.basename(file,'.jsonl')}`;\n if(parent){for(const event of events)event.eligible=false;}\n if(harness==='pi')gaps.add('pi_exchange_projection_fidelity');\n const complete=bytes.subarray(0,consumed);return {nativeId,project,parent,child:parent!==null,title,events,gaps:[...gaps],hash:digest(complete),consumed,bytes:complete};\n}\n", "import { createHash } from 'node:crypto';\nimport type { Exchange, ExchangeToolCall } from './adapters/types.js';\nimport { Theme } from './theme.js';\nimport type { Row } from './render.js';\nimport * as fmt from './format.js';\nimport {\n ALLOW_SPANS,\n RULES,\n SECRET_TYPES,\n type Rule,\n type SecretType,\n} from './redact-rules.js';\n\nexport type { SecretType } from './redact-rules.js';\n// The pre-redaction pass. Not redaction \u2014 it removes binary bulk that carries\n// no meaning for retrieval \u2014 but it runs immediately before this module on the\n// same strings, so it is re-exported here and the two are read together.\nexport {\n elideBinary,\n elideExchange,\n emptyElisions,\n addElisions,\n MIN_PAYLOAD,\n ELISION_RE,\n type Elisions,\n} from './redact-elide.js';\nexport {\n RULES,\n SECRET_TYPES,\n shannonEntropy,\n ENTROPY_MIN_LENGTH,\n ENTROPY_THRESHOLD,\n nameLooksLikeSecret,\n valueLooksLikeSecret,\n type Rule,\n} from './redact-rules.js';\n\n/**\n * L2 \u2014 redaction. `plans/03-ARCHITECTURE.md` \u00A75 and \u00A711.\n *\n * This module decides whether a user's secrets can ever leave their machine.\n * Nothing downstream of it \u2014 the index, cards, ask, graft \u2014 is allowed to see\n * an unredacted string, and every string that reaches a model passes through\n * here first. A false negative is a leaked credential; a false positive is one\n * unreadable token in a search result. The rules are tuned accordingly.\n *\n * Pure and synchronous by contract: no I/O, no network, no module state that\n * survives a call. It runs over the whole corpus at index time, so it also has\n * to be fast \u2014 see `tests/redact.test.ts` for the measured 10 MB throughput.\n *\n * ## The mask\n *\n * \u2039redacted:<type>:<sha8>\u203A e.g. \u2039redacted:aws:cccc2222\u203A\n *\n * `sha8` is the first 8 hex characters of sha256(secret), so the *same* secret\n * always produces the *same* mask: the index stays searchable by shape (\"that\n * session where the same aws key appeared\") and never by value. Two different\n * secrets colliding needs a 32-bit sha256 prefix collision.\n *\n * The guillemets are deliberate: `\u2039` U+2039 and `\u203A` U+203A cannot appear in a\n * shell token, a json key or a base64 blob, so the mask can never be confused\n * for content and can never be pasted back into a command by accident.\n *\n * fts5 tokenisation, measured against the bundled sqlite (default `unicode61`\n * tokenizer): `\u2039redacted:aws:cccc2222\u203A` indexes as the three tokens\n * `redacted`, `aws`, `cccc2222` \u2014 both guillemets and both colons are\n * separators. So `find \"cccc2222\"` locates every exchange that leaked that one\n * secret, `find \"redacted AND aws\"` locates every exchange that leaked an aws\n * key, and the phrase query `\"redacted:aws:cccc2222\"` also works. The mask\n * costs three tokens per hit in the index and nothing else.\n *\n * ## What redaction does NOT touch\n *\n * The archive copy (L3) is byte-exact and unredacted: it is the user's own file\n * on the user's own disk. Only the *index* is redacted. There is no\n * `--no-redact` flag (`03` \u00A711) and adding one is not a feature request.\n */\n\n/** A masked secret. `sha8` identifies it without revealing it. */\nexport interface RedactionHit {\n type: SecretType;\n /** Rule id that claimed it \u2014 `doctor` and false-positive triage. */\n rule: string;\n /** First 8 hex chars of sha256(secret). */\n sha8: string;\n /** Offset of the secret in the *input* text. */\n start: number;\n /** Length of the secret in the input text. */\n length: number;\n}\n\nexport interface RedactionResult {\n text: string;\n hits: RedactionHit[];\n}\n\n/** Counts by type, for `doctor`. */\nexport interface RedactionCounts {\n total: number;\n byType: Record<SecretType, number>;\n}\n\nconst OPEN = '\u2039';\nconst CLOSE = '\u203A';\n\n/** Matches potsherd's own mask, so a second pass recognises its output. */\nexport const MASK_RE = new RegExp(`${OPEN}redacted:[a-z-]+:[0-9a-f]{8}${CLOSE}`, 'g');\n\n/** The first 8 hex characters of sha256(secret). */\nexport function secretDigest(secret: string): string {\n return createHash('sha256').update(secret, 'utf8').digest('hex').slice(0, 8);\n}\n\n/** `\u2039redacted:aws:cccc2222\u203A` */\nexport function maskFor(type: SecretType, secret: string): string {\n return `${OPEN}redacted:${type}:${secretDigest(secret)}${CLOSE}`;\n}\n\n/** Does this text already contain a potsherd mask? */\nexport function containsMask(text: string): boolean {\n return new RegExp(MASK_RE.source).test(text);\n}\n\ninterface Span {\n start: number;\n end: number;\n}\n\n/**\n * Mask every secret in `text`.\n *\n * Rules are applied in `RULES` order and the first rule to claim a span keeps\n * it, which is why the table is ordered specific \u2192 generic \u2192 entropy: a jwt is\n * reported as a jwt and not as three high-entropy tokens, and the base64 body\n * of a private key is reported as one private key and not as forty.\n *\n * Idempotent: existing masks are protected spans, so `redact(redact(x).text)`\n * returns the same text with no further hits.\n */\nexport function redact(text: string): RedactionResult {\n if (typeof text !== 'string' || text.length === 0) return { text: text ?? '', hits: [] };\n\n // Claimed characters. One byte per input character: an O(1) overlap test that\n // stays honest when 40 rules each propose overlapping spans.\n const claimed = new Uint8Array(text.length);\n const spans: Array<Span & { rule: Rule; value: string }> = [];\n\n // Allowlisted regions (data URIs, SRI hashes) and this module's own masks are\n // claimed before any rule runs, so nothing can match inside them.\n for (const span of protectedSpans(text)) claim(claimed, span);\n\n for (const rule of RULES) {\n for (const m of rule.scan(text)) {\n if (m.start < 0 || m.end > text.length || m.end <= m.start) continue;\n if (isClaimed(claimed, m)) continue;\n claim(claimed, m);\n spans.push({ start: m.start, end: m.end, rule, value: m.value });\n }\n }\n\n if (spans.length === 0) return { text, hits: [] };\n spans.sort((a, b) => a.start - b.start);\n\n const out: string[] = [];\n const hits: RedactionHit[] = [];\n let cursor = 0;\n for (const s of spans) {\n out.push(text.slice(cursor, s.start));\n const sha8 = secretDigest(s.value);\n out.push(`${OPEN}redacted:${s.rule.type}:${sha8}${CLOSE}`);\n hits.push({ type: s.rule.type, rule: s.rule.id, sha8, start: s.start, length: s.end - s.start });\n cursor = s.end;\n }\n out.push(text.slice(cursor));\n return { text: out.join(''), hits };\n}\n\n/** Just the text, for the many callers that do not care what was masked. */\nexport function redactText(text: string): string {\n return redact(text).text;\n}\n\n/**\n * Redact one exchange in place of its unredacted self: `user_text`,\n * `assistant_text` and every `tool_calls.input` / `.result` (`03` \u00A75). Returns\n * a new object; the input is never mutated, because the caller may still be\n * writing the byte-exact archive copy from it.\n */\nexport function redactExchange(ex: Exchange): { exchange: Exchange; hits: RedactionHit[] } {\n const hits: RedactionHit[] = [];\n const one = (s: string): string => {\n const r = redact(s);\n if (r.hits.length) hits.push(...r.hits);\n return r.text;\n };\n\n const userText = one(ex.userText);\n const assistantText = one(ex.assistantText);\n const toolCalls: ExchangeToolCall[] = ex.toolCalls.map((tc) => {\n const next: ExchangeToolCall = { ...tc, input: one(tc.input) };\n if (tc.result !== undefined) next.result = one(tc.result);\n return next;\n });\n\n return {\n exchange: { ...ex, userText, assistantText, toolCalls, redacted: ex.redacted || hits.length > 0 },\n hits,\n };\n}\n\n// ---------------------------------------------------------------- counting\n\nexport function emptyCounts(): RedactionCounts {\n const byType = {} as Record<SecretType, number>;\n for (const t of SECRET_TYPES) byType[t] = 0;\n return { total: 0, byType };\n}\n\n/** Tally hits by type. `doctor` sums these across the whole index. */\nexport function tally(hits: Iterable<RedactionHit>, into: RedactionCounts = emptyCounts()): RedactionCounts {\n for (const h of hits) {\n into.byType[h.type] = (into.byType[h.type] ?? 0) + 1;\n into.total++;\n }\n return into;\n}\n\nexport function addCounts(a: RedactionCounts, b: RedactionCounts): RedactionCounts {\n const out = emptyCounts();\n out.total = a.total + b.total;\n for (const t of SECRET_TYPES) out.byType[t] = (a.byType[t] ?? 0) + (b.byType[t] ?? 0);\n return out;\n}\n\n/** `{ total, aws: 3, jwt: 12 }` \u2014 the `--json` shape for `doctor`. */\nexport function countsJson(c: RedactionCounts): Record<string, number> {\n const out: Record<string, number> = { total: c.total };\n for (const t of SECRET_TYPES) if ((c.byType[t] ?? 0) > 0) out[t] = c.byType[t] ?? 0;\n return out;\n}\n\n/**\n * The `doctor` line (`03` \u00A75: \"`potsherd doctor` reports redaction counts by\n * type\"), in the house style of `render.ts`:\n *\n * secrets masked 1,284 jwt 512 \u00B7 entropy 402 \u00B7 aws 12\n *\n * The note lists types by count, biggest first, and elides rather than wraps \u2014\n * `render.ts` never wraps a row. Wired into the doctor card by T1.5; kept here\n * so the counts and the way they are said stay in one file.\n */\nexport function redactionRow(\n c: RedactionCounts,\n t: Theme = new Theme(),\n noteWidth = 43,\n): Row {\n const parts = SECRET_TYPES.filter((k) => (c.byType[k] ?? 0) > 0)\n .sort((a, b) => (c.byType[b] ?? 0) - (c.byType[a] ?? 0))\n .map((k) => `${k} ${fmt.num(c.byType[k] ?? 0)}`);\n const note = parts.length === 0\n ? 'nothing matched \u2014 index holds no secrets'\n : fmt.joinFit(parts, noteWidth, ` ${t.mid} `, t.ellip);\n return {\n label: 'secrets masked',\n value: fmt.num(c.total),\n note,\n tone: c.total > 0 ? 'ok' : 'dim',\n };\n}\n\n/** One plain line, for logs and for `doctor` in a non-card context. */\nexport function redactionLine(c: RedactionCounts, t: Theme = new Theme()): string {\n const row = redactionRow(c, t, Math.max(20, t.width - 30));\n return `${row.label.padEnd(22)}${(row.value ?? '').padStart(7)} ${t.dim(row.note ?? '')}`;\n}\n\n// ---------------------------------------------------------------- internals\n\nfunction protectedSpans(text: string): Span[] {\n const spans: Span[] = [];\n const patterns = [MASK_RE, ...ALLOW_SPANS];\n for (const p of patterns) {\n const rx = new RegExp(p.source, p.flags.includes('g') ? p.flags : p.flags + 'g');\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n if (m[0].length === 0) { rx.lastIndex++; continue; }\n spans.push({ start: m.index, end: m.index + m[0].length });\n }\n }\n return spans;\n}\n\nfunction isClaimed(claimed: Uint8Array, s: Span): boolean {\n for (let i = s.start; i < s.end; i++) if (claimed[i]) return true;\n return false;\n}\n\nfunction claim(claimed: Uint8Array, s: Span): void {\n const end = Math.min(s.end, claimed.length);\n for (let i = Math.max(0, s.start); i < end; i++) claimed[i] = 1;\n}\n\n/** Legacy projections have no immutable text-hash contract; mask on public read.\n * Canonical evidence/notes must instead refuse an unsafe old immutable value.\n */\nexport function redactLegacyProjection<T>(value:T):T{\n const visit=(input:unknown):{value:unknown;changed:boolean}=>{\n if(typeof input==='string'){const clean=redact(input).text;return {value:clean,changed:clean!==input};}\n if(Array.isArray(input)){const items=input.map(visit);return {value:items.map(item=>item.value),changed:items.some(item=>item.changed)};}\n if(input&&typeof input==='object'&&Object.getPrototypeOf(input)===Object.prototype){const output:Record<string,unknown>={};let changed=false;for(const [key,child] of Object.entries(input)){const result=visit(child);output[key]=result.value;changed ||= result.changed;}if(changed){if('redacted' in output)output.redacted=true;if('text' in output&&'match' in output)output.match=null;output.redactionRefreshed=true;}return {value:output,changed};}\n return {value:input,changed:false};\n };return visit(value).value as T;\n}\n", "import process from 'node:process';\n\n/**\n * The terminal design system, in code (plans/05-SHAREABLE-EXPERIENCE.md).\n *\n * Rules this module enforces so no verb can break them:\n * - never more than three colours on screen: accent, warn, ok. Everything\n * else is `dim` or default.\n * - NO_COLOR and --no-color are honoured; a non-TTY stdout is never coloured.\n * - --ascii replaces every non-ASCII glyph, so the output survives a terminal\n * with no unicode font and a screenshot taken on Windows. Two mechanisms,\n * because one was demonstrably forgettable: {@link Theme.g} picks the\n * fallback where the glyph is chosen, and {@link Theme.asciiLine} folds\n * whatever still got through \u2014 an em dash typed into a note, a `\u00B7` an\n * adapter wrote, an emoji in someone's own prompt. `render.ts` runs every\n * line it emits through the fold, so no verb can opt out by forgetting.\n */\n\nexport interface ThemeOptions {\n color?: boolean;\n ascii?: boolean;\n width?: number;\n}\n\nconst CSI = '\\u001b[';\n\nexport class Theme {\n readonly color: boolean;\n readonly ascii: boolean;\n readonly width: number;\n\n constructor(opts: ThemeOptions = {}) {\n this.color = opts.color ?? detectColor();\n this.ascii = opts.ascii ?? detectAscii();\n this.width = opts.width ?? detectWidth();\n }\n\n private wrap(code: string, s: string): string {\n return this.color ? `${CSI}${code}m${s}${CSI}0m` : s;\n }\n\n /** The single most important number on the screen. Exactly one per card. */\n accent(s: string): string { return this.wrap('38;5;209', s); }\n /** Urgency: something is about to be lost. */\n warn(s: string): string { return this.wrap('38;5;214', s); }\n /** Done, saved, safe. */\n ok(s: string): string { return this.wrap('38;5;71', s); }\n /** Secondary text: units, notes, sources. */\n dim(s: string): string { return this.wrap('2', s); }\n bold(s: string): string { return this.wrap('1', s); }\n\n /** Pick a glyph, with an ASCII fallback for --ascii / non-unicode terminals. */\n g(unicode: string, fallback: string): string {\n return this.ascii ? fallback : unicode;\n }\n\n get arrow(): string { return this.g('\u2192', '->'); }\n get mid(): string { return this.g('\u00B7', '.'); }\n get sep(): string { return this.g('\u00B7', '|'); }\n get ellip(): string { return this.g('\u2026', '...'); }\n get star(): string { return this.g('\u2605', '*'); }\n get le(): string { return this.g('\u2264', '<='); }\n get bullet(): string { return this.g('\u2022', '-'); }\n /** The em dash that stands in for \"no number here\". */\n get dash(): string { return this.g('\u2014', '-'); }\n\n /**\n * Fold one rendered line to pure ASCII, when `--ascii` is on.\n *\n * Applied at the very end, after the line has been fitted to the terminal\n * width, so **every substitution is exactly one character wide or narrower**.\n * That is the whole design constraint: `\u2026` \u2192 `...` here would push a line\n * that just fitted 80 columns to 82. The three-character ellipsis comes from\n * {@link ellip}, which the width arithmetic sees; this is only the net.\n */\n asciiLine(s: string): string {\n return this.ascii ? toAscii(s) : s;\n }\n\n /** Visible width, ignoring ANSI escapes. */\n static len(s: string): number {\n return stripAnsi(s).length;\n }\n}\n\n/**\n * The glyphs the design system uses, and their one-character ASCII stand-ins.\n * Anything not listed is decomposed (`\u00E9` \u2192 `e`) and, failing that, becomes a\n * single `?` \u2014 never silently dropped, because a vanished character is a\n * vanished fact.\n */\nconst ASCII_FOLD: Record<string, string> = {\n '\u2026': '.', '\u00B7': '.', '\u2022': '*', '\u2027': '.', '\u2219': '.',\n '\u2014': '-', '\u2013': '-', '\u2012': '-', '\u2212': '-', '\u2015': '-',\n '\u2192': '>', '\u21D2': '>', '\u2190': '<', '\u21D0': '<', '\u2191': '^', '\u2193': 'v',\n '\u2264': '<', '\u2265': '>', '\u2260': '!', '\u00B1': '~', '\u00D7': 'x', '\u00F7': '/',\n '\u2605': '*', '\u2606': '*', '\u2713': 'v', '\u2714': 'v', '\u2717': 'x', '\u2718': 'x',\n '\u2039': '<', '\u203A': '>', '\u00AB': '<', '\u00BB': '>',\n '\u201C': '\"', '\u201D': '\"', '\u201E': '\"', '\u2018': \"'\", '\u2019': \"'\", '\u201A': \"'\",\n '\u2588': '#', '\u2587': '#', '\u2593': '#', '\u2592': '+', '\u2591': '.', '\u25A0': '#', '\u25A1': '.',\n '\u2502': '|', '\u2500': '-', '\u250C': '+', '\u2510': '+', '\u2514': '+', '\u2518': '+', '\u251C': '+',\n '\u2524': '+', '\u252C': '+', '\u2534': '+', '\u253C': '+', '\u00B0': 'o', '\u00A7': 'S', '\u00B6': 'P',\n '\\u00a0': ' ', '\\u2007': ' ', '\\u2009': ' ', '\\u202f': ' ', '\\ufeff': '',\n};\n\n/**\n * Every non-ASCII code point replaced by one that is, without ever making the\n * string longer (measured in characters, which is what a terminal column is).\n * Surrogate pairs count as the one character they display as.\n */\nexport function toAscii(s: string): string {\n // eslint-disable-next-line no-control-regex\n if (!/[^\\x00-\\x7F]/.test(s)) return s;\n let out = '';\n for (const ch of s) {\n if (ch.charCodeAt(0) < 128 && ch.length === 1) { out += ch; continue; }\n const mapped = ASCII_FOLD[ch];\n if (mapped !== undefined) { out += mapped; continue; }\n // `\u00E9` is `e` plus a combining acute; drop the accent and keep the letter.\n const bare = ch.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '');\n // eslint-disable-next-line no-control-regex\n out += bare.length === 1 && !/[^\\x00-\\x7F]/.test(bare) ? bare : '?';\n }\n return out;\n}\n\nconst ANSI_RE = new RegExp('\\\\u001b\\\\[[0-9;]*m', 'g');\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '');\n}\n\nfunction detectColor(): boolean {\n if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') return false;\n if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0') return true;\n if (process.env.TERM === 'dumb') return false;\n return Boolean(process.stdout.isTTY);\n}\n\nfunction detectAscii(): boolean {\n if (process.env.POTSHERD_ASCII === '1') return true;\n const enc = `${process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? ''}`;\n if (enc && !/utf-?8/i.test(enc)) return true;\n return false;\n}\n\nfunction detectWidth(): number {\n const cols = process.stdout.columns;\n if (!cols || cols < 40) return 80;\n return Math.min(cols, 100);\n}\n", "/**\n * L2 redaction \u2014 the rule table.\n *\n * ## Provenance (read this before adding a rule)\n *\n * `plans/03-ARCHITECTURE.md` \u00A75 and the reuse table in\n * `plans/02-STRATEGY-AND-VIRALITY.md` are explicit: **port rules, do not write\n * regexes from memory**. Every pattern below is a port of a published,\n * MIT-licensed detection rule, and each rule names its upstream rule id in\n * `source` and in the comment above it.\n *\n * Upstreams:\n *\n * gitleaks \u2014 https://github.com/gitleaks/gitleaks\n * rule pack: `cmd/generate/config/rules/*.go`, published as\n * `config/gitleaks.toml`.\n * Copyright (c) 2019 Zachary Rice. Licensed under the MIT License.\n *\n * secretlint \u2014 https://github.com/secretlint/secretlint\n * rule pack: `@secretlint/secretlint-rule-preset-recommend`, which bundles\n * `-rule-aws`, `-rule-gcp`, `-rule-github`, `-rule-slack`, `-rule-npm`,\n * `-rule-privatekey`, `-rule-basicauth`, `-rule-sendgrid`, `-rule-shopify`.\n * Copyright (c) 2020 Secretlint. Licensed under the MIT License.\n *\n * Neither project's *runtime* is a dependency. secretlint's engine is async,\n * plugin-loading and file-oriented; this module has to be pure, synchronous and\n * cheap enough to run over the whole corpus during `potsherd index`. What is\n * taken is the rule knowledge \u2014 the part that must not be invented. See\n * the header of every rule below. The `NOTICE` entry for both packs lands with\n * T1.5, when this module is first wired into the index.\n *\n * ## What a rule is\n *\n * A scanner over a string returning the spans to mask, a `type` that appears in\n * the mask, and a stable `id`. Rules are applied in array order and the first\n * rule to claim a span wins (see `redact.ts`), so the order here is the\n * precedence order: key material, vendor tokens, credentials in urls, the\n * generic `KEY=` assignment, entropy last.\n *\n * `type` deliberately names a *family* (`aws`, `github`) and not the rule\n * (`aws-access-key-id`): it is user-visible inside the mask, so it stays short,\n * stable and legible in a search result. The rule id rides along on the hit,\n * for `doctor` and for debugging a false positive.\n */\n\n/** The family name that appears in `\u2039redacted:<type>:<sha8>\u203A`. */\nexport type SecretType =\n | 'aws'\n | 'gcp'\n | 'github'\n | 'slack'\n | 'stripe'\n | 'openai'\n | 'anthropic'\n | 'npm'\n | 'jwt'\n | 'private-key'\n | 'basic-auth'\n | 'generic'\n | 'entropy';\n\n/** Every type, in the order `doctor` reports them. */\nexport const SECRET_TYPES: readonly SecretType[] = [\n 'aws',\n 'gcp',\n 'github',\n 'slack',\n 'stripe',\n 'openai',\n 'anthropic',\n 'npm',\n 'jwt',\n 'private-key',\n 'basic-auth',\n 'generic',\n 'entropy',\n] as const;\n\n/** One span of text a rule wants masked. */\nexport interface RuleMatch {\n start: number;\n end: number;\n value: string;\n}\n\nexport interface Rule {\n /** Stable id, reported on the hit and used in tests. */\n id: string;\n type: SecretType;\n /** Upstream rule this was ported from, with its licence. */\n source: string;\n /** Pure: same input, same output, no state carried between calls. */\n scan(text: string): RuleMatch[];\n}\n\n// ---------------------------------------------------------------- entropy\n\n/**\n * Shannon entropy in bits per character. `03` \u00A75 fixes the threshold at 4.5\n * over tokens of \u2265 20 characters.\n *\n * Worth knowing before either number is tuned: entropy measured on a sample of\n * length n cannot exceed log2(n), so a 20-character token can never reach 4.5\n * (log2(20) = 4.32) and nothing shorter than 23 characters can trip this rule\n * at all. That is why 40-char hex git shas (alphabet cap 4.0) and uuids pass\n * through untouched \u2014 the threshold in `03` is self-limiting by design.\n */\nexport function shannonEntropy(s: string): number {\n const n = s.length;\n if (n === 0) return 0;\n const counts = new Map<string, number>();\n for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);\n let h = 0;\n for (const c of counts.values()) {\n const p = c / n;\n h -= p * Math.log2(p);\n }\n return h;\n}\n\nexport const ENTROPY_MIN_LENGTH = 20;\nexport const ENTROPY_THRESHOLD = 4.5;\n\n// ---------------------------------------------------------------- allowlists\n\n/**\n * Spans that are never a secret and must not be scanned at all. Ported in\n * spirit from gitleaks' `[[rules.allowlist]] regexes` and secretlint's `allows`\n * option (both MIT).\n *\n * A base64 data URI is the worst false positive in a coding transcript: an\n * inlined PNG is tens of kilobytes of maximum-entropy base64 that no rule could\n * tell from a key. It is excluded by construction rather than by lowering a\n * threshold that would then start missing real keys.\n */\nexport const ALLOW_SPANS: RegExp[] = [\n // data: URIs \u2014 `data:image/png;base64,iVBORw0KGgo\u2026`\n /\\bdata:[a-zA-Z0-9!#$&^_.+-]*(?:\\/[a-zA-Z0-9!#$&^_.+-]*)?(?:;[a-zA-Z0-9-]+=[^;,\\s]*)*;base64,[A-Za-z0-9+/=]{20,}(?:\\s+[A-Za-z0-9+/=]{20,})*/g,\n // Subresource Integrity \u2014 `integrity=\"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9\u2026\"`\n /\\bsha(?:256|384|512)-[A-Za-z0-9+/]{20,}={0,3}/g,\n];\n\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\nconst HEX_RE = /^[0-9a-fA-F]+$/;\nconst NUMERIC_RE = /^[0-9_+-]+$/;\n\n// -------------------------------------------------- entropy-rule exclusions\n//\n// Each of these answers a false-positive class *measured* on the reference\n// corpus by `scripts/redaction-benchmark.mjs`, and each is named and commented\n// so a future reader can audit \u2014 or delete \u2014 one of them on its own merits.\n//\n// The load-bearing property of all of them: they apply **only to a bare token\n// the entropy rule found lying in the text with no context**. A value that is\n// assigned to a secret-named key, sent in an `Authorization` header or put in\n// a url's userinfo is claimed by a rule that runs earlier and never consults\n// this list. So \"exclude uuids\" cannot let `API_KEY=<uuid>` through, and\n// \"exclude `toolu_\u2026`\" cannot let `ANTHROPIC_API_KEY=toolu_\u2026` through. Both are\n// planted cases in `tests/fixtures/secrets/planted.jsonl`.\n\n/**\n * **E1 \u2014 minted object ids.** Model apis and agent harnesses stamp every\n * message, request, tool use and run with a random id under a fixed prefix.\n * They are the densest high-entropy shape in an agent transcript by an order\n * of magnitude \u2014 `toolu_014ZfaccgxvcYNpcTLq8qvkR` and its kin \u2014 and none of\n * them is a credential: they are handed out in api *responses*, they appear in\n * public logs, and they authorise nothing.\n *\n * Prefixes, and who mints them:\n * toolu_ srvtoolu_ msg_ req_ anthropic messages api\n * chatcmpl- fc_ call_ run_ step_\n * thread_ asst_ resp_ evt_ openai\n * exec- exec_ agent- sess_ session_ agent harnesses (claude code, codex)\n * task_ job_ turn_ conv_ snapshot- harness bookkeeping\n *\n * Deliberately *not* here: `sk_`, `rk_`, `ghp_`, `xoxb-`, `npm_`, `AKIA`,\n * `sk-ant-`, `tvly-` \u2014 every one of those prefixes means the opposite.\n */\nconst MINTED_ID_RE =\n /^(?:toolu|srvtoolu|msg|req|resp|call|fc|run|step|thread|asst|evt|sess|session|exec|job|task|turn|conv|agent|snapshot|chatcmpl)[-_]/i;\n\n/**\n * **E5 \u2014 ULIDs.** 26 characters of Crockford base32, the first 10 encoding a\n * millisecond timestamp. log2(26) = 4.70, so a ULID can and does clear the 4.5\n * bar. Sortable ids, not secrets; the alphabet excludes I, L, O and U on\n * purpose, which is what makes the shape recognisable.\n */\nconst ULID_RE = /^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/;\n\n/**\n * **E6 \u2014 prose wearing a token's clothes.** The single largest surviving false\n * positive on the reference corpus once images were elided: url slugs.\n *\n * \u2026%2Fy-combinator_reducto-has-just-raised-a-75m-series-b-activity-7383909473913880576-ba7M\n *\n * That is 87 characters over a wide alphabet, so its Shannon entropy is 4.9 \u2014\n * comfortably \"random\" by the measure in `03` \u00A75 \u2014 and it is a LinkedIn\n * permalink. Shannon entropy on a single short sample cannot tell *random*\n * from *varied*, and English is very varied.\n *\n * What separates them is **runs**. A base64 or base62 credential draws each\n * character independently, so a run of 7 consecutive same-case letters has\n * probability \u2248 (26/64)^7 \u2248 1 in 900 per position; two disjoint such runs in\n * one 40-character token is well under 1%. English words are nothing but such\n * runs \u2014 `combinator`, `activity`, `whatsapp`, `killmonger`.\n *\n * So: two runs of \u2265 7 same-case letters, or one run of \u2265 12, and the token is\n * text. Both numbers were checked against the corpus rather than chosen: at\n * \u2265 7/\u00D72 every tavily key, every planted secret and every base64 fixture value\n * survives (their longest same-case run is 4), and the slug class disappears.\n */\nconst SAMECASE_RUN_MIN = 7;\nconst SAMECASE_RUNS_NEEDED = 2;\nconst SAMECASE_RUN_ALONE = 12;\n\nfunction looksLikeProse(token: string): boolean {\n let long = 0;\n for (const run of token.match(/[a-z]+|[A-Z]+/g) ?? []) {\n if (run.length >= SAMECASE_RUN_ALONE) return true;\n if (run.length >= SAMECASE_RUN_MIN) long += 1;\n }\n return long >= SAMECASE_RUNS_NEEDED;\n}\n\n/**\n * **E7 \u2014 alphabet constants.** `0123456789ABCDEFGHJKMNPQRSTVWXYZ` is the\n * Crockford base32 table; every base32/base58/base62 encoder in every codebase\n * declares one, and with no repeated character it scores a perfect log2(n)\n * entropy \u2014 the highest possible.\n *\n * The test is exactly \"no character occurs twice\". Drawing 24 characters from\n * a 62-character alphabet without a single repeat happens with probability\n * \u2248 1%, and from base64url's 64 with probability \u2248 1.4%; combined with the\n * 24-character floor and with the fact that a credential in any real context\n * is claimed by an earlier rule, this is a safe trade for a class that is\n * otherwise permanently unmaskable-looking.\n */\nfunction looksLikeAlphabetConstant(token: string): boolean {\n return token.length >= 24 && new Set(token).size === token.length;\n}\n\n/**\n * Placeholder values. Ported from gitleaks' `stopwords` list and secretlint's\n * dummy-value handling, trimmed to the ones that actually occur in coding\n * transcripts. A value matching this is documentation, not a credential.\n */\nconst PLACEHOLDER_RE =\n /(?:^|[^a-z0-9])(?:x{3,}|your|my[-_]?(?:key|token|secret|pass)|example|sample|dummy|fake|mock|placeholder|change[-_]?(?:me|it|this)|replace[-_]?me|insert|todo|fixme|redacted|hidden|omitted|elided|not[-_]?real|no[-_]?such|hunter2|password|passwd|secret|token|apikey|api[-_]key|abcdef|123456|s3cret|letmein|foobar|lorem|ipsum)(?:$|[^a-z0-9])/i;\n\n/** `${VAR}`, `{{var}}`, `%(var)s`, `<%= x %>`, `<your-key>`, `$VAR` \u2026 */\nconst INTERPOLATION_RE = /\\$\\{|\\{\\{|%\\(|<%|^\\$[A-Za-z_(]|^<|^\\{|\\}$|^%[A-Za-z(]/;\n\n/** A reference to a value rather than the value: `process.env.X`, `cfg.token`. */\nconst REFERENCE_RE =\n /^(?:process\\.env|import\\.meta\\.env|os\\.environ|System\\.getenv|Deno\\.env|env|ENV|config|conf|cfg|settings|opts|options|args|argv|params|props|state|data|input|payload|body|req|res|ctx|context|self|this|that|obj|row|item|user|account|creds|credentials|secrets|vault|store|keychain)\\b\\s*[.[(]/;\n\n/** A bare word with no digits \u2014 `hashedPassword`, `MY_SECRET`, `undefined`. */\nconst WORDY_IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z_$]*$/;\n\n/**\n * A dotted identifier chain \u2014 `crypto.randomBytes`, `formData.password`,\n * `settings.auth.token`. Code reaching for a value, not the value. Base64,\n * base64url and hex credentials never contain a `.`, and the ones that do\n * (jwts) have a rule of their own that runs first.\n */\nconst DOTTED_CHAIN_RE = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\\.[A-Za-z_$][A-Za-z0-9_$]*)+$/;\n\n/** A url or a filesystem path, not a credential. */\nconst PATHISH_RE = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\.{0,2}\\/|~\\/|[A-Za-z]:\\\\)/;\n\n/** Syntax that means the capture ran into code, not into a credential. */\nconst CODEY_RE = /[<>{}[\\]()|\\\\;,&?!*\"'`]/;\n\n/** The mask itself, so a second pass recognises its own output. */\nexport const MASK_FRAGMENT_RE = /\u2039redacted:/;\n\n/** English words ending in a keyword that never name a secret. */\nconst NAME_STOPWORDS = new Set([\n 'monkey',\n 'donkey',\n 'turkey',\n 'whiskey',\n 'jockey',\n 'hockey',\n 'lackey',\n 'mickey',\n 'malarkey',\n 'hotkey',\n 'sortkey',\n 'oauth',\n]);\n\n/**\n * Does this identifier name a secret? `apiKey`, `AWS_SECRET_ACCESS_KEY`,\n * `db.password`, `client_secret` yes; `tokenizer`, `keyboard`, `monkey` no.\n *\n * Ported from the keyword half of gitleaks' `generic-api-key` and tightened:\n * that rule allows the keyword anywhere inside a 50-character identifier, which\n * flags every `tokenizer:` and `keyboardShortcut:` line in a transcript. Here\n * the keyword has to be the identifier's last segment, splitting on `_ - . $`\n * and on camelCase humps.\n */\nexport function nameLooksLikeSecret(name: string): boolean {\n const segments = name\n .split(/[^A-Za-z0-9]+/)\n .flatMap((part) => part.split(/(?<=[a-z0-9])(?=[A-Z])/))\n .filter(Boolean);\n const last = segments[segments.length - 1];\n if (!last) return false;\n const lower = last.toLowerCase();\n if (NAME_STOPWORDS.has(lower)) return false;\n return /(?:key|token|secret|password|passwd|pwd|credential|auth)s?$/.test(lower);\n}\n\n/**\n * Is this assignment's value plausibly a real credential?\n *\n * The generic `KEY=` rule is where false positives come from, because every\n * codebase assigns to something called `token`. Everything rejected here is\n * something transcripts are full of: env lookups, template interpolations,\n * references to another variable, documentation placeholders, type\n * annotations, version numbers, paths.\n */\nexport function valueLooksLikeSecret(value: string): boolean {\n const v = value.trim();\n if (v.length < 10 || v.length > 200) return false;\n if (/\\s/.test(v)) return false;\n if (MASK_FRAGMENT_RE.test(v)) return false;\n if (CODEY_RE.test(v)) return false;\n if (INTERPOLATION_RE.test(v)) return false;\n if (REFERENCE_RE.test(v)) return false;\n if (DOTTED_CHAIN_RE.test(v)) return false;\n if (PATHISH_RE.test(v)) return false;\n if (NUMERIC_RE.test(v)) return false;\n if (PLACEHOLDER_RE.test(v)) return false;\n // A bare word with no digits is a variable name or a sentence fragment, not\n // a 32-character credential.\n if (WORDY_IDENTIFIER_RE.test(v) && shannonEntropy(v) < 4.0) return false;\n // Filler: `****`, `------`, `0000000000`.\n if (new Set(v).size <= 2) return false;\n // gitleaks' generic-api-key requires 3.5 bits on the captured value. 3.2\n // here: potsherd masks a token in an index rather than failing a build, so a\n // marginal hit costs one unreadable word in a search result and a marginal\n // miss costs a leaked credential.\n if (shannonEntropy(v) < 3.2) return false;\n return true;\n}\n\n/**\n * Entropy-rule allowlist: shapes that are high-entropy but never secret.\n *\n * Every `return false` is an exclusion rule with a letter, defined above with\n * the class it was measured against. Read the block comment there before\n * adding, removing or relaxing one.\n *\n * This is consulted **only** by the bare-token entropy rule. It is not part of\n * `valueLooksLikeSecret`, so nothing here can excuse a value that appears in a\n * credential-shaped position.\n */\nexport function entropyCandidateAllowed(token: string): boolean {\n if (token.length < ENTROPY_MIN_LENGTH) return false;\n // E2 \u2014 uuids. Session ids, request ids, trace ids. Capped at 4.0 bits by\n // their alphabet anyway; excluded explicitly so the intent is readable.\n if (UUID_RE.test(token)) return false;\n // E2b \u2014 a uuid under a prefix: `exec-<uuid>`, `agent-<uuid>`, `snapshot-\u2026`.\n if (UUID_RE.test(token.replace(/^[A-Za-z][A-Za-z0-9]{0,15}[-_]/, ''))) return false;\n // E3 \u2014 hex digests: git sha1s, sha256 sums, md5s, content hashes.\n if (HEX_RE.test(token)) return false;\n // E4 \u2014 a hex digest under a prefix (`sha256-\u2026` without the SRI base64 body,\n // `blake3-\u2026`, `md5-\u2026`). The base64 SRI form is an ALLOW_SPAN, above.\n if (/^(?:sha1|sha256|sha384|sha512|md5|blake3|crc32|xxh64)[-_:]/i.test(token)) return false;\n if (NUMERIC_RE.test(token)) return false;\n if (MASK_FRAGMENT_RE.test(token)) return false;\n if (PLACEHOLDER_RE.test(token)) return false;\n if (MINTED_ID_RE.test(token)) return false; // E1\n if (ULID_RE.test(token)) return false; // E5\n if (looksLikeProse(token)) return false; // E6\n if (looksLikeAlphabetConstant(token)) return false; // E7\n return true;\n}\n\n// ---------------------------------------------------------------- machinery\n\ninterface RegexRuleOptions {\n /** Capture group holding the bytes to mask. 0 = the whole match. */\n group?: number;\n /** Reject a candidate; returning false leaves the text untouched. */\n validate?: (value: string, m: RegExpExecArray) => boolean;\n}\n\n/** Build a scanning rule from one global regex. */\nfunction regexRule(\n id: string,\n type: SecretType,\n source: string,\n re: RegExp,\n opts: RegexRuleOptions = {},\n): Rule {\n const group = opts.group ?? 0;\n return {\n id,\n type,\n source,\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n // A fresh regex per scan: a module-level `lastIndex` is shared state and\n // this module promises purity.\n const rx = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n if (m[0].length === 0) { rx.lastIndex++; continue; }\n const value = group === 0 ? m[0] : m[group];\n if (value === undefined || value.length === 0) continue;\n if (opts.validate && !opts.validate(value, m)) continue;\n const offset = group === 0 ? 0 : m[0].indexOf(value);\n if (offset < 0) continue;\n out.push({ start: m.index + offset, end: m.index + offset + value.length, value });\n }\n return out;\n },\n };\n}\n\n// ---------------------------------------------------------------- the rules\n\n/**\n * The generic `(KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]` rule from `03` \u00A75, given the\n * shape of gitleaks' `generic-api-key`.\n *\n * It is written as a scanner rather than one regex for two reasons. Speed: a\n * pattern of the form `identifier{0,48}(keyword)[:=]` has to be retried at\n * every letter of a 10 MB corpus, while anchoring on the literal keyword lets\n * the engine skip. Correctness: only the *value* is masked, never the name, so\n * `TOKEN=\u2039redacted:generic:\u2026\u203A` still tells a reader which variable leaked.\n */\nconst GENERIC_ANCHOR =\n /(?:key|token|secret|password|passwd|pwd|credential|auth)s?[\"']?[ \\t]*(?::=|=>|[:=])/gi;\n\nconst GENERIC_VALUE =\n // The bare alternative stops at a backslash on purpose: transcripts carry\n // json-escaped text, where `TOKEN=abc\\nNEXT=\u2026` is one line and the `\\n` is\n // two literal characters. Without this the capture swallows the rest of the\n // record and the value is thrown out as code.\n /[ \\t]*(?:\"([^\"\\r\\n]{10,200})\"|'([^'\\r\\n]{10,200})'|`([^`\\r\\n]{10,200})`|([^\\s\"'`,;)\\](}>\\\\]{10,200}))/y;\n\nconst NAME_CHAR_RE = /[A-Za-z0-9_$.-]/;\n\nconst genericAssignmentRule: Rule = {\n id: 'generic-assignment',\n type: 'generic',\n source: '03 \u00A75, given the shape of gitleaks generic-api-key (MIT)',\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n const anchor = new RegExp(GENERIC_ANCHOR.source, GENERIC_ANCHOR.flags);\n let m: RegExpExecArray | null;\n while ((m = anchor.exec(text)) !== null) {\n const opEnd = m.index + m[0].length;\n const opLen = /(?::=|=>)$/.test(m[0]) ? 2 : 1;\n const before = text[opEnd - opLen - 1] ?? '';\n // `==`, `===`, `!=`, `<=`, `>=`, `+=` are comparisons and compound\n // assignment, not `TOKEN=\u2026`.\n if (text[opEnd] === '=' || (opLen === 1 && /[!<>+\\-*/%&|^=]/.test(before))) continue;\n\n // Walk back over the identifier the keyword ends: `AWS_SECRET_ACCESS_KEY`.\n const keywordEnd = m.index + m[0].replace(/[\"']?[ \\t]*(?::=|=>|[:=])$/, '').length;\n let nameStart = m.index;\n while (nameStart > 0 && NAME_CHAR_RE.test(text[nameStart - 1] ?? '')) nameStart--;\n const name = text.slice(nameStart, keywordEnd);\n if (!nameLooksLikeSecret(name)) continue;\n\n GENERIC_VALUE.lastIndex = opEnd;\n const v = GENERIC_VALUE.exec(text);\n if (!v) continue;\n const value = v[1] ?? v[2] ?? v[3] ?? v[4];\n if (value === undefined || !valueLooksLikeSecret(value)) continue;\n const start = v.index + v[0].lastIndexOf(value);\n out.push({ start, end: start + value.length, value });\n anchor.lastIndex = start + value.length;\n }\n return out;\n },\n};\n\n/** Explicit socket-auth command arguments are credential context, not hashes. */\nconst socketAuthRule:Rule={\n id:'socket-auth-argument',type:'generic',source:'03 \u00A75 credential context',\n scan(text:string):RuleMatch[]{const out:RuleMatch[]=[];const anchor=/(?:^|[\\s\"'`])--socket-auth[\"']?(?:[ \\t]*=[ \\t]*|[ \\t]+)/gi;let match:RegExpExecArray|null;\n while((match=anchor.exec(text))!==null){GENERIC_VALUE.lastIndex=anchor.lastIndex;const found=GENERIC_VALUE.exec(text);if(!found)continue;const value=found[1]??found[2]??found[3]??found[4];if(value===undefined||!valueLooksLikeSecret(value))continue;const start=found.index+found[0].lastIndexOf(value);out.push({start,end:start+value.length,value});anchor.lastIndex=start+value.length;}\n return out;}\n};\n\n/**\n * `Authorization: Bearer <token>` \u2014 a credential *context* rather than a\n * credential *shape*.\n *\n * The rule exists to make the entropy exclusions above safe to hold. They all\n * assume that a value in a position that shouts \"credential\" is claimed by an\n * earlier rule; `KEY=`, `?token=` and `https://user:pw@` were already covered,\n * and the http authorization header was the hole. It matters more now than it\n * did before T1.4b: a `Bearer toolu_\u2026`-shaped token is excluded by E1 as a\n * bare token, and must not be excluded here.\n *\n * The name is not masked, only the credential, so a redacted transcript still\n * says which scheme was used.\n */\nconst BEARER_RE =\n /(?:^|[^A-Za-z0-9_-])(?:Bearer|Token|ApiKey|Api-Key|Basic|DPoP)[ \\t]+([A-Za-z0-9+/._~-]{16,512}={0,2})/g;\n\nconst bearerRule: Rule = regexRule(\n 'authorization-bearer',\n 'generic',\n '03 \u00A75 (credential context), given the shape of gitleaks generic-api-key (MIT)',\n BEARER_RE,\n {\n group: 1,\n // Same value screen as the `KEY=` rule: `Bearer ${token}`, `Bearer <TOKEN>`\n // and `Bearer your-token-here` are documentation, not credentials.\n validate: (value) => valueLooksLikeSecret(value),\n },\n);\n\n/**\n * The entropy rule from `03` \u00A75 \u2014 \u2265 4.5 bits over tokens of \u2265 20 characters \u2014\n * written as a scanner rather than as one regex.\n *\n * `03` fixes the threshold and the length floor and both are honoured\n * unchanged. What T1.4b changed is **what counts as a token**, because that\n * was never specified and the naive reading was doing the damage:\n *\n * 1. `=` is base64 *padding*, so it is only a token character at the end.\n * Before, `ANTHROPIC_VERTEX_PROJECT_ID=example-project` was one\n * \"token\" \u2014 a variable glued to its value \u2014 and scored 4.7.\n * 2. `/` and `.` remain separators, so a long path or a dotted hostname is\n * not one token. (Unchanged from T1.4; the reasoning is that a real\n * base64 secret containing `/` still leaves a \u2265 23-character run, and 23\n * is the shortest string that can reach 4.5 bits at all.)\n * 3. Transcripts are json-inside-json, so the text often carries a *literal*\n * backslash-n where a newline belongs. `\\ntvly-dev-\u2026` used to yield the\n * token `ntvly-dev-\u2026` \u2014 the same secret with a different first character,\n * and therefore a different sha8 and a different mask. Escape residue is\n * trimmed, which is a correctness fix for the \"same secret, same mask\"\n * guarantee and not only a cosmetic one.\n * 4. Percent-escape residue (`%2F` leaving `2F\u2026`) and leading/trailing\n * separators are trimmed for the same reason.\n *\n * Shape exclusions live in {@link entropyCandidateAllowed}.\n */\nconst ENTROPY_TOKEN = /[A-Za-z0-9+_-]{20,}={0,2}/g;\n\n/** Characters a `\\x` json escape leaves glued to the front of a token. */\nconst ESCAPE_LETTERS = 'ntrbfv';\n\nconst highEntropyRule: Rule = {\n id: 'high-entropy-token',\n type: 'entropy',\n source: '03 \u00A75 (4.5 bits / 20 chars) + gitleaks entropy allowlists (MIT)',\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n const rx = new RegExp(ENTROPY_TOKEN.source, ENTROPY_TOKEN.flags);\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n let start = m.index;\n let value = m[0];\n // `\\n`, `\\t`, `\\r` written literally by an outer json encoder.\n if (start > 0 && text[start - 1] === '\\\\' && ESCAPE_LETTERS.includes(value[0] ?? '')) {\n start += 1;\n value = value.slice(1);\n }\n // `%2F`, `%3D` \u2014 the `%` is a separator, but the two hex digits that\n // complete the escape are not part of the token that follows it.\n if (start > 0 && text[start - 1] === '%' && /^[0-9A-Fa-f]{2}/.test(value)) {\n start += 2;\n value = value.slice(2);\n }\n // Leading and trailing separators belong to the surrounding text.\n const lead = value.length - value.replace(/^[-_+]+/, '').length;\n start += lead;\n value = value.slice(lead).replace(/[-_+]+$/, '');\n\n if (value.length < ENTROPY_MIN_LENGTH) continue;\n if (!entropyCandidateAllowed(value)) continue;\n if (shannonEntropy(value) < ENTROPY_THRESHOLD) continue;\n out.push({ start, end: start + value.length, value });\n }\n return out;\n },\n};\n\nexport const RULES: Rule[] = [\n // ---- key material ------------------------------------------------------\n regexRule(\n // gitleaks `private-key`; secretlint `@secretlint/secretlint-rule-privatekey`.\n // The whole block is masked, header to footer: the base64 body alone would\n // otherwise be shredded into a dozen separate entropy hits.\n 'private-key-block',\n 'private-key',\n 'gitleaks private-key / secretlint-rule-privatekey (MIT)',\n /-----BEGIN[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----[\\s\\S]{0,200000}?-----END[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----/g,\n ),\n regexRule(\n // gitleaks `private-key`, unterminated variant: a transcript often quotes\n // the header and the first body lines and then elides the rest.\n //\n // The body is taken line by line and only where a line is \u2265 20 characters\n // of pure base64, so an unterminated header followed by prose masks the\n // header alone instead of swallowing the sentence after it. The separator\n // class carries the backslash so json-escaped `\\n` works, and it is\n // disjoint from the base64 class, which is what keeps this linear.\n 'private-key-header',\n 'private-key',\n 'gitleaks private-key (MIT)',\n /-----BEGIN[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----(?:[\\r\\n \\t\\\\]+[A-Za-z0-9+/=]{20,})*/g,\n ),\n regexRule(\n // gitleaks `jwt`: three base64url segments, the first two starting `ey`\n // (the base64 of `{\"`). Session transcripts are full of these.\n 'jwt',\n 'jwt',\n 'gitleaks jwt (MIT)',\n /\\bey[A-Za-z0-9_-]{17,}\\.ey[A-Za-z0-9_-]{17,}\\.[A-Za-z0-9_-]{10,}={0,2}/g,\n ),\n\n // ---- vendor tokens -----------------------------------------------------\n regexRule(\n // gitleaks `aws-access-token`; secretlint-rule-aws `AWSAccessKeyID`.\n 'aws-access-key-id',\n 'aws',\n 'gitleaks aws-access-token / secretlint-rule-aws (MIT)',\n /\\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\\b/g,\n ),\n regexRule(\n // secretlint-rule-aws `AWSSecretAccessKey`: a 40-character base64 value\n // bound to an AWS-flavoured name. Typed `aws` and placed before the generic\n // rule so `doctor` reports it as what it is.\n 'aws-secret-access-key',\n 'aws',\n 'secretlint-rule-aws AWSSecretAccessKey (MIT)',\n /aws[_.-]?(?:secret|access)[_.-]?(?:access[_.-]?)?key(?:[_.-]?id)?[\"'\\s]{0,4}[:=][\"'\\s]{0,4}([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])/gi,\n { group: 1 },\n ),\n regexRule(\n // gitleaks `gcp-api-key`; secretlint-rule-gcp `GCPApiKey`.\n 'gcp-api-key',\n 'gcp',\n 'gitleaks gcp-api-key / secretlint-rule-gcp (MIT)',\n /\\bAIza[0-9A-Za-z_-]{35}\\b/g,\n ),\n regexRule(\n // gitleaks `gcp-oauth-client-secret`.\n 'gcp-oauth-client-secret',\n 'gcp',\n 'gitleaks gcp-oauth-client-secret (MIT)',\n /\\bGOCSPX-[a-zA-Z0-9_-]{28}\\b/g,\n ),\n regexRule(\n // gitleaks `github-pat` / `-oauth` / `-app-token` / `-refresh-token`;\n // secretlint-rule-github. ghp_ user, gho_ oauth, ghu_/ghs_ app, ghr_ refresh.\n 'github-token',\n 'github',\n 'gitleaks github-pat / secretlint-rule-github (MIT)',\n /\\bgh[pousr]_[A-Za-z0-9]{36,255}\\b/g,\n ),\n regexRule(\n // gitleaks `github-fine-grained-pat`.\n 'github-fine-grained-pat',\n 'github',\n 'gitleaks github-fine-grained-pat (MIT)',\n /\\bgithub_pat_[0-9a-zA-Z_]{82}\\b/g,\n ),\n regexRule(\n // gitleaks `slack-bot-token` / `-user-token` / `-app-token`;\n // secretlint-rule-slack.\n 'slack-token',\n 'slack',\n 'gitleaks slack-bot-token / secretlint-rule-slack (MIT)',\n /\\bxox[abprs]-[0-9a-zA-Z-]{10,72}\\b/g,\n ),\n regexRule(\n // gitleaks `slack-webhook-url`; secretlint-rule-slack `SlackWebhook`.\n 'slack-webhook',\n 'slack',\n 'gitleaks slack-webhook-url (MIT)',\n /https:\\/\\/hooks\\.slack\\.com\\/(?:services|workflows|triggers)\\/[A-Za-z0-9+/]{6,}\\/[A-Za-z0-9+/]{6,}\\/[A-Za-z0-9+/]{6,}/g,\n ),\n regexRule(\n // gitleaks `stripe-access-token`. `pk_` publishable keys are public by\n // design and are deliberately not matched.\n 'stripe-key',\n 'stripe',\n 'gitleaks stripe-access-token (MIT)',\n /\\b(?:sk|rk)_(?:test|live|prod)_[A-Za-z0-9]{10,99}\\b/g,\n ),\n regexRule(\n // gitleaks `anthropic-api-key`. Must precede the openai rules: both start\n // `sk-`, and whichever rule claims the span first wins.\n 'anthropic-api-key',\n 'anthropic',\n 'gitleaks anthropic-api-key (MIT)',\n /\\bsk-ant-(?:api|admin)[0-9]{2}-[A-Za-z0-9_-]{80,120}\\b/g,\n ),\n regexRule(\n // gitleaks `openai-api-key`: the `T3BlbkFJ` infix is the base64 of\n // \"OpenAI\" and is what makes this rule safe to run over prose.\n 'openai-api-key-project',\n 'openai',\n 'gitleaks openai-api-key (MIT)',\n /\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}T3BlbkFJ[A-Za-z0-9_-]{20,}\\b/g,\n ),\n regexRule(\n // gitleaks `openai-api-key`, legacy 48-character form with no infix.\n 'openai-api-key-legacy',\n 'openai',\n 'gitleaks openai-api-key (MIT)',\n /\\bsk-[A-Za-z0-9]{48}\\b/g,\n ),\n regexRule(\n // gitleaks `npm-access-token`; secretlint-rule-npm.\n 'npm-access-token',\n 'npm',\n 'gitleaks npm-access-token / secretlint-rule-npm (MIT)',\n /\\bnpm_[A-Za-z0-9]{36}\\b/g,\n ),\n\n // ---- credentials in urls -----------------------------------------------\n regexRule(\n // gitleaks `authenticated-url`; secretlint `-rule-basicauth`. Only the\n // password is masked: `postgres://app:\u2039redacted:basic-auth:\u2026\u203A@db:5432/x`\n // still says which host and which user, which is the point of an index that\n // stays searchable by shape.\n 'basic-auth-url',\n 'basic-auth',\n 'gitleaks authenticated-url / secretlint-rule-basicauth (MIT)',\n // The user half is `{0,64}`: `redis://:hunter2@host` has an empty user and\n // is exactly as leaked as the two-part form.\n /\\b[a-zA-Z][a-zA-Z0-9+.-]{1,20}:\\/\\/[^\\s:@/]{0,64}:([^\\s:@/]{1,128})@/g,\n {\n group: 1,\n validate: (value) => {\n if (INTERPOLATION_RE.test(value)) return false;\n if (PLACEHOLDER_RE.test(value)) return false;\n if (MASK_FRAGMENT_RE.test(value)) return false;\n if (/^(?:pass|pw|user|admin|root|test|guest|\\*+|x+|\\d{1,4})$/i.test(value)) return false;\n return true;\n },\n },\n ),\n\n // ---- credential context (03 \u00A75) ----------------------------------------\n bearerRule,\n genericAssignmentRule,\n socketAuthRule,\n\n // ---- entropy (03 \u00A75) ---------------------------------------------------\n // Last, so that anything a named rule understands is reported under its real\n // type and a bare token is the fallback rather than the default.\n highEntropyRule,\n];\n", "/**\n * Binary elision \u2014 the pass that runs **before** the redactor.\n *\n * ## Why this exists\n *\n * T1.4 landed the redactor and `potsherd index --full` promptly reported\n * *165,088 secrets masked* over 1,406 exchanges. Measuring where they were\n * (`scripts/redaction-benchmark.mjs`) settled it: 98.6% were in `tool_calls`,\n * and the single worst tool call was a **589 KB base64 JPEG** pasted into a\n * `Read` result, which alone produced 5,660 entropy hits.\n *\n * That is not a miscalibrated entropy rule. It is a picture. No secret scanner\n * ever written can look at 589 KB of base64 and tell you which 40 characters\n * of it are a credential, because none of them are \u2014 it is a JPEG. The fix is\n * not to make the detector blinder; it is to stop feeding it images.\n *\n * The codex adapter already established the convention for exactly this\n * problem (`adapters/codex.ts`, \"Trap 3\"): a binary payload becomes a short\n * marker, `\u2039elided:image/png:109362 bytes\u203A`. Its regex only recognises\n * `data:\u2026;base64,\u2026` URIs, which is the shape codex writes. Claude Code writes\n * the Anthropic content-block shape instead \u2014\n *\n * [{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"data\":\"/9j/4AAQ\u2026\",\"media_type\":\"image/jpeg\"}}]\n *\n * \u2014 which that regex never sees. This module generalises the convention to\n * both shapes, plus to a bare base64 run that announces itself with a file\n * magic, and is called from `ingest.ts` on the way into the store, before\n * `redactExchange`.\n *\n * ## Why it is safe to run before redaction\n *\n * Every shape elided here is identified by something a *credential never has*:\n * a `data:` URI scheme, an image content-block wrapper, or the base64 of a\n * file-format magic number. A 40-character AWS secret is not a JPEG header,\n * and the {@link MIN_PAYLOAD} floor of 512 base64 characters is far above any\n * credential that has ever been issued. PEM private-key bodies are longer than\n * that but begin `MII\u2026` / `b3Blb\u2026` and carry a `-----BEGIN` header, so they\n * match no magic here and reach the redactor intact \u2014 `tests/redact.test.ts`\n * holds that case.\n *\n * The marker uses the same guillemets as the mask (`\u2039` U+2039, `\u203A` U+203A) and\n * for the same reason: those characters cannot occur in base64, in a shell\n * token or in a json key, so an elision can never be confused for content and\n * a second pass recognises its own output.\n *\n * Elision is **not** redaction and does not pretend to be. It removes bulk\n * that carries no meaning for retrieval; the redactor still runs afterwards\n * over everything that survives, and there is still no `--no-redact` flag.\n */\n\nimport type { Exchange, ExchangeToolCall } from './adapters/types.js';\n\n/** What one pass threw away, so a caller can say it out loud. */\nexport interface Elisions {\n /** Binary payloads replaced by a marker. */\n binaryParts: number;\n /** Characters dropped. */\n charsElided: number;\n}\n\nexport function emptyElisions(): Elisions {\n return { binaryParts: 0, charsElided: 0 };\n}\n\nexport function addElisions(a: Elisions, b: Elisions): Elisions {\n return {\n binaryParts: a.binaryParts + b.binaryParts,\n charsElided: a.charsElided + b.charsElided,\n };\n}\n\n/**\n * The shortest base64 run this module will elide, in characters. 512 base64\n * characters is 384 bytes.\n *\n * Chosen to sit far above every credential shape in `redact-rules.ts` \u2014 the\n * longest is an anthropic key at ~120 characters \u2014 so raising this floor can\n * never be the reason a secret is missed. A \"binary payload\" smaller than this\n * is not worth a marker anyway.\n */\nexport const MIN_PAYLOAD = 512;\n\n/** Matches this module's own marker, so a second pass is a no-op. */\nexport const ELISION_RE = /\u2039elided:[^\u203A]{1,120}\u203A/g;\n\n/**\n * base64 of the first bytes of a file format, longest prefix first.\n *\n * A base64 payload that starts with one of these *is* that file: base64 is a\n * fixed 3-bytes-to-4-characters encoding with no header of its own, so the\n * leading characters are a faithful transcription of the leading bytes, which\n * for every format below is a magic number the format spec mandates.\n *\n * Only formats that actually turn up pasted into an agent transcript are here.\n * Adding one is cheap; guessing one is not, so each names the bytes it encodes.\n */\nconst BASE64_MAGIC: Array<[prefix: string, mime: string, bytes: string]> = [\n ['iVBORw0KGgo', 'image/png', '89 50 4E 47 0D 0A 1A 0A'],\n ['/9j/', 'image/jpeg', 'FF D8 FF (JFIF/Exif SOI)'],\n ['R0lGODdh', 'image/gif', 'GIF87a'],\n ['R0lGODlh', 'image/gif', 'GIF89a'],\n ['Qk0', 'image/bmp', '42 4D (\"BM\")'],\n ['SUkqAA', 'image/tiff', '49 49 2A 00 (little-endian TIFF)'],\n ['TU0AK', 'image/tiff', '4D 4D 00 2A (big-endian TIFF)'],\n ['AAABAA', 'image/x-icon', '00 00 01 00 (ICO)'],\n ['UklGR', 'application/octet-stream', '52 49 46 46 (\"RIFF\" \u2014 webp/wav/avi)'],\n ['JVBERi0', 'application/pdf', '25 50 44 46 2D (\"%PDF-\")'],\n ['UEsDB', 'application/zip', '50 4B 03 04 (\"PK\\\\x03\\\\x04\" \u2014 zip/docx/xlsx)'],\n ['H4sI', 'application/gzip', '1F 8B 08'],\n ['SUQz', 'audio/mpeg', '49 44 33 (\"ID3\")'],\n ['T2dnU', 'application/ogg', '4F 67 67 53 (\"OggS\")'],\n ['d09GRg', 'font/woff', '77 4F 46 46 (\"wOFF\")'],\n ['d09GMg', 'font/woff2', '77 4F 46 32 (\"wOF2\")'],\n ['AAEAAA', 'font/ttf', '00 01 00 00 (TrueType)'],\n ['T1RUTw', 'font/otf', '4F 54 54 4F (\"OTTO\")'],\n];\n\n/** A payload character: base64, plus the `\\/` a json encoder writes for `/`. */\nconst B64_RUN = `(?:[A-Za-z0-9+/=]|\\\\\\\\/)`;\n\n/**\n * A payload, possibly hard-wrapped.\n *\n * Whitespace is tolerated *only between two long chunks*. Allowing it as a\n * plain payload character is the obvious way to write this and it is wrong:\n * `<900 characters of png>\\ndone` is then a single run, and the elision eats\n * the word after the payload. Requiring a continuation to be \u2265 40 characters\n * means prose on the next line ends the run instead of joining it.\n */\nconst B64_BODY = `${B64_RUN}{40,}(?:[\\\\r\\\\n \\\\t]+${B64_RUN}{40,})*`;\n\n/**\n * `data:image/png;base64,\u2026` \u2014 the shape the codex adapter already elides,\n * kept identical here so the two passes agree and the second is a no-op.\n */\nconst DATA_URI = new RegExp(\n `data:([a-zA-Z0-9.+-]+/[a-zA-Z0-9.+-]+)?(?:;[a-zA-Z0-9.+=-]+)*;base64,${B64_BODY}`,\n 'g',\n);\n\n/**\n * The Anthropic / OpenAI image **content block**, as the parser stringifies it\n * into `tool_calls.result`:\n *\n * {\"type\":\"image\",\"source\":{\"type\":\"base64\",\"data\":\"/9j/4AAQ\u2026\",\"media_type\":\"image/jpeg\"}}\n *\n * `media_type` may sit either side of `data` (both orders occur in the real\n * corpus), so the mime is recovered by a second look rather than by trying to\n * write one regex that matches both. The payload key is the union of the keys\n * the shapes in the wild use: `data` (anthropic), `image_data`, `b64_json`\n * (openai images), `base64`.\n *\n * The `\"base64\"` / `media_type` context is *required*: without it this would\n * be \"elide any long string called data\", which would swallow a base64\n * credential posted in a json body. That case is a planted fixture.\n */\nconst CONTENT_BLOCK = new RegExp(\n `\"(?:data|image_data|b64_json|base64)\"\\\\s*:\\\\s*\"(${B64_BODY})\"`,\n 'g',\n);\n\n/** `\"media_type\":\"image/jpeg\"`, `\"mimeType\": \"image/png\"`, `\"type\":\"base64\"`. */\nconst MEDIA_HINT = /\"(?:media_?type|mime_?type|mimeType)\"\\s*:\\s*\"([a-zA-Z0-9.+-]+\\/[a-zA-Z0-9.+-]+)\"|\"type\"\\s*:\\s*\"base64\"/gi;\n\n/** How far either side of a payload a media hint still counts as its own. */\nconst HINT_WINDOW = 200;\n\n/**\n * A bare base64 run that announces itself with a file magic \u2014 a payload pasted\n * without any wrapper at all, which is what `cat image.png | base64` in a Bash\n * tool result looks like.\n *\n * Anchored on the magic prefixes rather than on \"any base64 character\", which\n * is not a nicety: a `{512,}` quantifier over an unanchored character class\n * is retried at every letter of the corpus, and the corpus is 78 MB. With the\n * literal prefixes up front the engine skips to the next possible start.\n */\nconst MAGIC_PREFIXES = BASE64_MAGIC.map(([p]) => p.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&')).join('|');\nconst BARE_RUN = new RegExp(\n `(?<![A-Za-z0-9+/=])(?:${MAGIC_PREFIXES})${B64_BODY}`,\n 'g',\n);\n\ninterface Span {\n start: number;\n end: number;\n mime: string;\n}\n\n/** Strip json escapes and whitespace to get at the payload's real leading bytes. */\nfunction magicOf(payload: string): string | undefined {\n const head = payload.slice(0, 32).replace(/\\\\\\//g, '/').replace(/\\s+/g, '');\n for (const [prefix, mime] of BASE64_MAGIC) if (head.startsWith(prefix)) return mime;\n return undefined;\n}\n\n/** The mime named nearest to `[start,end)`, if the window holds a hint. */\nfunction mimeNear(text: string, start: number, end: number): string | undefined {\n const from = Math.max(0, start - HINT_WINDOW);\n const window = text.slice(from, start) + text.slice(end, Math.min(text.length, end + HINT_WINDOW));\n const rx = new RegExp(MEDIA_HINT.source, MEDIA_HINT.flags);\n let m: RegExpExecArray | null;\n let sawBase64 = false;\n while ((m = rx.exec(window)) !== null) {\n if (m[1]) return m[1];\n sawBase64 = true;\n }\n return sawBase64 ? 'application/octet-stream' : undefined;\n}\n\nfunction collect(re: RegExp, text: string, group: number, decide: (payload: string, start: number, end: number) => string | undefined, out: Span[]): void {\n const rx = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n const payload = group === 0 ? m[0] : m[group];\n if (payload === undefined || payload.length === 0) { rx.lastIndex += 1; continue; }\n const start = m.index + (group === 0 ? 0 : m[0].indexOf(payload));\n const end = start + payload.length;\n const mime = decide(payload, start, end);\n if (mime === undefined) continue;\n out.push({ start, end, mime });\n }\n}\n\n/**\n * Replace every binary payload in `text` with `\u2039elided:<mime>:<n> bytes\u203A`.\n *\n * Idempotent: the marker contains no base64 run of its own, so a second call\n * finds nothing and returns the same string.\n */\nexport function elideBinary(text: string, tally: Elisions = emptyElisions()): string {\n if (typeof text !== 'string' || text.length < MIN_PAYLOAD) return text ?? '';\n // Cheap reject. Every shape below needs a long unbroken base64 run, and\n // that needs at least this much alphabet. Skipping here is what keeps the\n // pass off the 99% of transcript text that is prose and code.\n if (!/[A-Za-z0-9+/]{64}/.test(text)) return text;\n\n const spans: Span[] = [];\n // The regexes only require 40 payload characters so that a hard-wrapped\n // payload still matches as one run; the MIN_PAYLOAD floor is applied here,\n // to the whole run.\n const big = (payload: string) => payload.length >= MIN_PAYLOAD;\n // 1. data: URIs \u2014 mime is in the URI itself.\n collect(DATA_URI, text, 0, (payload) => {\n if (!big(payload)) return undefined;\n const m = /^data:([a-zA-Z0-9.+-]+\\/[a-zA-Z0-9.+-]+)?/.exec(payload);\n return m?.[1] ?? 'application/octet-stream';\n }, spans);\n // 2. image content blocks \u2014 the wrapper must say `base64` or name a mime,\n // otherwise a long value that merely happens to be called `data` is left\n // for the redactor to judge.\n collect(CONTENT_BLOCK, text, 1, (payload, start, end) => {\n if (!big(payload)) return undefined;\n const hint = mimeNear(text, start, end);\n if (hint === undefined) return undefined;\n return magicOf(payload) ?? hint;\n }, spans);\n // 3. bare runs that carry a file magic.\n collect(BARE_RUN, text, 0, (payload) => (big(payload) ? magicOf(payload) : undefined), spans);\n\n if (spans.length === 0) return text;\n\n // First span wins on overlap: a data: URI inside a content block is elided\n // once, as the URI, not twice.\n spans.sort((a, b) => a.start - b.start || b.end - a.end);\n const out: string[] = [];\n let cursor = 0;\n for (const s of spans) {\n if (s.start < cursor) continue;\n out.push(text.slice(cursor, s.start));\n const n = s.end - s.start;\n out.push(`\u2039elided:${s.mime}:${n} bytes\u203A`);\n tally.binaryParts += 1;\n tally.charsElided += n;\n cursor = s.end;\n }\n out.push(text.slice(cursor));\n return out.join('');\n}\n\n/**\n * {@link elideBinary} over every field of an exchange that `03` \u00A75 redacts.\n * Returns a new object; the input is never mutated, because the caller may\n * still be writing the byte-exact archive copy from it.\n */\nexport function elideExchange(ex: Exchange): { exchange: Exchange; elisions: Elisions } {\n const elisions = emptyElisions();\n const one = (s: string): string => elideBinary(s, elisions);\n\n const userText = one(ex.userText);\n const assistantText = one(ex.assistantText);\n const toolCalls: ExchangeToolCall[] = ex.toolCalls.map((tc) => {\n const next: ExchangeToolCall = { ...tc, input: one(tc.input) };\n if (tc.result !== undefined) next.result = one(tc.result);\n return next;\n });\n\n if (elisions.binaryParts === 0) return { exchange: ex, elisions };\n return { exchange: { ...ex, userText, assistantText, toolCalls }, elisions };\n}\n", "import {StringDecoder} from 'node:string_decoder';\nimport {EXCLUSION_MARKERS} from '../markers.js';\ntype ImageBody={frame:Frame;chunks:string[];bytes:number;overflow:boolean};\ntype Frame={path:string[];omitImage:boolean;array:boolean;state:'key'|'keyRequired'|'colon'|'value'|'valueRequired'|'comma';key:string|null;keep:boolean;value:Record<string,unknown>|unknown[]|null};\n/** Validates one complete JSON record while omitting body values, with bounded retained metadata. */\nexport class NativeMetadataProjection {\n private readonly decoder=new StringDecoder('utf8');private frames:Frame[]=[];private root:unknown;private done=false;private mode:'idle'|'string'|'number'|'literal'='idle';private token='';private isKey=false;private keep=false;private escape=false;private unicode='';private markerTail='';private retained=0;private error:string|null=null;private marker=false;private scanString=false;private scanEscape=false;private scanUnicode='';private scanTail='';\n // Defer the producer check until the whole record is known, retaining unknown values only within the shared metadata budget.\n private imageBodies:ImageBody[]=[];private imageCandidate:ImageBody|null=null;private imageBytes=0;\n private trimImages():void{for(let i=this.imageBodies.length-1;i>=0&&this.retained+this.imageBytes>this.maxBytes;i--){const body=this.imageBodies[i]!;this.imageBytes-=body.bytes;body.chunks=[];body.bytes=0;body.overflow=true;}}\n constructor(private readonly maxBytes=8*1024*1024,private readonly harness:string|null=null){}\n private fail(code='native_metadata_invalid'):void{this.error??=code;}\n private add(c:string):void{if(this.keep||this.isKey){this.retained+=Buffer.byteLength(JSON.stringify(c))-2;if(this.retained>this.maxBytes||this.isKey&&this.token.length>32768){this.fail('native_metadata_bytes_limit');return;}this.token+=c;this.trimImages();}if(this.imageCandidate&&!this.imageCandidate.overflow){const bytes=Buffer.byteLength(JSON.stringify(c))-2;this.imageCandidate.bytes+=bytes;this.imageBytes+=bytes;this.imageCandidate.chunks.push(c);this.trimImages();}const searchable=this.markerTail+c;if(EXCLUSION_MARKERS.some(m=>searchable.includes(m)))this.marker=true;this.markerTail=searchable.slice(-256);}\n private expectedValue():boolean{const f=this.frames.at(-1);return f?f.state==='value'||f.state==='valueRequired':!this.done;}\n private imageBody(f:Frame):boolean{return this.harness==='codex'&&f.key==='image_url'&&f.path.length===3&&f.path[0]==='payload'&&f.path[1]==='output'&&f.path[2]==='[]';}\n private retainValue():boolean{const f=this.frames.at(-1);return !f||f.keep&&!(f.key==='content'||f.key==='text'||f.omitImage);}\n private accept(value:unknown):void{if(this.retainValue()){this.retained+=16;this.trimImages();if(this.retained>this.maxBytes){this.fail('native_metadata_bytes_limit');return;}}const f=this.frames.at(-1);if(!f){if(this.done){this.fail();return;}this.root=value;this.done=true;return;}if(f.state!=='value'&&f.state!=='valueRequired'){this.fail();return;}if(f.keep){if(f.array)(f.value as unknown[]).push(value);else if(f.key!==null&&this.retainValue())Object.defineProperty(f.value!,f.key,{value,writable:true,enumerable:true,configurable:true});}f.key=null;f.omitImage=false;f.state='comma';}\n private scalarEnd():void{if(this.mode==='number'){if(!/^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(this.token)){this.fail();return;}this.accept(this.keep?Number(this.token):null);}else if(this.mode==='literal'){if(!['true','false','null'].includes(this.token)){this.fail();return;}this.accept(this.keep?JSON.parse(this.token):null);}this.mode='idle';this.token='';}\n private char(c:string):void{\n if(this.error)return;\n if(this.mode==='string'){\n if(this.unicode){if(!/[0-9a-f]/i.test(c)){this.fail();return;}this.unicode+=c;if(this.unicode.length===5){this.add(String.fromCharCode(parseInt(this.unicode.slice(1),16)));this.unicode='';}return;}\n if(this.escape){this.escape=false;if(c==='u'){this.unicode='u';return;}const decoded:Record<string,string>={'\"':'\"','\\\\':'\\\\','/':'/','b':'\\b','f':'\\f','n':'\\n','r':'\\r','t':'\\t'};if(!(c in decoded)){this.fail();return;}this.add(decoded[c]!);return;}\n if(c==='\\\\'){this.escape=true;return;}if(c==='\"'){if(this.isKey){const f=this.frames.at(-1)!;f.key=this.token;f.state='colon';}else this.accept(this.keep?this.token:null);this.mode='idle';this.token='';this.imageCandidate=null;this.markerTail='';return;}if(c.charCodeAt(0)<32){this.fail();return;}this.add(c);return;\n }\n if(this.mode==='number'||this.mode==='literal'){const allowed=this.mode==='number'?/[0-9eE+.-]/:/[a-z]/;if(allowed.test(c)){if(this.token.length>=256){this.fail('native_metadata_scalar_limit');return;}this.token+=c;return;}this.scalarEnd();if(this.error)return;}\n if(/\\s/.test(c)){if(![' ','\\t','\\r','\\n'].includes(c))this.fail();return;}\n const f=this.frames.at(-1);\n if(c==='\"'){this.isKey=!!f&&!f.array&&(f.state==='key'||f.state==='keyRequired');if(!this.isKey&&!this.expectedValue()){this.fail();return;}if(!this.isKey&&f&&this.imageBody(f)){f.omitImage=true;this.imageCandidate={frame:f,chunks:[],bytes:0,overflow:false};this.imageBodies.push(this.imageCandidate);}this.keep=this.isKey||this.retainValue()&&f?.key!=='message';this.token='';this.markerTail='';this.mode='string';return;}\n if(c==='{'||c==='['){if(!this.expectedValue()||this.frames.length>=128){this.fail('native_metadata_depth_limit');return;}const keep=this.retainValue();this.frames.push({path:f?[...f.path,f.array?'[]':f.key!]:[],omitImage:false,array:c==='[',state:c==='['?'value':'key',key:null,keep,value:keep?(c==='['?[]:{}):null});return;}\n if(c==='}'||c===']'){if(!f||f.array!==(c===']')||!['comma',f.array?'value':'key'].includes(f.state)){this.fail();return;}this.frames.pop();this.accept(f.value);return;}\n if(c===':'){if(!f||f.state!=='colon'){this.fail();return;}f.state='valueRequired';return;}\n if(c===','){if(!f||f.state!=='comma'){this.fail();return;}f.state=f.array?'valueRequired':'keyRequired';return;}\n if(!this.expectedValue()){this.fail();return;}this.keep=this.retainValue();this.token=c;if(c==='-'||/[0-9]/.test(c))this.mode='number';else if(/[tfn]/.test(c))this.mode='literal';else this.fail();\n }\n private scanMarkers(text:string):void{const special=/[\"\\\\]/g;let at=0;const add=(value:string)=>{const combined=this.scanTail+value;if(EXCLUSION_MARKERS.some(m=>combined.includes(m)))this.marker=true;this.scanTail=combined.slice(-256);};while(at<text.length){if(this.scanString&&!this.scanEscape&&!this.scanUnicode){special.lastIndex=at;const hit=special.exec(text),end=hit?.index??text.length;add(text.slice(at,end));at=end;if(at>=text.length)break;}const c=text[at++]!;if(this.scanUnicode){this.scanUnicode+=c;if(this.scanUnicode.length===5){if(/^u[0-9a-f]{4}$/i.test(this.scanUnicode))add(String.fromCharCode(parseInt(this.scanUnicode.slice(1),16)));this.scanUnicode='';}continue;}if(this.scanEscape){this.scanEscape=false;if(c==='u')this.scanUnicode='u';else add(({n:'\\n',r:'\\r',t:'\\t'} as Record<string,string>)[c]??c);continue;}if(c==='\"'){this.scanString=!this.scanString;this.scanTail='';}else if(this.scanString&&c==='\\\\')this.scanEscape=true;}}\n push(bytes:Buffer):void{const text=this.decoder.write(bytes);this.scanMarkers(text);const special=/[\"\\\\\\x00-\\x1f]/g;let at=0;while(at<text.length&&!this.error){if(this.mode==='string'&&!this.escape&&!this.unicode){special.lastIndex=at;const hit=special.exec(text),end=hit?.index??text.length;if(end>at)this.add(text.slice(at,end));at=end;if(at>=text.length)break;}this.char(text[at++]!);}}\n finish():{record:Record<string,unknown>|null;code:string|null;exclusionMarker:boolean}{for(const c of this.decoder.end())this.char(c);if(this.mode==='number'||this.mode==='literal')this.scalarEnd();if(this.mode!=='idle'||this.frames.length||!this.done)this.fail();if(!this.error&&(!this.root||typeof this.root!=='object'||Array.isArray(this.root)))this.fail();if(!this.error&&this.imageBodies.length){const root=this.root as Record<string,unknown>,payload=root.payload as Record<string,unknown>|undefined;for(const body of this.imageBodies){if(root.type==='response_item'&&(payload?.type==='custom_tool_call_output'||payload?.type==='function_call_output')&&(body.frame.value as Record<string,unknown>|null)?.type==='input_image')continue;if(body.overflow)this.fail('native_metadata_bytes_limit');else Object.defineProperty(body.frame.value!,'image_url',{value:body.chunks.join(''),writable:true,enumerable:true,configurable:true});}}if(!this.error&&Buffer.byteLength(JSON.stringify(this.root))>this.maxBytes)this.fail('native_metadata_bytes_limit');return {record:this.error?null:this.root as Record<string,unknown>,code:this.error,exclusionMarker:this.marker};}\n}\n", "import {createHash} from 'node:crypto';\nimport type {AuditHarness} from './contracts.js';\nimport type {RecordedInference} from './launch-contracts.js';\n\ntype R=Record<string,unknown>;\nconst obj=(v:unknown):R=>v!==null&&typeof v==='object'&&!Array.isArray(v)?v as R:{};\nconst str=(...v:unknown[]):string|null=>v.find(x=>typeof x==='string'&&x.length>0) as string|undefined??null;\nconst num=(v:unknown):number|null=>typeof v==='number'&&Number.isSafeInteger(v)&&v>=0?v:null;\nconst cost=(v:unknown):number|null=>typeof v==='number'&&Number.isFinite(v)&&v>=0?v:null;\nconst hash=(v:string)=>createHash('sha256').update(v).digest('hex');\nconst at=(v:unknown):string|null=>typeof v==='number'&&Number.isFinite(v)&&Math.abs(v)<8.64e15?new Date(v).toISOString():typeof v==='string'&&Number.isFinite(Date.parse(v))?new Date(v).toISOString():null;\nexport interface UsageRecordScope {key:string;rawStart:number;rawEnd:number;eventAt:string|null;project:string|null;}\nexport interface NativeUsageOptions {project?:string|null;maxRecords?:number;acceptRecord?:(record:R,scope:UsageRecordScope)=>boolean;}\n/** Reads only the caller's bounded frozen bytes. Excluded records still advance native counters. */\nexport interface NativeUsageAccumulator {invalidateContext():void;pushLine(line:string):void;pushRecord(record:R,position?:{rawStart:number;rawEnd:number}):void;records():RecordedInference[];counts():{observed:number;excluded:number;deduplicated:number};}\n/** Stateful per-record extraction lets full usage stream independently of context captures. */\nexport function createNativeUsageAccumulator(harness:AuditHarness,conversationId:string,options:NativeUsageOptions={}):NativeUsageAccumulator {\n let observed=0,excluded=0;\n const records=new Map<string,RecordedInference>();let project=options.project??null,model:string|null=null,provider:string|null=null,session=conversationId,offset=0,seq=0;\n let previous:R|null=null;const seenTotals=new Set<string>();\n const identities=new Map<string,{models:Set<string>;providers:Set<string>}>();\n const score=(v:RecordedInference)=> (v.inputTokens??0)+(v.outputTokens??0)+(v.cacheReadTokens??0)+Math.max(v.cacheWriteTokens??0,(v.cacheWrite5mTokens??0)+(v.cacheWrite1hTokens??0))+(v.reasoningTokens??0);\n const put=(r:RecordedInference)=>{const old=records.get(r.id),identity=identities.get(r.id)??{models:new Set<string>(),providers:new Set<string>()};if(r.model!==null)identity.models.add(r.model);if(r.provider!==null)identity.providers.add(r.provider);identities.set(r.id,identity);const chosen=!old||score(r)>score(old)?r:old;const conflict=identity.models.size>1||identity.providers.size>1;records.set(r.id,conflict?{...chosen,model:null,provider:null,gaps:[...new Set([...chosen.gaps,'response_identity_model_conflict'])]}:chosen);};\n const pushRecord=(record:R,position?:{rawStart:number;rawEnd:number}):void=>{\n const start=position?.rawStart??offset;if(position)offset=position.rawEnd;if(++seq>(options.maxRecords??100_000))return;let r=record;\n if(harness==='opencode'){r={...r,...obj(r.message)};const wrapped=r.data??r.content;if(typeof wrapped==='string'){try{r={...r,...obj(JSON.parse(wrapped))};}catch{/* unsupported projection remains unknown */}}else if(wrapped&&typeof wrapped==='object')r={...r,...obj(wrapped)};}\n const p=obj(r.payload),m=obj(r.message);\n project=str(r.cwd,p.cwd,r.directory)??project;if(harness==='claude')session=str(r.sessionId)??session;if(harness==='pi'&&r.type==='session')session=str(r.id)??session;\n if(harness==='codex'&&(r.type==='session_meta'||r.type==='turn_context')){session=str(p.session_id,p.id)??session;model=str(p.model)??model;provider=str(p.model_provider,p.provider)??provider;return;}\n const eventAt=at(r.timestamp)??at(m.timestamp)??at(obj(r.time).created);const key=str(r.uuid,r.id,p.id,m.id)??`record:${seq}`;\n const accepted=options.acceptRecord?.(r,{key,rawStart:start,rawEnd:offset,eventAt,project})??true;\n let input:number|null=null,output:number|null=null,read:number|null=null,write:number|null=null,reasoning:number|null=null,reported:number|null=null;\n let observedModel:string|null=null,observedProvider:string|null=null,id:string,basis:string,includesCache=false,includesReasoning=true;const gaps:string[]=[];\n if(harness==='codex'){\n if(r.type!=='event_msg'||p.type!=='token_count')return;const info=obj(p.info),last=obj(info.last_token_usage),total=obj(info.total_token_usage);if(!Object.keys(last).length&&!Object.keys(total).length)return;observed++;\n const previousTotal=previous;previous=Object.keys(total).length?total:previous;\n const signature=Object.keys(total).length?JSON.stringify([session,total.input_tokens,total.output_tokens,total.cached_input_tokens,total.reasoning_output_tokens]):null;\n if(signature&&seenTotals.has(signature))return;if(signature)seenTotals.add(signature);\n const delta=(field:string):number|null=>{const current=num(total[field]),prev=num(previousTotal?.[field]);return current===null||prev===null||current<prev?null:current-prev;};\n const firstComplete=previousTotal===null&&num(last.input_tokens)!==null&&last.input_tokens===total.input_tokens&&last.output_tokens===total.output_tokens;\n const bucket=(field:string)=>num(last[field])??delta(field)??(firstComplete?num(total[field]):null);\n input=bucket('input_tokens');output=bucket('output_tokens');read=bucket('cached_input_tokens');write=bucket('cache_write_input_tokens');reasoning=bucket('reasoning_output_tokens');\n if(!Object.keys(last).length&&previousTotal===null)gaps.push('cumulative_baseline_unknown');\n if(previousTotal&&Object.keys(total).length&&['input_tokens','output_tokens'].some(k=>num(total[k])!==null&&num(previousTotal[k])!==null&&(num(total[k]) as number)<(num(previousTotal[k]) as number)))gaps.push('cumulative_counter_reset');\n observedModel=str(p.model,info.model)??model;observedProvider=str(p.model_provider,p.provider,info.provider)??provider;\n includesCache=true;basis='codex_last_response_with_cumulative_dedup';id=`codex:${hash(JSON.stringify([session,str(p.response_id,info.response_id)??signature??[eventAt,last]]))}`;\n // Absent optional cache-write means zero in Codex's native usage schema.\n write=write??0;\n }else if(harness==='claude'){\n if(r.type!=='assistant'||m.role!=='assistant')return;const u=obj(m.usage);input=num(u.input_tokens);output=num(u.output_tokens);read=num(u.cache_read_input_tokens)??(input!==null?0:null);write=num(u.cache_creation_input_tokens)??(input!==null?0:null);reasoning=num(u.reasoning_tokens);const duration=obj(u.cache_creation);const five=num(duration.ephemeral_5m_input_tokens),hour=num(duration.ephemeral_1h_input_tokens);if(five!==null&&hour!==null&&write!==null&&five+hour!==write)gaps.push('cache_write_duration_conflict');\n if(hour!==null&&hour>0&&(five===null||write===null||five+hour!==write))gaps.push('cache_write_duration_unknown');\n observedModel=str(m.model,r.model);observedProvider=str(m.provider,r.provider,r.modelProvider);reported=cost(r.costUSD)??cost(m.costUSD);basis='claude_response_usage';id=`claude:${hash(JSON.stringify([str(m.id,r.uuid)??key,str(r.requestId)??[session,eventAt]]))}`;\n }else if(harness==='pi'){\n if(r.type!=='message'||m.role!=='assistant')return;const u=obj(m.usage);input=num(u.input);output=num(u.output);read=num(u.cacheRead)??(input!==null?0:null);write=num(u.cacheWrite)??(input!==null?0:null);reasoning=num(u.reasoning);reported=cost(obj(u.cost).total);observedModel=str(m.model);observedProvider=str(m.provider);basis='pi_response_usage';id=`pi:${hash(JSON.stringify([session,str(r.id)??key,eventAt]))}`;\n }else{\n if(r.role!=='assistant')return;const u=obj(r.tokens),cache=obj(u.cache);input=num(u.input);output=num(u.output);read=num(cache.read)??(input!==null?0:null);write=num(cache.write)??(input!==null?0:null);reasoning=num(u.reasoning);reported=cost(r.cost);observedModel=str(r.modelID,obj(r.model).modelID,obj(r.model).id,r.model);observedProvider=str(r.providerID,obj(r.model).providerID,r.provider);basis='opencode_response_tokens';includesReasoning=false;id=`opencode:${str(r.id)??hash(JSON.stringify([conversationId,key,eventAt]))}`;\n }\n if(observedModel==='codex-auto-review'){observedModel=null;gaps.push('workflow_model_identity_unavailable');}\n if(harness!=='codex')observed++;if(r.isSynthetic===true||r.isMeta===true||m.isSynthetic===true||observedModel==='<synthetic>'){excluded++;return;}if(!accepted){excluded++;return;}if(!observedModel)gaps.push('model_unrecorded');if(!observedProvider)gaps.push('provider_unrecorded');if(input===null||output===null)gaps.push('usage_partial');\n if(includesCache&&read===null)gaps.push('cache_inclusion_unknown');\n if(includesCache&&input!==null&&read!==null&&write!==null&&read+write>input)gaps.push('cache_exceeds_input');\n if(includesReasoning&&output!==null&&reasoning!==null&&reasoning>output)gaps.push('reasoning_exceeds_output');\n put({id,conversationId,harness,eventAt,project,provider:observedProvider,model:observedModel,canonicalModel:null,inputTokens:input,outputTokens:output,cacheReadTokens:read,cacheWriteTokens:write,reasoningTokens:reasoning,inputIncludesCache:includesCache,outputIncludesReasoning:includesReasoning,reportedCostUsd:reported,basis,gaps,...(harness==='claude'?{cacheWrite5mTokens:num(obj(obj(m.usage).cache_creation).ephemeral_5m_input_tokens),cacheWrite1hTokens:num(obj(obj(m.usage).cache_creation).ephemeral_1h_input_tokens)}:{})});\n };\n const pushLine=(line:string):void=>{const start=offset;offset+=Buffer.byteLength(line)+1;if(!line.trim())return;let r:R;try{r=obj(JSON.parse(line));}catch{seq++;return;}pushRecord(r,{rawStart:start,rawEnd:offset});};\n return {pushRecord,invalidateContext:()=>{project=null;model=null;provider=null;previous=null;},pushLine,records:()=>[...records.values()],counts:()=>({observed,excluded,deduplicated:Math.max(0,observed-excluded-records.size)})};\n}\nexport function extractNativeUsageWithCounts(bytes:Buffer|string,harness:AuditHarness,conversationId:string,options:NativeUsageOptions={}):{usage:RecordedInference[];counts:{observed:number;excluded:number;deduplicated:number}}{\n const text=Buffer.isBuffer(bytes)?bytes.toString('utf8'):bytes,acc=createNativeUsageAccumulator(harness,conversationId,options);\n const lines=text.trimStart().startsWith('[')?(()=>{try{return (JSON.parse(text) as unknown[]).map(x=>JSON.stringify(x));}catch{return [];}})():text.split('\\n');for(const line of lines)acc.pushLine(line);return {usage:acc.records(),counts:acc.counts()};\n}\n\nexport function extractNativeUsage(bytes:Buffer|string,harness:AuditHarness,conversationId:string,options:NativeUsageOptions={}):RecordedInference[]{return extractNativeUsageWithCounts(bytes,harness,conversationId,options).usage;}\n", "import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Db } from './db.js';\nimport { configPath, expandTilde, potsherdDir } from './paths.js';\nimport type { SearchFilters } from './search/filters.js';\n\n/**\n * The ignore list: projects you do not want in `ls`, `find`, `ask` or `stats`.\n *\n * **Why it exists.** On the reference machine 9 of the top 15 `ls` rows are\n * potsherd's own worker and sdk sessions, and `find pgbouncer` returns\n * potsherd's own test sessions before the user's. Every user who builds\n * potsherd from a checkout hits a milder version of that, and every developer\n * running agents across many repos hits it whatever they build. The archive is\n * not wrong \u2014 it is complete, and completeness is what buries the answer.\n *\n * **Three rules this module is built to keep.**\n *\n * 1. **Nothing is ignored by default.** There is no shipped list, no\n * \"this looks like a build directory\" heuristic, and no auto-detection.\n * The user names what they ignore, with `potsherd ignore <project>`, and\n * `potsherd unignore <project>` takes it back. A tool that decided on its\n * own which of your work did not count would be making a claim about your\n * history it has no standing to make.\n *\n * 2. **An ignore list is never silent.** Every surface that drops rows says\n * so and says how many \u2014 `ls`, `find` and `stats` each print one line\n * naming the count and the flag that undoes it. A filter the user cannot\n * see is a claim about their archive the product cannot support: \"you\n * have 12 sessions about pgbouncer\" is a different sentence from \"you\n * have 12 sessions about pgbouncer, outside the projects you told me to\n * skip\". `doctor` prints the whole list, always.\n *\n * 3. **Ignoring is a view, not a deletion.** `index` keeps indexing\n * everything, `rescue` keeps rescuing everything, `show <id>` still shows\n * an ignored session, and `--all` brings every row back on the surfaces\n * that hide them. Nothing here ever deletes a row or skips a file.\n *\n * **Storage** is `~/.potsherd/config.json`, whose path `paths.configPath()`\n * has always resolved. The file is potsherd's own \u2014 the first thing potsherd\n * writes there that a user is expected to edit \u2014 so the writer preserves every\n * key it does not own and the reader survives a file that has been hand-edited\n * into nonsense.\n */\n\n/** The key this module owns inside `config.json`. Everything else is left alone. */\nexport const IGNORE_KEY = 'ignore';\n\nexport interface IgnoreConfig {\n /** The list as stored, in the order it was written. */\n list: string[];\n /** Every other key in the file, preserved across writes. */\n rest: Record<string, unknown>;\n /**\n * Set when the file exists and could not be understood. The list is then\n * empty \u2014 but `doctor` says the file is unreadable rather than reporting an\n * empty list, because \"you ignore nothing\" and \"I could not read your\n * settings\" are different facts and only one of them is actionable.\n */\n error?: string;\n /** The file this came from, whether or not it exists. */\n file: string;\n}\n\n/**\n * Read `<root>/config.json`.\n *\n * A missing file is not an error: it is the normal state of a fresh install\n * and means an empty list. A malformed one is reported rather than repaired \u2014\n * this file belongs to the user once they have opened it.\n */\nexport function readIgnoreConfig(root: string = potsherdDir()): IgnoreConfig {\n const file = configPath(root);\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return { list: [], rest: {}, file };\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { list: [], rest: {}, file, error: 'config.json is not valid JSON' };\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { list: [], rest: {}, file, error: 'config.json is not a JSON object' };\n }\n const record = parsed as Record<string, unknown>;\n const { [IGNORE_KEY]: raw, ...rest } = record;\n if (raw === undefined) return { list: [], rest, file };\n if (!Array.isArray(raw)) {\n return { list: [], rest, file, error: `config.json \"${IGNORE_KEY}\" is not an array` };\n }\n const list: string[] = [];\n for (const value of raw) {\n if (typeof value !== 'string') continue;\n const entry = normalizeIgnoreEntry(value);\n if (entry && !list.some((e) => sameEntry(e, entry))) list.push(entry);\n }\n return { list, rest, file };\n}\n\n/** Just the list. The shape every caller inside the engine wants. */\nexport function readIgnoreList(root: string = potsherdDir()): string[] {\n return readIgnoreConfig(root).list;\n}\n\n/**\n * Write the list back, preserving every other key.\n *\n * Written to a sibling temp file and renamed, so a crash mid-write leaves the\n * old config rather than half of a new one, and created 0600 because\n * `~/.potsherd` holds copies of transcripts and this file sits beside them.\n */\nexport function writeIgnoreList(root: string, list: readonly string[]): string[] {\n const current = readIgnoreConfig(root);\n const clean: string[] = [];\n for (const value of list) {\n const entry = normalizeIgnoreEntry(value);\n if (entry && !clean.some((e) => sameEntry(e, entry))) clean.push(entry);\n }\n const next = { ...current.rest, [IGNORE_KEY]: clean };\n const file = current.file;\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n const tmp = `${file}.tmp-${String(process.pid)}`;\n fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\\n`, { mode: 0o600 });\n fs.renameSync(tmp, file);\n return clean;\n}\n\nexport interface IgnoreChange {\n /** The list after the change. */\n list: string[];\n /** The entry as it was stored or removed, normalised. */\n entry: string;\n /** False when the entry was already there (`ignore`) or absent (`unignore`). */\n changed: boolean;\n}\n\n/** `potsherd ignore <project>`. Idempotent, and says so rather than pretending. */\nexport function addIgnored(root: string, project: string): IgnoreChange {\n const entry = normalizeIgnoreEntry(project);\n if (!entry) throw new Error('an ignore entry needs at least one character that is not a slash');\n const before = readIgnoreList(root);\n if (before.some((e) => sameEntry(e, entry))) return { list: before, entry, changed: false };\n const list = writeIgnoreList(root, [...before, entry]);\n return { list, entry, changed: true };\n}\n\n/** `potsherd unignore <project>`. */\nexport function removeIgnored(root: string, project: string): IgnoreChange {\n const entry = normalizeIgnoreEntry(project);\n if (!entry) throw new Error('an ignore entry needs at least one character that is not a slash');\n const before = readIgnoreList(root);\n if (!before.some((e) => sameEntry(e, entry))) return { list: before, entry, changed: false };\n const list = writeIgnoreList(\n root,\n before.filter((e) => !sameEntry(e, entry)),\n );\n return { list, entry, changed: true };\n}\n\n/**\n * What the user typed, as it will be stored.\n *\n * `~` is expanded because a stored `~/code/potsherd` would never match a\n * project recorded as `/Users/me/code/potsherd`, and a trailing slash is\n * dropped because `potsherd/` and `potsherd` are the same directory to\n * everyone except a string comparison.\n */\nexport function normalizeIgnoreEntry(value: string): string {\n const trimmed = expandTilde(value.trim());\n return trimmed.replace(/[\\\\/]+$/, '');\n}\n\nfunction fold(value: string): string {\n return value.replace(/\\\\/g, '/').replace(/\\/+$/, '').toLowerCase();\n}\n\nfunction sameEntry(a: string, b: string): boolean {\n return fold(a) === fold(b);\n}\n\n/**\n * Does this entry name this project?\n *\n * Two forms, and the difference is whether the user typed a slash.\n *\n * `potsherd` a **path segment**. Matches\n * `/Users/me/randomness/potsherd` and everything\n * under it, including\n * `/Users/me/randomness/potsherd/wt/w3-ignore`.\n * It does **not** match `potsherd-notes`: the\n * segment must be the whole segment, or `ignore\n * core` would hide `core-app` and the user would\n * have no way to tell it had.\n *\n * `~/randomness/potsherd` a **path**. Matches that directory and its\n * descendants, and nothing else. This is the form\n * to reach for when the same directory name\n * appears in two places and only one of them is\n * noise.\n *\n * The segment form is the default because it is the one that works: potsherd's\n * own sessions on the reference machine are spread across the checkout, six\n * git worktrees and a `.claude/worktrees/agent-*` directory, and a rule that\n * matched only the exact path the user typed would hide one of eight.\n */\nexport function matchesIgnoreEntry(project: string | null | undefined, entry: string): boolean {\n if (!project) return false;\n const p = fold(project);\n const e = fold(entry);\n if (!p || !e) return false;\n if (p === e) return true;\n if (e.includes('/')) return p.startsWith(`${e}/`);\n return p.split('/').filter(Boolean).includes(e);\n}\n\n/** True when any entry in the list names this project. */\nexport function isIgnoredProject(\n project: string | null | undefined,\n entries: readonly string[],\n): boolean {\n return entries.some((entry) => matchesIgnoreEntry(project, entry));\n}\n\n/**\n * `<root>` for an open database, so a core function that was handed only a\n * `Db` can still find the config beside it.\n *\n * This matters because `ask` reaches `recall` without passing a root through\n * every layer, and an ignore list `ls` honours but `ask` does not would be\n * worse than no ignore list at all. `PRAGMA database_list` names the file the\n * connection actually opened \u2014 not the file some caller believes it opened \u2014\n * so a test pointing at a temp directory and a user pointing at `~/.potsherd`\n * are answered the same way. An in-memory database has no file and returns\n * null, which is the honest answer: it has no config.\n */\nexport function rootForDb(db: Db): string | null {\n try {\n const rows = db.prepare('PRAGMA database_list').all() as {\n name?: string;\n file?: string;\n }[];\n const main = rows.find((r) => r.name === 'main') ?? rows[0];\n const file = main?.file;\n if (!file) return null;\n return path.dirname(file);\n } catch {\n return null;\n }\n}\n\n/**\n * The project values **in this index** that the list names.\n *\n * The predicate is a rule about paths; SQL needs a set of literals. Resolving\n * the rule against the projects that actually exist gives both \u2014 a bound\n * `NOT IN (?, ?)` that any of the three filter builders can carry, and the\n * exact list of what is being hidden, which is what the surfaces print.\n */\nexport function ignoredProjectsInIndex(db: Db, entries: readonly string[]): string[] {\n if (entries.length === 0) return [];\n let rows: { project: string | null }[] = [];\n try {\n rows = db\n .prepare(\n `SELECT DISTINCT project FROM (\n SELECT project FROM sessions WHERE project IS NOT NULL\n UNION\n SELECT project FROM ghosts WHERE project IS NOT NULL\n )`,\n )\n .all() as { project: string | null }[];\n } catch {\n return [];\n }\n const out: string[] = [];\n for (const r of rows) {\n if (r.project && isIgnoredProject(r.project, entries)) out.push(r.project);\n }\n return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nexport interface IgnoreOptions {\n /** `--all`: show everything. The list is read but not applied. */\n all?: boolean;\n /** potsherd root. Falls back to the database's own directory. */\n root?: string;\n /** Entries to use instead of reading the config. Tests, and `--json` echo. */\n entries?: readonly string[];\n}\n\nexport interface IgnoreApplication {\n /** The filters to run, with `excludeProjects` set when the list applies. */\n filters: SearchFilters;\n /** What the config holds, whether or not it was applied. */\n entries: string[];\n /** The project values excluded from this query. Empty when nothing applied. */\n projects: string[];\n /** True when rows were actually excluded. */\n applied: boolean;\n /** Why not, when `applied` is false and `entries` is not empty. */\n reason?: 'all' | 'named-project' | 'no-match';\n}\n\n/**\n * Fold the ignore list into a set of filters, once, at the top of a verb.\n *\n * Two things deliberately switch it off:\n *\n * **`--all`.** The escape hatch every surface names on screen.\n *\n * **`--project X`.** Naming a project *is* asking for it. Hiding the rows\n * someone has just asked for by name, and printing \"12 hidden\" under an\n * empty table, is the ignore list arguing with its user.\n */\nexport function applyIgnore(\n db: Db,\n filters: SearchFilters = {},\n options: IgnoreOptions = {},\n): IgnoreApplication {\n const root = options.root ?? rootForDb(db) ?? undefined;\n const entries = [...(options.entries ?? readIgnoreList(root ?? potsherdDir()))];\n if (entries.length === 0) return { filters, entries, projects: [], applied: false };\n if (options.all) return { filters, entries, projects: [], applied: false, reason: 'all' };\n if (filters.project) {\n return { filters, entries, projects: [], applied: false, reason: 'named-project' };\n }\n const projects = ignoredProjectsInIndex(db, entries);\n if (projects.length === 0) {\n return { filters, entries, projects: [], applied: false, reason: 'no-match' };\n }\n return { filters: { ...filters, excludeProjects: projects }, entries, projects, applied: true };\n}\n\n/**\n * What a surface reports about the rows it dropped.\n *\n * Carried on `ListResult`, `RecallResult` and `StatsReport` so the renderers\n * and `--json` read one shape, and so a `--json` consumer can tell \"no\n * results\" apart from \"no results outside your ignore list\".\n */\nexport interface IgnoreReport {\n /** The list as configured. */\n entries: string[];\n /** The project values actually excluded. */\n projects: string[];\n /**\n * How much the list cost, **in the units the surface reporting it uses**,\n * and 0 whenever the list did not apply.\n *\n * `ls` rows dropped from *this* listing \u2014 the ones that matched every\n * other filter and lost only on their project.\n * `find` sessions in the ignored projects that were not searched.\n * `stats` sessions and ghosts left out of the counts.\n *\n * Each surface names its unit on screen; they are not interchangeable and\n * nothing should add them together.\n */\n hidden: number;\n}\n\n/**\n * Sessions and ghosts belonging to the ignored projects, for the surfaces that\n * report what they did not look at rather than what they dropped.\n *\n * Top-level sessions only: a subagent transcript is not a row anybody counts,\n * and `197 sessions not searched` on a machine with 30 conversations would be\n * a true number that misinforms every reader of it.\n */\nexport function countIgnoredSessions(db: Db, projects: readonly string[]): number {\n if (projects.length === 0) return 0;\n const marks = projects.map(() => '?').join(', ');\n try {\n const row = db\n .prepare(\n `SELECT (SELECT COUNT(*) FROM sessions\n WHERE is_sidechain = 0 AND project IN (${marks}))\n + (SELECT COUNT(*) FROM ghosts WHERE project IN (${marks})) AS n`,\n )\n .get(...projects, ...projects) as { n: number };\n return row?.n ?? 0;\n } catch {\n return 0;\n }\n}\n\nexport function emptyIgnoreReport(entries: readonly string[] = []): IgnoreReport {\n return { entries: [...entries], projects: [], hidden: 0 };\n}\n", "import {runNativeScanWorker} from '../../core/src/analytics/native-pool.js';\nrunNativeScanWorker();\n"],
|
|
5
|
-
"mappings": ";;;;AAAA,SAAQ,QAAO,kBAAiB;AAChC,SAAQ,WAAU,mBAAkB;AACpC,SAAQ,cAAAA,mBAAiB;;;ACFzB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAQ,cAAAC,mBAAiB;;;ACUlB,SAAS,SAAS,OAAkD;AACzE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAiBO,SAAS,iBAAiB,SAAkB,YAAY,QAAgB;AAC7E,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,QAAO;AACpC,SAAO,QACJ,OAAO,CAAC,MAAoC,SAAS,CAAC,KAAK,EAAE,SAAS,aAAa,OAAO,EAAE,SAAS,QAAQ,EAC7G,IAAI,CAAC,MAAM,EAAE,IAAc,EAC3B,KAAK,IAAI;AACd;;;ACvBO,IAAM,4BACX;AAGK,IAAM,uBACX;AAEK,IAAM,oBAAuC;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,SAAS,mBAAmB,MAAuB;AACxD,SAAO,kBAAkB,KAAK,CAAC,WAAW,KAAK,SAAS,MAAM,CAAC;AACjE;;;AChCA,S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AAG,OAAM,CAAC;AAC9Z,YAAM,SAAO,UAAU,QAAQ;AAAE,UAAG,OAAO,UAAQ,QAAQ,kBAAgB,MAAI,OAAK,MAAM,OAAM,IAAI,MAAM,gCAAgC;AAAE,YAAMI,QAAKC,YAAW,QAAQ,EAAE,OAAO,MAAM,EAAE,OAAO,KAAK;AAAE,UAAI,WAAS;AAAE,eAAQC,MAAG,GAAEA,MAAG,OAAO,QAAOA,OAAI,OAAM;AAAC,cAAM,QAAM,WAAW,KAAK,OAAO,SAASA,KAAGA,MAAG,KAAK,CAAC;AAAE,aAAK,YAAY,EAAC,UAAS,UAAS,MAAK,SAAQ,OAAM,IAAI,OAAM,UAAS,YAAW,MAAK,MAAK,GAAE,CAAC,MAAM,MAAM,CAAC;AAAA,MAAE;AAAC,WAAK,YAAY,EAAC,UAAS,UAAS,MAAK,UAAS,OAAM,IAAI,OAAM,qBAAoB,OAAO,qBAAoB,OAAM,OAAO,QAAO,MAAAF,MAAI,CAAC;AAAA,IACxjB,SAAO,OAAM;AAAC,WAAK,YAAY,EAAC,UAAS,UAAS,MAAK,SAAQ,OAAM,IAAI,OAAM,MAAK,KAAK,KAAK,EAAC,CAAC;AAAA,IAAE,UAAC;AAAQ,aAAK;AAAA,IAAM;AAAA,EACvH,CAAC;AAAE,OAAK,YAAY,EAAC,UAAS,UAAS,MAAK,QAAO,CAAC;AACrD;;;AavCA,oBAAoB;",
|
|
6
|
-
"names": ["createHash", "
|
|
3
|
+
"sources": ["../../core/src/analytics/scan-pool.ts", "../../core/src/analytics/extract.ts", "../../core/src/markers.ts", "../../core/src/redact.ts", "../../core/src/theme.ts", "../../core/src/redact-rules.ts", "../../core/src/redact-elide.ts", "../../core/src/analytics/source.ts", "../../core/src/analytics/profanity.ts", "../../core/src/analytics/language-feedback.ts", "../../core/src/analytics/project-focus.ts", "../../core/src/analytics/findings.ts", "../../core/src/analytics/story-lexicon.ts", "../../core/src/analytics/story-time.ts", "../../core/src/analytics/story-extract.ts", "../src/audit-native-worker.ts"],
|
|
4
|
+
"sourcesContent": ["/**\n * Reads history files on a bounded pool of worker threads. Each worker runs\n * `extractFile` on one file at a time and posts the facts back; the caller\n * aggregates. Without a worker entry (tests, unusual installs) the same code\n * runs inline.\n */\nimport os from 'node:os';\nimport {Worker, parentPort} from 'node:worker_threads';\nimport {extractFile, stripText, type NativeHarness, type SourceFacts} from './extract.js';\n\nexport interface ScanJob {\n file: string;\n harness: NativeHarness;\n /** Bytes, used to schedule the largest files first. */\n size: number;\n /** Time zone for story counters. */\n timezone?: string;\n}\n\n/** Facts as they leave a reader: story fields kept, prompt text dropped. */\nexport const readFacts = (job: ScanJob): SourceFacts => stripText(extractFile(job.file, job.harness, {timezone: job.timezone}));\n\nexport type ScanResult = {job: ScanJob; facts: SourceFacts} | {job: ScanJob; error: string};\n\nexport interface ScanExecutor {\n /** Calls `onResult` once per job, in completion order. */\n scan(jobs: readonly ScanJob[], onResult: (result: ScanResult) => void, signal: AbortSignal): Promise<void>;\n close(): Promise<void>;\n}\n\nconst errorCode = (error: unknown) => (error instanceof Error && /^[a-z][a-z0-9_]{0,63}$/.test(error.message) ? error.message : 'source_unreadable');\n\nfunction runInline(job: ScanJob): ScanResult {\n try { return {job, facts: readFacts(job)}; } catch (error) { return {job, error: errorCode(error)}; }\n}\n\n/** In-process executor: yields between files so progress events can flow. */\nexport const inlineScanExecutor: ScanExecutor = {\n async scan(jobs, onResult, signal) {\n for (const job of jobs) {\n if (signal.aborted) return;\n onResult(runInline(job));\n await new Promise(resolve => setImmediate(resolve));\n }\n },\n async close() {},\n};\n\nexport function defaultThreads(): number {\n const forced = Number(process.env['SLOPIE_AUDIT_THREADS']);\n if (Number.isInteger(forced) && forced > 0) return Math.min(forced, 16);\n return Math.max(1, Math.min(8, os.availableParallelism() - 1));\n}\n\n/** Worker-thread executor. Threads start lazily and are reused across scans. */\nexport function createScanPool(entry: URL | string, threads = defaultThreads()): ScanExecutor {\n let workers: Worker[] = [];\n let closed = false;\n const start = (count: number) => {\n while (workers.length < count) workers.push(new Worker(entry, {stdout: false, stderr: false, resourceLimits: {maxOldGenerationSizeMb: 512}}));\n };\n return {\n async scan(jobs, onResult, signal) {\n if (closed) throw new Error('scan_pool_closed');\n const queue = [...jobs].sort((a, b) => b.size - a.size);\n if (!queue.length) return;\n start(Math.min(threads, queue.length));\n await new Promise<void>(resolve => {\n let active = 0, done = false;\n const finish = () => { if (!done) { done = true; signal.removeEventListener('abort', finish); resolve(); } };\n signal.addEventListener('abort', finish, {once: true});\n const feed = (worker: Worker) => {\n if (done) return;\n if (signal.aborted || !queue.length) { if (active === 0) finish(); return; }\n const job = queue.shift()!;\n active++;\n const onMessage = (message: {facts?: SourceFacts; error?: string}) => {\n cleanup();\n active--;\n if (!done) onResult(message.facts ? {job, facts: message.facts} : {job, error: message.error ?? 'source_unreadable'});\n feed(worker);\n };\n const onError = () => {\n cleanup();\n active--;\n workers = workers.filter(w => w !== worker);\n // A crashed thread loses only its file; read it here instead.\n if (!done) onResult(runInline(job));\n if (!workers.length && queue.length) { for (const next of queue.splice(0)) if (!done) onResult(runInline(next)); }\n if (active === 0 && !queue.length) finish();\n };\n const cleanup = () => { worker.off('message', onMessage); worker.off('error', onError); };\n worker.on('message', onMessage);\n worker.once('error', onError);\n worker.postMessage(job);\n };\n for (const worker of workers.slice(0, Math.min(workers.length, queue.length))) feed(worker);\n });\n },\n async close() {\n closed = true;\n const all = workers;\n workers = [];\n await Promise.all(all.map(w => w.terminate().catch(() => 0)));\n },\n };\n}\n\n/** Worker entry point. */\nexport function runScanWorker(): void {\n if (!parentPort) throw new Error('scan_worker_requires_parent');\n const port = parentPort;\n port.on('message', (job: ScanJob) => {\n try { port.postMessage({facts: readFacts(job)}); } catch (error) { port.postMessage({error: errorCode(error)}); }\n });\n}\n", "/**\n * Single-pass extraction of audit facts from one native history file.\n *\n * Only two things are kept from a transcript:\n * - usage metadata of assistant responses (model, token counts, time), and\n * - the text of user-role messages (redacted), classified as human or not.\n *\n * Assistant bodies, tool calls/outputs, images and reasoning are never parsed:\n * lines are classified from a short byte prefix (or a byte search) and only the\n * interesting ones go through JSON.parse.\n *\n * The usage rules follow ccusage 20.x; the prompt rules are documented in\n * `classifyText` and next to each harness below.\n */\nimport fs from 'node:fs';\nimport {createHash} from 'node:crypto';\nimport path from 'node:path';\nimport {hasExclusionMarker} from '../markers.js';\nimport {clean} from './source.js';\nimport type {AuditHarness, AuditPromptLex} from './contracts.js';\nimport {deriveStory, promptLex, isAgentTool, usageWeight, type StoryTextFacts, type TurnEvent, type TurnStats} from './story-extract.js';\nimport {featurize, safeQuote, topicWords, vocabularyWords, type PromptFeatures} from './story-lexicon.js';\nimport {localClock} from './story-time.js';\n\n/** 5: story features; prompt text is no longer kept in the cache. */\nexport const FACTS_VERSION = 5;\n\nexport type NativeHarness = Exclude<AuditHarness, 'opencode'>;\n\nexport interface UsageFact {\n /** De-duplication key (see `aggregate.ts`); null when the record has no stable identity. */\n key: string | null;\n at: number | null;\n model: string | null;\n provider: string | null;\n /** Uncached input tokens. */\n input: number;\n /** Output tokens, including reasoning. */\n output: number;\n cacheRead: number;\n /** All cache-creation tokens (5m + 1h). */\n cacheWrite: number;\n cacheWrite1h: number;\n reasoning: number;\n /** True when the model was not recorded and had to be inferred. */\n inferredModel?: boolean;\n /** Claude: written by a subagent / sidechain. */\n sidechain?: boolean;\n /** Claude: the record had no requestId. */\n requestless?: boolean;\n /** Claude: message id + session for sidechain-replay detection. */\n replayKey?: string;\n /** Recorded service tier: Claude `usage.speed`, Codex `thread_settings.service_tier`. */\n tier?: 'fast' | 'standard';\n /** Codex remote compaction request (token_usage_record). */\n compaction?: boolean;\n}\n\nexport type PromptKind = 'human' | 'command' | 'answer' | 'excluded';\n\nexport interface PromptFact {\n key: string;\n at: number | null;\n project: string | null;\n /** Redacted text, capped; empty unless the prompt is human. */\n text: string;\n kind: PromptKind;\n /** Why a user-role message is not a human prompt. */\n reason: string | null;\n /** Model whose response the user was reacting to. */\n before: string | null;\n beforeProvider: string | null;\n /** Model that answered this prompt. */\n after: string | null;\n afterProvider: string | null;\n /** Story: features of the text (human prompts). */\n f?: PromptFeatures;\n /** Lexical data for the language passes (human prompts). */\n lex?: AuditPromptLex;\n /** Story: safe quote candidate (fixed slots only). */\n q?: string;\n /** Story: stats of the turn this prompt started, from this file. */\n t?: TurnStats;\n}\n\nexport interface SourceFacts {\n v: number;\n harness: AuditHarness;\n file: string;\n size: number;\n mtimeMs: number;\n sessionId: string;\n /** Claude: all session ids seen on user records of a top-level transcript. */\n sessionIds?: string[];\n parentId: string | null;\n child: boolean;\n project: string | null;\n title: string | null;\n /** Non-interactive session (codex exec / sdk). */\n automated: boolean;\n /** Contains a potsherd exclusion marker: its text is never kept. */\n excluded: boolean;\n /** Codex: session_meta timestamp, used to order parents before children. */\n startedAt: string | null;\n firstAt: number | null;\n lastAt: number | null;\n usage: UsageFact[];\n prompts: PromptFact[];\n malformed: number;\n /** Time zone the story counters were bucketed in. */\n tz?: string;\n /** Story word counters (see story-extract.ts). */\n story?: StoryTextFacts;\n /** Append-only resume state (recent files only). */\n resume?: ResumeState;\n}\n\nexport interface ExtractOptions {\n /** Time zone for story counters (default: the system zone). */\n timezone?: string;\n}\n\nconst MAX_PROMPT_CHARS = 4000;\n\ntype Rec = Record<string, unknown>;\nconst isRec = (v: unknown): v is Rec => v !== null && typeof v === 'object' && !Array.isArray(v);\nconst str = (v: unknown): string | null => (typeof v === 'string' && v.length > 0 ? v : null);\nconst int = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : 0);\nfunction time(v: unknown): number | null {\n if (typeof v === 'string') {\n const t = Date.parse(v);\n return Number.isFinite(t) ? t : null;\n }\n if (typeof v === 'number' && Number.isFinite(v)) return v < 1e11 ? v * 1000 : v;\n return null;\n}\n\nfunction textOf(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n const parts: string[] = [];\n for (const block of content) if (isRec(block) && typeof block.text === 'string') parts.push(block.text);\n return parts.join('\\n');\n}\n\n/* ------------------------------------------------------- prompt rules --- */\n\n/** Text a harness injects into the user role. Anything starting with these is not a prompt. */\nconst INJECTED_PREFIXES: readonly [string, string][] = [\n ['<task-notification>', 'task_notification'],\n ['<local-command-stdout>', 'local_command_output'], ['<local-command-stderr>', 'local_command_output'],\n ['<local-command-caveat>', 'local_command_output'],\n ['[Request interrupted', 'interrupt_marker'], ['<turn_aborted>', 'interrupt_marker'],\n ['<environment_context>', 'environment_context'], ['# AGENTS.md instructions', 'agents_md'],\n ['<user_instructions>', 'agents_md'], ['<external_codex_apps', 'app_state'],\n ['<recommended_plugins>', 'app_state'], ['<heartbeat>', 'automation'],\n ['The following is the Codex agent history', 'guardian_review'],\n ['You have new hive inbox message', 'automation'],\n ['Another Claude session sent a message', 'cross_session_message'],\n ['This session is being continued from a previous conversation', 'compaction_summary'],\n ['Your claude.ai usage limit has reset', 'auto_continuation'],\n ['Base directory for this skill:', 'skill_expansion'],\n];\nconst SYSTEM_REMINDER = /<system-reminder>[\\s\\S]*?<\\/system-reminder>/g;\n\n/** Classifies the text of a user-role message. Returns the kind, a reason and the cleaned text. */\nexport function classifyText(raw: string): {kind: PromptKind; reason: string | null; text: string} {\n const text = (raw.includes('<system-reminder>') ? raw.replace(SYSTEM_REMINDER, '') : raw).trim();\n if (!text) return {kind: 'excluded', reason: 'empty', text};\n for (const [prefix, reason] of INJECTED_PREFIXES) if (text.startsWith(prefix)) return {kind: 'excluded', reason, text};\n if (text.startsWith('<command-name>') || text.startsWith('<command-message>')) return {kind: 'command', reason: 'slash_command', text};\n if (text.startsWith('<send_user_message_question_reply>')) return {kind: 'answer', reason: 'question_answer', text};\n return {kind: 'human', reason: null, text};\n}\n\nconst CODEX_STRIP = [/<in-app-browser-context[\\s\\S]*?<\\/in-app-browser-context>/g, /<image name=[^>]*>\\s*<\\/image>/g, /<\\/?image[^>]*>/g];\n/** Codex desktop wraps the typed request: '# Files mentioned by the user: ... ## My request: <typed>'. */\nfunction cleanCodexText(raw: string): string {\n let t = raw;\n if (t.includes('<')) for (const rx of CODEX_STRIP) t = t.replace(rx, '');\n const at = t.indexOf('## My request');\n if (at >= 0) {\n const rest = t.slice(at + '## My request'.length), colon = rest.indexOf(':');\n t = colon >= 0 ? rest.slice(colon + 1) : rest;\n } else if (t.trimStart().startsWith('# Files mentioned by the user')) t = '';\n return t.trim();\n}\n\n/* ----------------------------------------------------------- builder --- */\n\ninterface Builder {\n facts: SourceFacts;\n currentModel: string | null;\n currentProvider: string | null;\n /** Prompts waiting for the model that answers them. */\n pending: PromptFact[];\n seenPrompts: Set<string>;\n /** Assistant events and interrupts for per-turn stats. */\n events: TurnEvent[];\n interrupts: number[];\n}\n\nfunction makeBuilder(file: string, harness: NativeHarness, size: number, mtimeMs: number): Builder {\n return {\n facts: {\n v: FACTS_VERSION, harness, file, size, mtimeMs,\n sessionId: path.basename(file, '.jsonl'), parentId: null, child: false, project: null, title: null,\n automated: false, excluded: false, startedAt: null, firstAt: null, lastAt: null, usage: [], prompts: [], malformed: 0,\n },\n currentModel: null, currentProvider: null, pending: [], seenPrompts: new Set(), events: [], interrupts: [],\n };\n}\n\nfunction touch(b: Builder, at: number | null): void {\n if (at === null) return;\n if (b.facts.firstAt === null || at < b.facts.firstAt) b.facts.firstAt = at;\n if (b.facts.lastAt === null || at > b.facts.lastAt) b.facts.lastAt = at;\n}\n\nfunction answered(b: Builder, model: string | null, provider: string | null): void {\n if (!model) return;\n for (const p of b.pending) { p.after = model; p.afterProvider = provider; }\n b.pending.length = 0;\n b.currentModel = model;\n b.currentProvider = provider;\n}\n\nfunction addUsage(b: Builder, u: UsageFact): void {\n b.facts.usage.push(u);\n touch(b, u.at);\n answered(b, u.model, u.provider);\n}\n\nfunction addPrompt(b: Builder, key: string, at: number | null, project: string | null, kind: PromptKind, reason: string | null, text: string): void {\n if (b.seenPrompts.has(key)) return;\n b.seenPrompts.add(key);\n if (kind === 'human' && hasExclusionMarker(text)) b.facts.excluded = true;\n if (reason === 'interrupt_marker' && at !== null) b.interrupts.push(at);\n const prompt: PromptFact = {\n key, at, project, kind, reason,\n text: kind === 'human' ? clean(text.length > MAX_PROMPT_CHARS ? text.slice(0, MAX_PROMPT_CHARS) : text) : '',\n before: b.currentModel, beforeProvider: b.currentProvider, after: null, afterProvider: null,\n };\n b.facts.prompts.push(prompt);\n if (kind === 'human') b.pending.push(prompt);\n touch(b, at);\n}\n\n/* ------------------------------------------------------------ Claude --- */\n\nconst SUBAGENT_DIR = `${path.sep}subagents${path.sep}`;\n\nfunction claudeLine(b: Builder, line: Buffer, subagent: boolean, sessions: Set<string>): void {\n const assistant = line.includes('\"type\":\"assistant\"');\n if (assistant ? !line.includes('\"usage\"') : (subagent || !line.includes('\"type\":\"user\"'))) {\n // Titles are tiny records; everything else here is irrelevant.\n if (line.length > 4096 || (!line.includes('-title\"') && !line.includes('\"type\":\"summary\"'))) return;\n }\n let r: Rec;\n try { r = JSON.parse(line.toString('utf8')) as Rec; } catch { b.facts.malformed++; return; }\n if (!isRec(r)) return;\n const f = b.facts;\n if (r.type === 'summary' || r.type === 'custom-title' || r.type === 'ai-title') {\n const title = str(r.customTitle) ?? str(r.aiTitle) ?? str(r.title) ?? str(r.summary);\n if (title && (r.type !== 'summary' || !f.title)) f.title = title;\n return;\n }\n if (typeof r.cwd === 'string' && !f.project) f.project = r.cwd;\n const sid = str(r.sessionId);\n if (sid) {\n if (subagent) { f.parentId = sid; f.child = true; f.sessionId = `${sid}:${path.basename(f.file, '.jsonl')}`; }\n else if (!sessions.size) f.sessionId = sid;\n }\n const m = isRec(r.message) ? r.message : {};\n const at = time(r.timestamp);\n if (r.type === 'assistant') {\n const u = m.usage;\n if (!isRec(u)) return;\n const model = str(m.model);\n if (model === '<synthetic>') return;\n const cc = isRec(u.cache_creation) ? u.cache_creation : null;\n const write = cc ? int(cc.ephemeral_5m_input_tokens) + int(cc.ephemeral_1h_input_tokens) : int(u.cache_creation_input_tokens);\n const id = str(m.id), request = str(r.requestId), session = sid ?? f.file;\n const fact: UsageFact = {\n key: id ? (request ? `c:${id}:${request}` : `c:${id}::${session}:${String(r.timestamp)}`) : null,\n at, model, provider: null,\n input: int(u.input_tokens), output: int(u.output_tokens), cacheRead: int(u.cache_read_input_tokens),\n cacheWrite: write, cacheWrite1h: cc ? int(cc.ephemeral_1h_input_tokens) : 0, reasoning: 0,\n };\n if (r.isSidechain === true) fact.sidechain = true;\n if (!request) fact.requestless = true;\n if (id) fact.replayKey = `${id}:${session}`;\n if (u.speed === 'fast') fact.tier = 'fast';\n addUsage(b, fact);\n if (at !== null) {\n let tools = 0, subs = 0;\n if (Array.isArray(m.content)) for (const block of m.content) if (isRec(block) && block.type === 'tool_use') { tools++; if (typeof block.name === 'string' && isAgentTool(block.name)) subs++; }\n b.events.push({at, tools, subs, weight: usageWeight(fact.input, fact.output, fact.cacheRead, fact.cacheWrite)});\n }\n return;\n }\n if (r.type !== 'user' || r.isSidechain === true || subagent) return;\n const content = m.content;\n if (Array.isArray(content) && content.some(block => isRec(block) && block.type === 'tool_result')) return;\n if (sid) sessions.add(sid);\n const origin = isRec(r.origin) ? str(r.origin.kind) : null;\n const flagged = r.isMeta === true ? 'is_meta'\n : r.isCompactSummary === true ? 'compaction_summary'\n : origin && origin !== 'human' ? `origin_${origin}`\n : r.entrypoint === 'sdk-cli' ? 'headless_claude_p'\n : r.promptSource === 'system' ? 'prompt_source_system'\n : null;\n let {kind, reason, text} = classifyText(textOf(content));\n if (flagged) { kind = 'excluded'; reason = flagged; }\n else if (reason === 'empty' && origin === 'human' && Array.isArray(content) && content.some(block => isRec(block) && block.type === 'image')) {\n kind = 'human'; reason = null; text = '[image]';\n }\n addPrompt(b, str(r.uuid) ?? `${f.sessionId}:${String(r.timestamp)}`, at, str(r.cwd) ?? f.project, kind, reason, text);\n}\n\n/* ------------------------------------------------------------- Codex --- */\n\ninterface PendingCodexPrompt {key: string | null; at: number | null; text: string; imported: boolean; project: string | null}\ninterface CodexState {\n lineNo: number;\n previousTotal: string | null;\n tier: 'fast' | 'standard' | undefined;\n imported: boolean;\n records: Map<string, {at: number | null; usage: Rec}>;\n compacted: Set<string>;\n deltas: Set<string>;\n itemPrompts: PendingCodexPrompt[];\n responsePrompts: PendingCodexPrompt[];\n /** Which list became prompts, how many entries of it were converted, and their seen ids (resume). */\n mode: 'items' | 'responses' | null;\n converted: number;\n seen: Set<string>;\n compactionDone: Set<string>;\n}\nconst newCodexState = (): CodexState => ({lineNo: 0, previousTotal: null, tier: undefined, imported: false, records: new Map(), compacted: new Set(),\n deltas: new Set(), itemPrompts: [], responsePrompts: [], mode: null, converted: 0, seen: new Set(), compactionDone: new Set()});\n\n/** Thrown when an appended file cannot be resumed; the caller reads it in full. */\nexport class ResumeMismatch extends Error { constructor() { super('resume_mismatch'); } }\n\nconst U_KEYS = ['input_tokens', 'cached_input_tokens', 'output_tokens', 'reasoning_output_tokens', 'total_tokens'] as const;\nconst tuple = (u: unknown): number[] | null => (isRec(u) ? U_KEYS.map(k => int(u[k])) : null);\n\n/** Codex records its review helper as `codex-auto-review`; bill it as the helper model of that date. */\nconst AUTO_REVIEW_MODELS: readonly [string, string][] = [\n ['2026-07-30', 'gpt-5.6-luna'], ['2026-03-05', 'gpt-5.4'], ['2026-02-05', 'gpt-5.3-codex'],\n ['2025-12-11', 'gpt-5.2-codex'], ['2025-11-13', 'gpt-5.1-codex'], ['2025-09-15', 'gpt-5-codex'],\n];\nfunction codexModel(model: string | null, timestamp: string): {model: string; inferred: boolean} {\n if (model === 'codex-auto-review') {\n const day = timestamp.slice(0, 10);\n return {model: AUTO_REVIEW_MODELS.find(([since]) => day >= since)?.[1] ?? 'gpt-5', inferred: true};\n }\n return model ? {model, inferred: false} : {model: 'gpt-5', inferred: true};\n}\n\nfunction codexFact(b: Builder, s: CodexState, at: number | null, timestamp: string, d: readonly number[], key: string | null): UsageFact {\n const input = d[0]!, output = d[2]!, reasoning = d[3]!, cached = Math.min(d[1]!, input);\n const {model, inferred} = codexModel(b.currentModel, timestamp);\n const fact: UsageFact = {key, at, model, provider: 'openai', input: input - cached, output, cacheRead: cached, cacheWrite: 0, cacheWrite1h: 0, reasoning};\n if (inferred) fact.inferredModel = true;\n if (s.tier) fact.tier = s.tier;\n return fact;\n}\n\n/** Whether a Codex line (judged by its first bytes) can matter; everything else is skipped unread. */\nfunction codexWanted(head: string, lineNo: number): boolean {\n return (lineNo === 0 && head.includes('session_meta')) || head.includes('\"token_count\"') || head.includes('\"turn_context\"')\n || head.includes('thread_settings_applied') || head.includes('\"task_started\"') || head.includes('\"token_usage_record\"')\n || head.includes('\"type\":\"compacted\"') || (head.includes('\"UserMessage\"') && head.includes('item_completed'))\n || (head.includes('\"role\":\"user\"') && head.includes('\"response_item\"')) || (head.includes('\"event_msg\"') && head.includes('\"type\":\"user_message\"'));\n}\n\nfunction codexLine(b: Builder, line: Buffer, s: CodexState): void {\n const n = s.lineNo++;\n const head = line.toString(\"latin1\", 0, Math.min(line.length, 260));\n const f = b.facts;\n const parse = (): Rec | null => {\n try { return JSON.parse(line.toString('utf8')) as Rec; } catch { f.malformed++; return null; }\n };\n if (n === 0 && head.includes('session_meta')) {\n const r = parse();\n if (!r) return;\n const p = isRec(r.payload) ? r.payload : {};\n f.sessionId = str(p.id) ?? str(p.session_id) ?? f.sessionId;\n f.project = str(p.cwd);\n f.startedAt = str(p.timestamp) ?? str(r.timestamp);\n const source = p.source;\n if (isRec(source) && 'subagent' in source) {\n f.child = true;\n const sub = isRec(source.subagent) ? source.subagent : {};\n const spawn = isRec(sub.thread_spawn) ? sub.thread_spawn : {};\n f.parentId = str(spawn.parent_thread_id) ?? str(p.parent_thread_id) ?? str(p.forked_from_id);\n }\n if (source === 'exec' || p.originator === 'codex_exec' || p.originator === 'codex_sdk_ts') f.automated = true;\n touch(b, time(r.timestamp));\n return;\n }\n if (head.includes('\"token_count\"')) {\n const r = parse();\n const p = r && isRec(r.payload) ? r.payload : null;\n const info = p && isRec(p.info) ? p.info : null;\n if (!r || !info) return;\n const total = tuple(info.total_token_usage), last = tuple(info.last_token_usage);\n const totalSig = total ? total.join(',') : null;\n const advanced = totalSig === null || totalSig !== s.previousTotal;\n let d: number[] | null = null;\n if (last && advanced) d = last;\n else if (total) {\n const prev = s.previousTotal ? s.previousTotal.split(',').map(Number) : [0, 0, 0, 0, 0];\n d = total.map((v, i) => Math.max(0, v - prev[i]!));\n }\n if (totalSig) s.previousTotal = totalSig;\n if (!d || !(d[0]! || d[1]! || d[2]! || d[3]!)) return;\n s.deltas.add(d.join(','));\n // Counters replayed into another file repeat exactly; count each fingerprint once.\n const key = totalSig ? `x:${totalSig}|${last ? last.join(',') : ''}` : null;\n const fact = codexFact(b, s, time(r.timestamp), String(r.timestamp ?? ''), d, key);\n addUsage(b, fact);\n if (fact.at !== null) b.events.push({at: fact.at, tools: 0, subs: 0, weight: usageWeight(fact.input, fact.output, fact.cacheRead, fact.cacheWrite)});\n return;\n }\n if (head.includes('\"turn_context\"')) {\n const p = parse()?.payload;\n if (isRec(p)) { b.currentModel = str(p.model) ?? b.currentModel; if (typeof p.cwd === 'string') f.project = p.cwd; }\n return;\n }\n if (head.includes('thread_settings_applied')) {\n const p = parse()?.payload;\n const settings = isRec(p) && isRec(p.thread_settings) ? p.thread_settings : null;\n if (settings && 'service_tier' in settings) {\n const v = settings.service_tier;\n s.tier = v === 'priority' || v === 'fast' ? 'fast' : v === 'default' || v === 'standard' ? 'standard' : undefined;\n }\n return;\n }\n if (head.includes('\"task_started\"')) {\n const p = parse()?.payload;\n s.imported = isRec(p) && String(p.turn_id ?? '').startsWith('external-import');\n return;\n }\n if (head.includes('\"UserMessage\"') && head.includes('item_completed')) {\n const r = parse();\n const p = r && isRec(r.payload) ? r.payload : null;\n if (!r || !p) return;\n const item = isRec(p.item) ? p.item : {};\n s.itemPrompts.push({key: str(item.id), at: time(r.timestamp), text: textOf(item.content),\n imported: s.imported || String(p.turn_id ?? '').startsWith('external-import'), project: f.project});\n return;\n }\n if (head.includes('\"role\":\"user\"') && head.includes('\"response_item\"')) {\n const r = parse();\n if (!r) return;\n const p = isRec(r.payload) ? r.payload : {};\n s.responsePrompts.push({key: null, at: time(r.timestamp), text: textOf(p.content), imported: s.imported, project: f.project});\n return;\n }\n if (head.includes('\"event_msg\"') && line.subarray(0, 400).includes('\"type\":\"user_message\"')) {\n const r = parse();\n if (!r) return;\n const p = isRec(r.payload) ? r.payload : {};\n s.itemPrompts.push({key: null, at: time(r.timestamp), text: typeof p.message === 'string' ? p.message : '', imported: s.imported, project: f.project});\n return;\n }\n if (codexToolOrAbort(b, head)) return;\n if (head.includes('\"token_usage_record\"')) {\n const r = parse();\n const p = r && isRec(r.payload) ? r.payload : null;\n const id = p ? str(p.response_id) : null;\n if (r && p && id && isRec(p.usage)) s.records.set(id, {at: time(r.timestamp), usage: p.usage});\n return;\n }\n if (head.includes('\"type\":\"compacted\"')) {\n // The marker carries the whole replacement history; only its own id matters.\n const at = line.lastIndexOf('\"compaction_response_id\":\"');\n if (at >= 0) {\n const start = at + 26, end = line.indexOf(34, start);\n if (end > start) s.compacted.add(line.toString(\"latin1\", start, end));\n }\n }\n}\n\nconst TOOL_CALL = /\"type\":\"(?:function_call|custom_tool_call)\"/;\nconst NAME = /\"name\":\"([^\"]{1,80})\"/;\nconst STAMP = /\"timestamp\":\"([^\"]{10,40})\"/;\n/** Codex tool calls and aborted turns, judged from the line head only (the body can be huge). */\nfunction codexToolOrAbort(b: Builder, head: string): boolean {\n if (TOOL_CALL.test(head) && head.includes('\"response_item\"')) {\n const at = time(STAMP.exec(head)?.[1]);\n const name = NAME.exec(head)?.[1] ?? '';\n if (at !== null) b.events.push({at, tools: 1, subs: isAgentTool(name) ? 1 : 0, weight: 0});\n return true;\n }\n if (head.includes('\"turn_aborted\"') && head.includes('\"event_msg\"')) {\n const at = time(STAMP.exec(head)?.[1]);\n if (at !== null) b.interrupts.push(at);\n return true;\n }\n return false;\n}\n\nfunction finishCodex(b: Builder, s: CodexState): void {\n const f = b.facts;\n // Remote compaction requests: linked to a compacted marker and not already a token_count delta.\n for (const id of s.compacted) {\n if (s.compactionDone.has(id)) continue;\n const record = s.records.get(id);\n const d = record ? tuple(record.usage) : null;\n if (!record || !d || !(d[0]! || d[1]! || d[2]! || d[3]!) || s.deltas.has(d.join(','))) continue;\n s.compactionDone.add(id);\n const fact = codexFact(b, s, record.at, record.at ? new Date(record.at).toISOString() : '', d, `codex-compaction:${id}`);\n fact.compaction = true;\n f.usage.push(fact);\n touch(b, record.at);\n }\n // Current Codex marks typed input with item_completed/UserMessage (older: event_msg/user_message);\n // response_item role=user also carries injected context and is only a fallback.\n if (s.mode === 'responses' && s.itemPrompts.length) throw new ResumeMismatch();\n const mode = s.mode ?? (s.itemPrompts.length ? 'items' : s.responsePrompts.length ? 'responses' : null);\n const list = mode === 'items' ? s.itemPrompts : mode === 'responses' ? s.responsePrompts : [];\n s.mode = mode;\n const reason = f.child ? 'subagent_parent_written' : f.automated ? 'programmatic_exec_session' : null;\n const seen = s.seen, base = s.converted;\n s.converted += list.length;\n list.forEach((p, n) => {\n const i = base + n;\n if (p.key) { if (seen.has(p.key)) return; seen.add(p.key); }\n const key = `codex:${f.sessionId}:${p.key ?? i}`;\n if (reason) return addPrompt(b, key, p.at, p.project, 'excluded', reason, '');\n if (p.imported) return addPrompt(b, key, p.at, p.project, 'excluded', 'imported_from_claude_transcript', '');\n const c = classifyText(cleanCodexText(p.text));\n addPrompt(b, key, p.at, p.project, c.kind, c.reason, c.text);\n });\n // Attribute prompts to the models around them, by time.\n const answers = f.usage.filter(u => u.at !== null).sort((x, y) => x.at! - y.at!);\n let j = 0, previous: string | null = null;\n for (const p of [...f.prompts].sort((x, y) => (x.at ?? 0) - (y.at ?? 0))) {\n while (j < answers.length && answers[j]!.at! <= (p.at ?? 0)) previous = answers[j++]!.model;\n p.before = previous; p.beforeProvider = previous ? 'openai' : null;\n p.after = answers[j]?.model ?? null; p.afterProvider = p.after ? 'openai' : null;\n }\n}\n\n/* ---------------------------------------------------------------- pi --- */\n\nfunction piLine(b: Builder, line: Buffer): void {\n let r: Rec;\n try { r = JSON.parse(line.toString('utf8')) as Rec; } catch { b.facts.malformed++; return; }\n const f = b.facts, at = time(r.timestamp);\n if (r.type === 'session') {\n f.sessionId = str(r.id) ?? f.sessionId;\n f.project = str(r.cwd);\n touch(b, at);\n return;\n }\n if (r.type === 'model_change') {\n b.currentModel = str(r.modelId) ?? b.currentModel;\n b.currentProvider = str(r.provider) ?? b.currentProvider;\n return;\n }\n if (r.type !== 'message' || !isRec(r.message)) return;\n const m = r.message;\n if (m.role === 'assistant' && isRec(m.usage)) {\n const u = m.usage;\n const fact: UsageFact = {\n key: `pi:${f.sessionId}:${String(r.id)}`, at, model: str(m.model) ?? b.currentModel, provider: str(m.provider) ?? b.currentProvider,\n input: int(u.input), output: int(u.output), cacheRead: int(u.cacheRead), cacheWrite: int(u.cacheWrite), cacheWrite1h: 0, reasoning: 0,\n };\n if (fact.input + fact.output + fact.cacheRead + fact.cacheWrite > 0) addUsage(b, fact);\n else answered(b, fact.model, fact.provider);\n if (at !== null) {\n const tools = Array.isArray(m.content) ? m.content.filter(c => isRec(c) && typeof c.type === 'string' && c.type.toLowerCase().includes('tool')).length : 0;\n b.events.push({at, tools, subs: 0, weight: usageWeight(fact.input, fact.output, fact.cacheRead, fact.cacheWrite)});\n }\n return;\n }\n if (m.role === 'user') {\n const c = classifyText(textOf(m.content));\n addPrompt(b, `pi:${f.sessionId}:${String(r.id)}`, at, f.project, c.kind, c.reason, c.text);\n }\n}\n\n/* ------------------------------------------------------------ driver --- */\n\nconst CHUNK = 4 * 1024 * 1024;\n/** Lines longer than this are skipped without being materialized. */\nconst MAX_LINE = 256 * 1024 * 1024;\n\nlet sharedBuffer: Buffer | null = null;\n\n/** Files touched within this window keep resume state: they are the ones still being appended to. */\nconst RESUME_RECENT_MS = 48 * 3_600_000;\n\n/** What an append-only file needs to continue where the last read stopped. Only kept for recently modified files. */\nexport interface ResumeState {\n /** Byte offset just after the last newline read. */\n offset: number;\n /** sha256 of the 4 KiB before `offset`. */\n tail: string;\n dev: number;\n ino: number;\n model: string | null;\n provider: string | null;\n /** [at, tools, subagents, weight] per assistant event. */\n events: Float64Array;\n interrupts: Float64Array;\n sessions?: string[];\n codex?: Omit<CodexState, 'itemPrompts' | 'responsePrompts'>;\n}\n\n/**\n * Reads one file once, in large chunks, and returns its facts. With\n * `previous` (facts of an earlier read that carry resume state) only the bytes\n * appended since are parsed; ResumeMismatch is thrown when the file is not\n * the same append-only file any more.\n */\nexport function extractFile(file: string, harness: NativeHarness, options: ExtractOptions = {}, previous?: SourceFacts): SourceFacts {\n const fd = fs.openSync(file, 'r');\n try {\n const stat = fs.fstatSync(fd);\n let b = makeBuilder(file, harness, stat.size, stat.mtimeMs);\n let codex = newCodexState();\n let position = 0, firstNew = 0;\n const subagent = file.includes(SUBAGENT_DIR), sessions = new Set<string>();\n if (previous) {\n const r = previous.resume;\n if (!r || previous.excluded || r.dev !== stat.dev || r.ino !== stat.ino || r.offset > stat.size || r.offset < 1 || tailHash(fd, r.offset) !== r.tail) throw new ResumeMismatch();\n const nl = Buffer.alloc(1);\n fs.readSync(fd, nl, 0, 1, r.offset - 1);\n if (nl[0] !== 10) throw new ResumeMismatch();\n b = resumeBuilder(previous, r, stat);\n if (r.codex) codex = {...structuredClone(r.codex), itemPrompts: [], responsePrompts: []};\n for (const sid of r.sessions ?? []) sessions.add(sid);\n position = r.offset;\n firstNew = b.facts.prompts.length;\n }\n const onLine = harness === 'claude' ? (line: Buffer) => claudeLine(b, line, subagent, sessions)\n : harness === 'codex' ? (line: Buffer) => codexLine(b, line, codex)\n : (line: Buffer) => piLine(b, line);\n // One read buffer per thread, reused across files (it only grows for very long lines).\n let buffer = sharedBuffer ??= Buffer.allocUnsafe(CHUNK);\n let filled = 0, skipping = false, base = position, endsWithNewline = true;\n for (;;) {\n if (filled === buffer.length) {\n // A line longer than the buffer: drop it unread unless its head says we need it.\n if (harness === 'codex' && !codexWanted(buffer.toString('latin1', 0, Math.min(filled, 400)), codex.lineNo)) { codexToolOrAbort(b, buffer.toString('latin1', 0, Math.min(filled, 400))); skipping = true; base += filled; filled = 0; codex.lineNo++; }\n else if (buffer.length >= MAX_LINE) { skipping = true; base += filled; filled = 0; b.facts.malformed++; }\n else { const bigger = Buffer.allocUnsafe(buffer.length * 2); buffer.copy(bigger, 0, 0, filled); buffer = bigger; if (bigger.length <= 4 * CHUNK) sharedBuffer = bigger; }\n }\n const n = fs.readSync(fd, buffer, filled, buffer.length - filled, position);\n position += n;\n const end = filled + n;\n let start = 0;\n for (;;) {\n const nl = buffer.indexOf(10, start);\n if (nl < 0 || nl >= end) break;\n if (skipping) skipping = false;\n else if (nl > start) onLine(buffer.subarray(start, nl));\n start = nl + 1;\n }\n if (n === 0) {\n if (start < end) { endsWithNewline = false; if (!skipping) onLine(buffer.subarray(start, end)); }\n base += start;\n break;\n }\n buffer.copyWithin(0, start, end);\n base += start;\n filled = end - start;\n }\n if (harness === 'codex') finishCodex(b, codex);\n if (harness === 'claude' && !subagent && sessions.size) b.facts.sessionIds = [...sessions];\n b.facts.size = stat.size;\n b.facts.mtimeMs = stat.mtimeMs;\n finishStory(b, harness, options, firstNew);\n delete b.facts.resume;\n if (endsWithNewline && !b.facts.excluded && Date.now() - stat.mtimeMs < RESUME_RECENT_MS) {\n const events = new Float64Array(b.events.length * 4);\n b.events.forEach((e, i) => { events[i * 4] = e.at; events[i * 4 + 1] = e.tools; events[i * 4 + 2] = e.subs; events[i * 4 + 3] = e.weight; });\n const {itemPrompts: _items, responsePrompts: _responses, ...codexState} = codex;\n b.facts.resume = {offset: base, tail: tailHash(fd, base), dev: stat.dev, ino: stat.ino, model: b.currentModel, provider: b.currentProvider,\n events, interrupts: Float64Array.from(b.interrupts), ...(sessions.size ? {sessions: [...sessions]} : {}), ...(harness === 'codex' ? {codex: codexState} : {})};\n }\n return b.facts;\n } finally {\n fs.closeSync(fd);\n }\n}\n\n/** A builder positioned where `previous` stopped: copies of its lists, pending prompts and events. */\nfunction resumeBuilder(previous: SourceFacts, r: ResumeState, stat: fs.Stats): Builder {\n const facts: SourceFacts = {...previous, size: stat.size, mtimeMs: stat.mtimeMs, usage: [...previous.usage], prompts: previous.prompts.map(p => ({...p})),\n ...(previous.sessionIds ? {sessionIds: [...previous.sessionIds]} : {}),\n ...(previous.story ? {story: {vocab: previous.story.vocab ? new Map(previous.story.vocab) : null, topics: previous.story.topics ? previous.story.topics.map(t => ({...t, words: new Map([...t.words].map(([w, c]) => [w, [c[0], c[1]] as [number, number]]))})) : null}} : {})};\n delete facts.resume;\n const b = makeBuilder(previous.file, previous.harness as NativeHarness, stat.size, stat.mtimeMs);\n b.facts = facts;\n b.currentModel = r.model; b.currentProvider = r.provider;\n for (const p of facts.prompts) b.seenPrompts.add(p.key);\n // Prompts after the last answer still wait for the model that answers them.\n for (let i = facts.prompts.length - 1; i >= 0; i--) { const p = facts.prompts[i]!; if (p.kind !== 'human') continue; if (p.after !== null) break; b.pending.unshift(p); }\n for (let i = 0; i < r.events.length; i += 4) b.events.push({at: r.events[i]!, tools: r.events[i + 1]!, subs: r.events[i + 2]!, weight: r.events[i + 3]!});\n b.interrupts.push(...r.interrupts);\n return b;\n}\n\nfunction finishStory(b: Builder, harness: AuditHarness, options: ExtractOptions, from = 0): void {\n const f = b.facts;\n f.tz = options.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone;\n if (f.excluded) { for (const p of f.prompts) { p.text = ''; delete p.f; delete p.lex; delete p.q; } delete f.story; return; }\n // Claude's typed text lives in history.jsonl; its transcripts expand pastes inline.\n f.story = deriveStory(f.prompts, b.events, b.interrupts, {typed: false, counters: harness !== 'claude' && !f.child, timezone: f.tz, from, previous: f.story});\n}\n\n/** Story fields for facts built outside `extractFile` (OpenCode). */\nexport function finishExternalFacts(facts: SourceFacts, options: ExtractOptions = {}): SourceFacts {\n const b = makeBuilder(facts.file, 'pi', facts.size, facts.mtimeMs);\n b.facts = facts;\n finishStory(b, facts.harness, options);\n return facts;\n}\n\n/** Drops prompt text (story features and lexical data stay). Used before facts leave a worker or enter the cache. */\nexport function stripText(facts: SourceFacts): SourceFacts {\n for (const p of facts.prompts) p.text = '';\n return facts;\n}\n\n/* ------------------------------------------------- Claude history.jsonl --- */\n\nexport interface HistoryEntry {\n sessionId: string | null;\n at: number | null;\n project: string | null;\n kind: PromptKind;\n /** Empty once stripped (cache); story fields below stay. */\n text: string;\n /** The user pasted content into this prompt. */\n paste?: boolean;\n f?: PromptFeatures;\n lex?: AuditPromptLex;\n /** Safe quote candidate (history prompts are short typed text; \u226490 chars, masked). */\n q?: string;\n}\n\n/** Story word counters of history.jsonl, per Claude session. */\nexport interface HistoryCounters {project: string | null; vocab: Map<string, number>; topics: Map<string, {night: number; day: number; words: Map<string, [number, number]>}>}\n\nexport interface HistoryData {\n entries: HistoryEntry[];\n /** Per session id ('' when missing). */\n counters: Map<string, HistoryCounters>;\n /** sha256 of the 4 KiB before the end of what was read (append-only resume check). */\n tail?: string;\n /** Lines appended since the previous run were parsed alone (diagnostics). */\n resumed?: boolean;\n /** Bytes parsed (whole lines). */\n bytes?: number;\n}\n\n/** sha256 of the `TAIL` bytes before `offset`. */\nexport function tailHash(fd: number, offset: number): string {\n const start = Math.max(0, offset - TAIL), buffer = Buffer.alloc(offset - start);\n let read = 0;\n while (read < buffer.length) { const n = fs.readSync(fd, buffer, read, buffer.length - read, start + read); if (!n) break; read += n; }\n return createHash('sha256').update(buffer.subarray(0, read)).digest('hex');\n}\nconst TAIL = 4096;\n\n/**\n * Reads history.jsonl; when `previous` covers a prefix of the file (same\n * bytes before its end, ending on a newline) only the appended tail is parsed.\n */\nexport function readHistory(file: string, options: ExtractOptions, previous: {data: HistoryData; size: number} | null): HistoryData {\n let fd: number;\n try { fd = fs.openSync(file, 'r'); } catch { return {entries: [], counters: new Map()}; }\n try {\n const size = fs.fstatSync(fd).size;\n if (previous && previous.data.tail && previous.size <= size && tailHash(fd, previous.size) === previous.data.tail) {\n const last = Buffer.alloc(1);\n fs.readSync(fd, last, 0, 1, previous.size - 1);\n if (last[0] === 10) {\n const tail = Buffer.alloc(size - previous.size);\n let read = 0;\n while (read < tail.length) { const n = fs.readSync(fd, tail, read, tail.length - read, previous.size + read); if (!n) break; read += n; }\n // Only whole lines: an unfinished last line is left for the next run.\n const end = tail.lastIndexOf(10, read - 1) + 1;\n const data = parseHistory(tail.toString('utf8', 0, end), options, {entries: [...previous.data.entries], counters: previous.data.counters});\n data.tail = tailHash(fd, previous.size + end);\n data.bytes = previous.size + end;\n data.resumed = true;\n return data;\n }\n }\n const raw = Buffer.alloc(size);\n let read = 0;\n while (read < size) { const n = fs.readSync(fd, raw, read, size - read, read); if (!n) break; read += n; }\n const end = raw.lastIndexOf(10, read - 1) + 1;\n const data = parseHistory(raw.toString('utf8', 0, end), options);\n data.tail = tailHash(fd, end);\n data.bytes = end;\n return data;\n } finally {\n fs.closeSync(fd);\n }\n}\n\n/**\n * `~/.claude/history.jsonl` is Claude Code's log of what the user typed. It\n * gives sessions whose transcript is gone, and the typed text (without\n * expanded pastes) of live ones: `display` starting with `/` is a slash\n * command, anything else a human prompt.\n */\nexport function extractHistory(file: string, options: ExtractOptions = {}): HistoryEntry[] {\n let raw: string;\n try { raw = fs.readFileSync(file, 'utf8'); } catch { return []; }\n return parseHistory(raw, options).entries;\n}\n\n/** Parses history lines into entries (with story features) and appends to `into`. */\nexport function parseHistory(raw: string, options: ExtractOptions = {}, into: HistoryData = {entries: [], counters: new Map()}): HistoryData {\n const clock = localClock(options.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone);\n for (const line of raw.split('\\n')) {\n if (!line) continue;\n let r: Rec;\n try { r = JSON.parse(line) as Rec; } catch { continue; }\n const display = typeof r.display === 'string' ? r.display.trim() : '';\n if (!display) continue;\n const command = display.startsWith('/');\n const text = command ? '' : clean(display.length > MAX_PROMPT_CHARS ? display.slice(0, MAX_PROMPT_CHARS) : display);\n const entry: HistoryEntry = {sessionId: str(r.sessionId), at: time(r.timestamp), project: str(r.project), kind: command ? 'command' : 'human', text};\n if (!command) {\n const pasted = isRec(r.pastedContents) && Object.keys(r.pastedContents).length > 0;\n if (pasted) entry.paste = true;\n entry.f = featurize({text, typed: true, hasPaste: pasted});\n const lex = promptLex(text, []);\n if (lex) entry.lex = lex;\n const q = safeQuote(text, 90);\n if (q) entry.q = q;\n const key = entry.sessionId ?? '';\n let c = into.counters.get(key);\n if (!c) { c = {project: entry.project, vocab: new Map(), topics: new Map()}; into.counters.set(key, c); }\n for (const w of vocabularyWords(text)) c.vocab.set(w, (c.vocab.get(w) ?? 0) + 1);\n if (entry.at !== null) {\n const {hour, month} = clock(entry.at);\n const slot = hour < 5 ? 0 : hour >= 9 && hour < 19 ? 1 : -1;\n if (slot >= 0) {\n let bag = c.topics.get(month);\n if (!bag) { bag = {night: 0, day: 0, words: new Map()}; c.topics.set(month, bag); }\n if (slot === 0) bag.night++; else bag.day++;\n for (const w of topicWords(text)) { let n = bag.words.get(w); if (!n) { n = [0, 0]; bag.words.set(w, n); } n[slot as 0 | 1]++; }\n }\n }\n }\n into.entries.push(entry);\n }\n return into;\n}\n", "/**\n * Opt-out markers: text that means \"do not index this conversation\".\n *\n * Ported from obra/episodic-memory@1075769 `src/constants.ts` (the summarizer\n * content marker, verbatim) and `src/sync.ts:7-11` (the exclusion list)\n * (MIT, (c) 2025 Jesse Vincent).\n *\n * Two of the three markers are upstream's own product strings and are kept\n * **verbatim on purpose**: a user who has been running episodic-memory has\n * these markers sitting in real transcripts already, and potsherd must honour\n * the opt-out they represent rather than re-indexing what they excluded.\n * potsherd's own marker is added alongside.\n */\n\n/** Upstream's summarizer prompt contains this, so its own runs never index. */\nexport const SUMMARIZER_CONTEXT_MARKER =\n 'Context: This summary will be shown in a list to help users and Claude choose which conversations are relevant';\n\n/** potsherd's equivalent, for the card writer in phase 2. */\nexport const POTSHERD_CARD_MARKER =\n '<INSTRUCTIONS-TO-POTSHERD>DO NOT INDEX THIS CHAT</INSTRUCTIONS-TO-POTSHERD>';\n\nexport const EXCLUSION_MARKERS: readonly string[] = [\n '<INSTRUCTIONS-TO-EPISODIC-MEMORY>DO NOT INDEX THIS CHAT</INSTRUCTIONS-TO-EPISODIC-MEMORY>',\n 'Only use NO_INSIGHTS_FOUND',\n SUMMARIZER_CONTEXT_MARKER,\n POTSHERD_CARD_MARKER,\n];\n\n/** True when a transcript's text opts out of indexing. */\nexport function hasExclusionMarker(text: string): boolean {\n return EXCLUSION_MARKERS.some((marker) => text.includes(marker));\n}\n", "import { createHash } from 'node:crypto';\nimport type { Exchange, ExchangeToolCall } from './adapters/types.js';\nimport { Theme } from './theme.js';\nimport type { Row } from './render.js';\nimport * as fmt from './format.js';\nimport {\n ALLOW_SPANS,\n RULES,\n SECRET_TYPES,\n type Rule,\n type SecretType,\n} from './redact-rules.js';\n\nexport type { SecretType } from './redact-rules.js';\n// The pre-redaction pass. Not redaction \u2014 it removes binary bulk that carries\n// no meaning for retrieval \u2014 but it runs immediately before this module on the\n// same strings, so it is re-exported here and the two are read together.\nexport {\n elideBinary,\n elideExchange,\n emptyElisions,\n addElisions,\n MIN_PAYLOAD,\n ELISION_RE,\n type Elisions,\n} from './redact-elide.js';\nexport {\n RULES,\n SECRET_TYPES,\n shannonEntropy,\n ENTROPY_MIN_LENGTH,\n ENTROPY_THRESHOLD,\n nameLooksLikeSecret,\n valueLooksLikeSecret,\n type Rule,\n} from './redact-rules.js';\n\n/**\n * L2 \u2014 redaction. `plans/03-ARCHITECTURE.md` \u00A75 and \u00A711.\n *\n * This module decides whether a user's secrets can ever leave their machine.\n * Nothing downstream of it \u2014 the index, cards, ask, graft \u2014 is allowed to see\n * an unredacted string, and every string that reaches a model passes through\n * here first. A false negative is a leaked credential; a false positive is one\n * unreadable token in a search result. The rules are tuned accordingly.\n *\n * Pure and synchronous by contract: no I/O, no network, no module state that\n * survives a call. It runs over the whole corpus at index time, so it also has\n * to be fast \u2014 see `tests/redact.test.ts` for the measured 10 MB throughput.\n *\n * ## The mask\n *\n * \u2039redacted:<type>:<sha8>\u203A e.g. \u2039redacted:aws:cccc2222\u203A\n *\n * `sha8` is the first 8 hex characters of sha256(secret), so the *same* secret\n * always produces the *same* mask: the index stays searchable by shape (\"that\n * session where the same aws key appeared\") and never by value. Two different\n * secrets colliding needs a 32-bit sha256 prefix collision.\n *\n * The guillemets are deliberate: `\u2039` U+2039 and `\u203A` U+203A cannot appear in a\n * shell token, a json key or a base64 blob, so the mask can never be confused\n * for content and can never be pasted back into a command by accident.\n *\n * fts5 tokenisation, measured against the bundled sqlite (default `unicode61`\n * tokenizer): `\u2039redacted:aws:cccc2222\u203A` indexes as the three tokens\n * `redacted`, `aws`, `cccc2222` \u2014 both guillemets and both colons are\n * separators. So `find \"cccc2222\"` locates every exchange that leaked that one\n * secret, `find \"redacted AND aws\"` locates every exchange that leaked an aws\n * key, and the phrase query `\"redacted:aws:cccc2222\"` also works. The mask\n * costs three tokens per hit in the index and nothing else.\n *\n * ## What redaction does NOT touch\n *\n * The archive copy (L3) is byte-exact and unredacted: it is the user's own file\n * on the user's own disk. Only the *index* is redacted. There is no\n * `--no-redact` flag (`03` \u00A711) and adding one is not a feature request.\n */\n\n/** A masked secret. `sha8` identifies it without revealing it. */\nexport interface RedactionHit {\n type: SecretType;\n /** Rule id that claimed it \u2014 `doctor` and false-positive triage. */\n rule: string;\n /** First 8 hex chars of sha256(secret). */\n sha8: string;\n /** Offset of the secret in the *input* text. */\n start: number;\n /** Length of the secret in the input text. */\n length: number;\n}\n\nexport interface RedactionResult {\n text: string;\n hits: RedactionHit[];\n}\n\n/** Counts by type, for `doctor`. */\nexport interface RedactionCounts {\n total: number;\n byType: Record<SecretType, number>;\n}\n\nconst OPEN = '\u2039';\nconst CLOSE = '\u203A';\n\n/** Matches potsherd's own mask, so a second pass recognises its output. */\nexport const MASK_RE = new RegExp(`${OPEN}redacted:[a-z-]+:[0-9a-f]{8}${CLOSE}`, 'g');\n\n/** The first 8 hex characters of sha256(secret). */\nexport function secretDigest(secret: string): string {\n return createHash('sha256').update(secret, 'utf8').digest('hex').slice(0, 8);\n}\n\n/** `\u2039redacted:aws:cccc2222\u203A` */\nexport function maskFor(type: SecretType, secret: string): string {\n return `${OPEN}redacted:${type}:${secretDigest(secret)}${CLOSE}`;\n}\n\n/** Does this text already contain a potsherd mask? */\nexport function containsMask(text: string): boolean {\n return new RegExp(MASK_RE.source).test(text);\n}\n\ninterface Span {\n start: number;\n end: number;\n}\n\n/**\n * Mask every secret in `text`.\n *\n * Rules are applied in `RULES` order and the first rule to claim a span keeps\n * it, which is why the table is ordered specific \u2192 generic \u2192 entropy: a jwt is\n * reported as a jwt and not as three high-entropy tokens, and the base64 body\n * of a private key is reported as one private key and not as forty.\n *\n * Idempotent: existing masks are protected spans, so `redact(redact(x).text)`\n * returns the same text with no further hits.\n */\nexport function redact(text: string): RedactionResult {\n if (typeof text !== 'string' || text.length === 0) return { text: text ?? '', hits: [] };\n\n // Claimed characters. One byte per input character: an O(1) overlap test that\n // stays honest when 40 rules each propose overlapping spans.\n const claimed = new Uint8Array(text.length);\n const spans: Array<Span & { rule: Rule; value: string }> = [];\n\n // Allowlisted regions (data URIs, SRI hashes) and this module's own masks are\n // claimed before any rule runs, so nothing can match inside them.\n for (const span of protectedSpans(text)) claim(claimed, span);\n\n for (const rule of RULES) {\n for (const m of rule.scan(text)) {\n if (m.start < 0 || m.end > text.length || m.end <= m.start) continue;\n if (isClaimed(claimed, m)) continue;\n claim(claimed, m);\n spans.push({ start: m.start, end: m.end, rule, value: m.value });\n }\n }\n\n if (spans.length === 0) return { text, hits: [] };\n spans.sort((a, b) => a.start - b.start);\n\n const out: string[] = [];\n const hits: RedactionHit[] = [];\n let cursor = 0;\n for (const s of spans) {\n out.push(text.slice(cursor, s.start));\n const sha8 = secretDigest(s.value);\n out.push(`${OPEN}redacted:${s.rule.type}:${sha8}${CLOSE}`);\n hits.push({ type: s.rule.type, rule: s.rule.id, sha8, start: s.start, length: s.end - s.start });\n cursor = s.end;\n }\n out.push(text.slice(cursor));\n return { text: out.join(''), hits };\n}\n\n/** Just the text, for the many callers that do not care what was masked. */\nexport function redactText(text: string): string {\n return redact(text).text;\n}\n\n/**\n * Redact one exchange in place of its unredacted self: `user_text`,\n * `assistant_text` and every `tool_calls.input` / `.result` (`03` \u00A75). Returns\n * a new object; the input is never mutated, because the caller may still be\n * writing the byte-exact archive copy from it.\n */\nexport function redactExchange(ex: Exchange): { exchange: Exchange; hits: RedactionHit[] } {\n const hits: RedactionHit[] = [];\n const one = (s: string): string => {\n const r = redact(s);\n if (r.hits.length) hits.push(...r.hits);\n return r.text;\n };\n\n const userText = one(ex.userText);\n const assistantText = one(ex.assistantText);\n const toolCalls: ExchangeToolCall[] = ex.toolCalls.map((tc) => {\n const next: ExchangeToolCall = { ...tc, input: one(tc.input) };\n if (tc.result !== undefined) next.result = one(tc.result);\n return next;\n });\n\n return {\n exchange: { ...ex, userText, assistantText, toolCalls, redacted: ex.redacted || hits.length > 0 },\n hits,\n };\n}\n\n// ---------------------------------------------------------------- counting\n\nexport function emptyCounts(): RedactionCounts {\n const byType = {} as Record<SecretType, number>;\n for (const t of SECRET_TYPES) byType[t] = 0;\n return { total: 0, byType };\n}\n\n/** Tally hits by type. `doctor` sums these across the whole index. */\nexport function tally(hits: Iterable<RedactionHit>, into: RedactionCounts = emptyCounts()): RedactionCounts {\n for (const h of hits) {\n into.byType[h.type] = (into.byType[h.type] ?? 0) + 1;\n into.total++;\n }\n return into;\n}\n\nexport function addCounts(a: RedactionCounts, b: RedactionCounts): RedactionCounts {\n const out = emptyCounts();\n out.total = a.total + b.total;\n for (const t of SECRET_TYPES) out.byType[t] = (a.byType[t] ?? 0) + (b.byType[t] ?? 0);\n return out;\n}\n\n/** `{ total, aws: 3, jwt: 12 }` \u2014 the `--json` shape for `doctor`. */\nexport function countsJson(c: RedactionCounts): Record<string, number> {\n const out: Record<string, number> = { total: c.total };\n for (const t of SECRET_TYPES) if ((c.byType[t] ?? 0) > 0) out[t] = c.byType[t] ?? 0;\n return out;\n}\n\n/**\n * The `doctor` line (`03` \u00A75: \"`potsherd doctor` reports redaction counts by\n * type\"), in the house style of `render.ts`:\n *\n * secrets masked 1,284 jwt 512 \u00B7 entropy 402 \u00B7 aws 12\n *\n * The note lists types by count, biggest first, and elides rather than wraps \u2014\n * `render.ts` never wraps a row. Wired into the doctor card by T1.5; kept here\n * so the counts and the way they are said stay in one file.\n */\nexport function redactionRow(\n c: RedactionCounts,\n t: Theme = new Theme(),\n noteWidth = 43,\n): Row {\n const parts = SECRET_TYPES.filter((k) => (c.byType[k] ?? 0) > 0)\n .sort((a, b) => (c.byType[b] ?? 0) - (c.byType[a] ?? 0))\n .map((k) => `${k} ${fmt.num(c.byType[k] ?? 0)}`);\n const note = parts.length === 0\n ? 'nothing matched \u2014 index holds no secrets'\n : fmt.joinFit(parts, noteWidth, ` ${t.mid} `, t.ellip);\n return {\n label: 'secrets masked',\n value: fmt.num(c.total),\n note,\n tone: c.total > 0 ? 'ok' : 'dim',\n };\n}\n\n/** One plain line, for logs and for `doctor` in a non-card context. */\nexport function redactionLine(c: RedactionCounts, t: Theme = new Theme()): string {\n const row = redactionRow(c, t, Math.max(20, t.width - 30));\n return `${row.label.padEnd(22)}${(row.value ?? '').padStart(7)} ${t.dim(row.note ?? '')}`;\n}\n\n// ---------------------------------------------------------------- internals\n\nfunction protectedSpans(text: string): Span[] {\n const spans: Span[] = [];\n const patterns = [MASK_RE, ...ALLOW_SPANS];\n for (const p of patterns) {\n const rx = new RegExp(p.source, p.flags.includes('g') ? p.flags : p.flags + 'g');\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n if (m[0].length === 0) { rx.lastIndex++; continue; }\n spans.push({ start: m.index, end: m.index + m[0].length });\n }\n }\n return spans;\n}\n\nfunction isClaimed(claimed: Uint8Array, s: Span): boolean {\n for (let i = s.start; i < s.end; i++) if (claimed[i]) return true;\n return false;\n}\n\nfunction claim(claimed: Uint8Array, s: Span): void {\n const end = Math.min(s.end, claimed.length);\n for (let i = Math.max(0, s.start); i < end; i++) claimed[i] = 1;\n}\n\n/** Legacy projections have no immutable text-hash contract; mask on public read.\n * Canonical evidence/notes must instead refuse an unsafe old immutable value.\n */\nexport function redactLegacyProjection<T>(value:T):T{\n const visit=(input:unknown):{value:unknown;changed:boolean}=>{\n if(typeof input==='string'){const clean=redact(input).text;return {value:clean,changed:clean!==input};}\n if(Array.isArray(input)){const items=input.map(visit);return {value:items.map(item=>item.value),changed:items.some(item=>item.changed)};}\n if(input&&typeof input==='object'&&Object.getPrototypeOf(input)===Object.prototype){const output:Record<string,unknown>={};let changed=false;for(const [key,child] of Object.entries(input)){const result=visit(child);output[key]=result.value;changed ||= result.changed;}if(changed){if('redacted' in output)output.redacted=true;if('text' in output&&'match' in output)output.match=null;output.redactionRefreshed=true;}return {value:output,changed};}\n return {value:input,changed:false};\n };return visit(value).value as T;\n}\n", "import process from 'node:process';\n\n/**\n * The terminal design system, in code (plans/05-SHAREABLE-EXPERIENCE.md).\n *\n * Rules this module enforces so no verb can break them:\n * - never more than three colours on screen: accent, warn, ok. Everything\n * else is `dim` or default.\n * - NO_COLOR and --no-color are honoured; a non-TTY stdout is never coloured.\n * - --ascii replaces every non-ASCII glyph, so the output survives a terminal\n * with no unicode font and a screenshot taken on Windows. Two mechanisms,\n * because one was demonstrably forgettable: {@link Theme.g} picks the\n * fallback where the glyph is chosen, and {@link Theme.asciiLine} folds\n * whatever still got through \u2014 an em dash typed into a note, a `\u00B7` an\n * adapter wrote, an emoji in someone's own prompt. `render.ts` runs every\n * line it emits through the fold, so no verb can opt out by forgetting.\n */\n\nexport interface ThemeOptions {\n color?: boolean;\n ascii?: boolean;\n width?: number;\n}\n\nconst CSI = '\\u001b[';\n\nexport class Theme {\n readonly color: boolean;\n readonly ascii: boolean;\n readonly width: number;\n\n constructor(opts: ThemeOptions = {}) {\n this.color = opts.color ?? detectColor();\n this.ascii = opts.ascii ?? detectAscii();\n this.width = opts.width ?? detectWidth();\n }\n\n private wrap(code: string, s: string): string {\n return this.color ? `${CSI}${code}m${s}${CSI}0m` : s;\n }\n\n /** The single most important number on the screen. Exactly one per card. */\n accent(s: string): string { return this.wrap('38;5;209', s); }\n /** Urgency: something is about to be lost. */\n warn(s: string): string { return this.wrap('38;5;214', s); }\n /** Done, saved, safe. */\n ok(s: string): string { return this.wrap('38;5;71', s); }\n /** Secondary text: units, notes, sources. */\n dim(s: string): string { return this.wrap('2', s); }\n bold(s: string): string { return this.wrap('1', s); }\n\n /** Pick a glyph, with an ASCII fallback for --ascii / non-unicode terminals. */\n g(unicode: string, fallback: string): string {\n return this.ascii ? fallback : unicode;\n }\n\n get arrow(): string { return this.g('\u2192', '->'); }\n get mid(): string { return this.g('\u00B7', '.'); }\n get sep(): string { return this.g('\u00B7', '|'); }\n get ellip(): string { return this.g('\u2026', '...'); }\n get star(): string { return this.g('\u2605', '*'); }\n get le(): string { return this.g('\u2264', '<='); }\n get bullet(): string { return this.g('\u2022', '-'); }\n /** The em dash that stands in for \"no number here\". */\n get dash(): string { return this.g('\u2014', '-'); }\n\n /**\n * Fold one rendered line to pure ASCII, when `--ascii` is on.\n *\n * Applied at the very end, after the line has been fitted to the terminal\n * width, so **every substitution is exactly one character wide or narrower**.\n * That is the whole design constraint: `\u2026` \u2192 `...` here would push a line\n * that just fitted 80 columns to 82. The three-character ellipsis comes from\n * {@link ellip}, which the width arithmetic sees; this is only the net.\n */\n asciiLine(s: string): string {\n return this.ascii ? toAscii(s) : s;\n }\n\n /** Visible width, ignoring ANSI escapes. */\n static len(s: string): number {\n return stripAnsi(s).length;\n }\n}\n\n/**\n * The glyphs the design system uses, and their one-character ASCII stand-ins.\n * Anything not listed is decomposed (`\u00E9` \u2192 `e`) and, failing that, becomes a\n * single `?` \u2014 never silently dropped, because a vanished character is a\n * vanished fact.\n */\nconst ASCII_FOLD: Record<string, string> = {\n '\u2026': '.', '\u00B7': '.', '\u2022': '*', '\u2027': '.', '\u2219': '.',\n '\u2014': '-', '\u2013': '-', '\u2012': '-', '\u2212': '-', '\u2015': '-',\n '\u2192': '>', '\u21D2': '>', '\u2190': '<', '\u21D0': '<', '\u2191': '^', '\u2193': 'v',\n '\u2264': '<', '\u2265': '>', '\u2260': '!', '\u00B1': '~', '\u00D7': 'x', '\u00F7': '/',\n '\u2605': '*', '\u2606': '*', '\u2713': 'v', '\u2714': 'v', '\u2717': 'x', '\u2718': 'x',\n '\u2039': '<', '\u203A': '>', '\u00AB': '<', '\u00BB': '>',\n '\u201C': '\"', '\u201D': '\"', '\u201E': '\"', '\u2018': \"'\", '\u2019': \"'\", '\u201A': \"'\",\n '\u2588': '#', '\u2587': '#', '\u2593': '#', '\u2592': '+', '\u2591': '.', '\u25A0': '#', '\u25A1': '.',\n '\u2502': '|', '\u2500': '-', '\u250C': '+', '\u2510': '+', '\u2514': '+', '\u2518': '+', '\u251C': '+',\n '\u2524': '+', '\u252C': '+', '\u2534': '+', '\u253C': '+', '\u00B0': 'o', '\u00A7': 'S', '\u00B6': 'P',\n '\\u00a0': ' ', '\\u2007': ' ', '\\u2009': ' ', '\\u202f': ' ', '\\ufeff': '',\n};\n\n/**\n * Every non-ASCII code point replaced by one that is, without ever making the\n * string longer (measured in characters, which is what a terminal column is).\n * Surrogate pairs count as the one character they display as.\n */\nexport function toAscii(s: string): string {\n // eslint-disable-next-line no-control-regex\n if (!/[^\\x00-\\x7F]/.test(s)) return s;\n let out = '';\n for (const ch of s) {\n if (ch.charCodeAt(0) < 128 && ch.length === 1) { out += ch; continue; }\n const mapped = ASCII_FOLD[ch];\n if (mapped !== undefined) { out += mapped; continue; }\n // `\u00E9` is `e` plus a combining acute; drop the accent and keep the letter.\n const bare = ch.normalize('NFD').replace(/[\\u0300-\\u036f]/g, '');\n // eslint-disable-next-line no-control-regex\n out += bare.length === 1 && !/[^\\x00-\\x7F]/.test(bare) ? bare : '?';\n }\n return out;\n}\n\nconst ANSI_RE = new RegExp('\\\\u001b\\\\[[0-9;]*m', 'g');\n\nexport function stripAnsi(s: string): string {\n return s.replace(ANSI_RE, '');\n}\n\nfunction detectColor(): boolean {\n if (process.env.NO_COLOR !== undefined && process.env.NO_COLOR !== '') return false;\n if (process.env.FORCE_COLOR && process.env.FORCE_COLOR !== '0') return true;\n if (process.env.TERM === 'dumb') return false;\n return Boolean(process.stdout.isTTY);\n}\n\nfunction detectAscii(): boolean {\n if (process.env.POTSHERD_ASCII === '1') return true;\n const enc = `${process.env.LC_ALL ?? process.env.LC_CTYPE ?? process.env.LANG ?? ''}`;\n if (enc && !/utf-?8/i.test(enc)) return true;\n return false;\n}\n\nfunction detectWidth(): number {\n const cols = process.stdout.columns;\n if (!cols || cols < 40) return 80;\n return Math.min(cols, 100);\n}\n", "/**\n * L2 redaction \u2014 the rule table.\n *\n * ## Provenance (read this before adding a rule)\n *\n * `plans/03-ARCHITECTURE.md` \u00A75 and the reuse table in\n * `plans/02-STRATEGY-AND-VIRALITY.md` are explicit: **port rules, do not write\n * regexes from memory**. Every pattern below is a port of a published,\n * MIT-licensed detection rule, and each rule names its upstream rule id in\n * `source` and in the comment above it.\n *\n * Upstreams:\n *\n * gitleaks \u2014 https://github.com/gitleaks/gitleaks\n * rule pack: `cmd/generate/config/rules/*.go`, published as\n * `config/gitleaks.toml`.\n * Copyright (c) 2019 Zachary Rice. Licensed under the MIT License.\n *\n * secretlint \u2014 https://github.com/secretlint/secretlint\n * rule pack: `@secretlint/secretlint-rule-preset-recommend`, which bundles\n * `-rule-aws`, `-rule-gcp`, `-rule-github`, `-rule-slack`, `-rule-npm`,\n * `-rule-privatekey`, `-rule-basicauth`, `-rule-sendgrid`, `-rule-shopify`.\n * Copyright (c) 2020 Secretlint. Licensed under the MIT License.\n *\n * Neither project's *runtime* is a dependency. secretlint's engine is async,\n * plugin-loading and file-oriented; this module has to be pure, synchronous and\n * cheap enough to run over the whole corpus during `potsherd index`. What is\n * taken is the rule knowledge \u2014 the part that must not be invented. See\n * the header of every rule below. The `NOTICE` entry for both packs lands with\n * T1.5, when this module is first wired into the index.\n *\n * ## What a rule is\n *\n * A scanner over a string returning the spans to mask, a `type` that appears in\n * the mask, and a stable `id`. Rules are applied in array order and the first\n * rule to claim a span wins (see `redact.ts`), so the order here is the\n * precedence order: key material, vendor tokens, credentials in urls, the\n * generic `KEY=` assignment, entropy last.\n *\n * `type` deliberately names a *family* (`aws`, `github`) and not the rule\n * (`aws-access-key-id`): it is user-visible inside the mask, so it stays short,\n * stable and legible in a search result. The rule id rides along on the hit,\n * for `doctor` and for debugging a false positive.\n */\n\n/** The family name that appears in `\u2039redacted:<type>:<sha8>\u203A`. */\nexport type SecretType =\n | 'aws'\n | 'gcp'\n | 'github'\n | 'slack'\n | 'stripe'\n | 'openai'\n | 'anthropic'\n | 'npm'\n | 'jwt'\n | 'private-key'\n | 'basic-auth'\n | 'generic'\n | 'entropy';\n\n/** Every type, in the order `doctor` reports them. */\nexport const SECRET_TYPES: readonly SecretType[] = [\n 'aws',\n 'gcp',\n 'github',\n 'slack',\n 'stripe',\n 'openai',\n 'anthropic',\n 'npm',\n 'jwt',\n 'private-key',\n 'basic-auth',\n 'generic',\n 'entropy',\n] as const;\n\n/** One span of text a rule wants masked. */\nexport interface RuleMatch {\n start: number;\n end: number;\n value: string;\n}\n\nexport interface Rule {\n /** Stable id, reported on the hit and used in tests. */\n id: string;\n type: SecretType;\n /** Upstream rule this was ported from, with its licence. */\n source: string;\n /** Pure: same input, same output, no state carried between calls. */\n scan(text: string): RuleMatch[];\n}\n\n// ---------------------------------------------------------------- entropy\n\n/**\n * Shannon entropy in bits per character. `03` \u00A75 fixes the threshold at 4.5\n * over tokens of \u2265 20 characters.\n *\n * Worth knowing before either number is tuned: entropy measured on a sample of\n * length n cannot exceed log2(n), so a 20-character token can never reach 4.5\n * (log2(20) = 4.32) and nothing shorter than 23 characters can trip this rule\n * at all. That is why 40-char hex git shas (alphabet cap 4.0) and uuids pass\n * through untouched \u2014 the threshold in `03` is self-limiting by design.\n */\nexport function shannonEntropy(s: string): number {\n const n = s.length;\n if (n === 0) return 0;\n const counts = new Map<string, number>();\n for (const ch of s) counts.set(ch, (counts.get(ch) ?? 0) + 1);\n let h = 0;\n for (const c of counts.values()) {\n const p = c / n;\n h -= p * Math.log2(p);\n }\n return h;\n}\n\nexport const ENTROPY_MIN_LENGTH = 20;\nexport const ENTROPY_THRESHOLD = 4.5;\n\n// ---------------------------------------------------------------- allowlists\n\n/**\n * Spans that are never a secret and must not be scanned at all. Ported in\n * spirit from gitleaks' `[[rules.allowlist]] regexes` and secretlint's `allows`\n * option (both MIT).\n *\n * A base64 data URI is the worst false positive in a coding transcript: an\n * inlined PNG is tens of kilobytes of maximum-entropy base64 that no rule could\n * tell from a key. It is excluded by construction rather than by lowering a\n * threshold that would then start missing real keys.\n */\nexport const ALLOW_SPANS: RegExp[] = [\n // data: URIs \u2014 `data:image/png;base64,iVBORw0KGgo\u2026`\n /\\bdata:[a-zA-Z0-9!#$&^_.+-]*(?:\\/[a-zA-Z0-9!#$&^_.+-]*)?(?:;[a-zA-Z0-9-]+=[^;,\\s]*)*;base64,[A-Za-z0-9+/=]{20,}(?:\\s+[A-Za-z0-9+/=]{20,})*/g,\n // Subresource Integrity \u2014 `integrity=\"sha384-oqVuAfXRKap7fdgcCY5uykM6+R9\u2026\"`\n /\\bsha(?:256|384|512)-[A-Za-z0-9+/]{20,}={0,3}/g,\n];\n\nconst UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\nconst HEX_RE = /^[0-9a-fA-F]+$/;\nconst NUMERIC_RE = /^[0-9_+-]+$/;\n\n// -------------------------------------------------- entropy-rule exclusions\n//\n// Each of these answers a false-positive class *measured* on the reference\n// corpus by `scripts/redaction-benchmark.mjs`, and each is named and commented\n// so a future reader can audit \u2014 or delete \u2014 one of them on its own merits.\n//\n// The load-bearing property of all of them: they apply **only to a bare token\n// the entropy rule found lying in the text with no context**. A value that is\n// assigned to a secret-named key, sent in an `Authorization` header or put in\n// a url's userinfo is claimed by a rule that runs earlier and never consults\n// this list. So \"exclude uuids\" cannot let `API_KEY=<uuid>` through, and\n// \"exclude `toolu_\u2026`\" cannot let `ANTHROPIC_API_KEY=toolu_\u2026` through. Both are\n// planted cases in `tests/fixtures/secrets/planted.jsonl`.\n\n/**\n * **E1 \u2014 minted object ids.** Model apis and agent harnesses stamp every\n * message, request, tool use and run with a random id under a fixed prefix.\n * They are the densest high-entropy shape in an agent transcript by an order\n * of magnitude \u2014 `toolu_014ZfaccgxvcYNpcTLq8qvkR` and its kin \u2014 and none of\n * them is a credential: they are handed out in api *responses*, they appear in\n * public logs, and they authorise nothing.\n *\n * Prefixes, and who mints them:\n * toolu_ srvtoolu_ msg_ req_ anthropic messages api\n * chatcmpl- fc_ call_ run_ step_\n * thread_ asst_ resp_ evt_ openai\n * exec- exec_ agent- sess_ session_ agent harnesses (claude code, codex)\n * task_ job_ turn_ conv_ snapshot- harness bookkeeping\n *\n * Deliberately *not* here: `sk_`, `rk_`, `ghp_`, `xoxb-`, `npm_`, `AKIA`,\n * `sk-ant-`, `tvly-` \u2014 every one of those prefixes means the opposite.\n */\nconst MINTED_ID_RE =\n /^(?:toolu|srvtoolu|msg|req|resp|call|fc|run|step|thread|asst|evt|sess|session|exec|job|task|turn|conv|agent|snapshot|chatcmpl)[-_]/i;\n\n/**\n * **E5 \u2014 ULIDs.** 26 characters of Crockford base32, the first 10 encoding a\n * millisecond timestamp. log2(26) = 4.70, so a ULID can and does clear the 4.5\n * bar. Sortable ids, not secrets; the alphabet excludes I, L, O and U on\n * purpose, which is what makes the shape recognisable.\n */\nconst ULID_RE = /^[0-7][0-9ABCDEFGHJKMNPQRSTVWXYZ]{25}$/;\n\n/**\n * **E6 \u2014 prose wearing a token's clothes.** The single largest surviving false\n * positive on the reference corpus once images were elided: url slugs.\n *\n * \u2026%2Fy-combinator_reducto-has-just-raised-a-75m-series-b-activity-7383909473913880576-ba7M\n *\n * That is 87 characters over a wide alphabet, so its Shannon entropy is 4.9 \u2014\n * comfortably \"random\" by the measure in `03` \u00A75 \u2014 and it is a LinkedIn\n * permalink. Shannon entropy on a single short sample cannot tell *random*\n * from *varied*, and English is very varied.\n *\n * What separates them is **runs**. A base64 or base62 credential draws each\n * character independently, so a run of 7 consecutive same-case letters has\n * probability \u2248 (26/64)^7 \u2248 1 in 900 per position; two disjoint such runs in\n * one 40-character token is well under 1%. English words are nothing but such\n * runs \u2014 `combinator`, `activity`, `whatsapp`, `killmonger`.\n *\n * So: two runs of \u2265 7 same-case letters, or one run of \u2265 12, and the token is\n * text. Both numbers were checked against the corpus rather than chosen: at\n * \u2265 7/\u00D72 every tavily key, every planted secret and every base64 fixture value\n * survives (their longest same-case run is 4), and the slug class disappears.\n */\nconst SAMECASE_RUN_MIN = 7;\nconst SAMECASE_RUNS_NEEDED = 2;\nconst SAMECASE_RUN_ALONE = 12;\n\nfunction looksLikeProse(token: string): boolean {\n let long = 0;\n for (const run of token.match(/[a-z]+|[A-Z]+/g) ?? []) {\n if (run.length >= SAMECASE_RUN_ALONE) return true;\n if (run.length >= SAMECASE_RUN_MIN) long += 1;\n }\n return long >= SAMECASE_RUNS_NEEDED;\n}\n\n/**\n * **E7 \u2014 alphabet constants.** `0123456789ABCDEFGHJKMNPQRSTVWXYZ` is the\n * Crockford base32 table; every base32/base58/base62 encoder in every codebase\n * declares one, and with no repeated character it scores a perfect log2(n)\n * entropy \u2014 the highest possible.\n *\n * The test is exactly \"no character occurs twice\". Drawing 24 characters from\n * a 62-character alphabet without a single repeat happens with probability\n * \u2248 1%, and from base64url's 64 with probability \u2248 1.4%; combined with the\n * 24-character floor and with the fact that a credential in any real context\n * is claimed by an earlier rule, this is a safe trade for a class that is\n * otherwise permanently unmaskable-looking.\n */\nfunction looksLikeAlphabetConstant(token: string): boolean {\n return token.length >= 24 && new Set(token).size === token.length;\n}\n\n/**\n * Placeholder values. Ported from gitleaks' `stopwords` list and secretlint's\n * dummy-value handling, trimmed to the ones that actually occur in coding\n * transcripts. A value matching this is documentation, not a credential.\n */\nconst PLACEHOLDER_RE =\n /(?:^|[^a-z0-9])(?:x{3,}|your|my[-_]?(?:key|token|secret|pass)|example|sample|dummy|fake|mock|placeholder|change[-_]?(?:me|it|this)|replace[-_]?me|insert|todo|fixme|redacted|hidden|omitted|elided|not[-_]?real|no[-_]?such|hunter2|password|passwd|secret|token|apikey|api[-_]key|abcdef|123456|s3cret|letmein|foobar|lorem|ipsum)(?:$|[^a-z0-9])/i;\n\n/** `${VAR}`, `{{var}}`, `%(var)s`, `<%= x %>`, `<your-key>`, `$VAR` \u2026 */\nconst INTERPOLATION_RE = /\\$\\{|\\{\\{|%\\(|<%|^\\$[A-Za-z_(]|^<|^\\{|\\}$|^%[A-Za-z(]/;\n\n/** A reference to a value rather than the value: `process.env.X`, `cfg.token`. */\nconst REFERENCE_RE =\n /^(?:process\\.env|import\\.meta\\.env|os\\.environ|System\\.getenv|Deno\\.env|env|ENV|config|conf|cfg|settings|opts|options|args|argv|params|props|state|data|input|payload|body|req|res|ctx|context|self|this|that|obj|row|item|user|account|creds|credentials|secrets|vault|store|keychain)\\b\\s*[.[(]/;\n\n/** A bare word with no digits \u2014 `hashedPassword`, `MY_SECRET`, `undefined`. */\nconst WORDY_IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z_$]*$/;\n\n/**\n * A dotted identifier chain \u2014 `crypto.randomBytes`, `formData.password`,\n * `settings.auth.token`. Code reaching for a value, not the value. Base64,\n * base64url and hex credentials never contain a `.`, and the ones that do\n * (jwts) have a rule of their own that runs first.\n */\nconst DOTTED_CHAIN_RE = /^[A-Za-z_$][A-Za-z0-9_$]*(?:\\.[A-Za-z_$][A-Za-z0-9_$]*)+$/;\n\n/** A url or a filesystem path, not a credential. */\nconst PATHISH_RE = /^(?:[a-z][a-z0-9+.-]*:\\/\\/|\\.{0,2}\\/|~\\/|[A-Za-z]:\\\\)/;\n\n/** Syntax that means the capture ran into code, not into a credential. */\nconst CODEY_RE = /[<>{}[\\]()|\\\\;,&?!*\"'`]/;\n\n/** The mask itself, so a second pass recognises its own output. */\nexport const MASK_FRAGMENT_RE = /\u2039redacted:/;\n\n/** English words ending in a keyword that never name a secret. */\nconst NAME_STOPWORDS = new Set([\n 'monkey',\n 'donkey',\n 'turkey',\n 'whiskey',\n 'jockey',\n 'hockey',\n 'lackey',\n 'mickey',\n 'malarkey',\n 'hotkey',\n 'sortkey',\n 'oauth',\n]);\n\n/**\n * Does this identifier name a secret? `apiKey`, `AWS_SECRET_ACCESS_KEY`,\n * `db.password`, `client_secret` yes; `tokenizer`, `keyboard`, `monkey` no.\n *\n * Ported from the keyword half of gitleaks' `generic-api-key` and tightened:\n * that rule allows the keyword anywhere inside a 50-character identifier, which\n * flags every `tokenizer:` and `keyboardShortcut:` line in a transcript. Here\n * the keyword has to be the identifier's last segment, splitting on `_ - . $`\n * and on camelCase humps.\n */\nexport function nameLooksLikeSecret(name: string): boolean {\n const segments = name\n .split(/[^A-Za-z0-9]+/)\n .flatMap((part) => part.split(/(?<=[a-z0-9])(?=[A-Z])/))\n .filter(Boolean);\n const last = segments[segments.length - 1];\n if (!last) return false;\n const lower = last.toLowerCase();\n if (NAME_STOPWORDS.has(lower)) return false;\n return /(?:key|token|secret|password|passwd|pwd|credential|auth)s?$/.test(lower);\n}\n\n/**\n * Is this assignment's value plausibly a real credential?\n *\n * The generic `KEY=` rule is where false positives come from, because every\n * codebase assigns to something called `token`. Everything rejected here is\n * something transcripts are full of: env lookups, template interpolations,\n * references to another variable, documentation placeholders, type\n * annotations, version numbers, paths.\n */\nexport function valueLooksLikeSecret(value: string): boolean {\n const v = value.trim();\n if (v.length < 10 || v.length > 200) return false;\n if (/\\s/.test(v)) return false;\n if (MASK_FRAGMENT_RE.test(v)) return false;\n if (CODEY_RE.test(v)) return false;\n if (INTERPOLATION_RE.test(v)) return false;\n if (REFERENCE_RE.test(v)) return false;\n if (DOTTED_CHAIN_RE.test(v)) return false;\n if (PATHISH_RE.test(v)) return false;\n if (NUMERIC_RE.test(v)) return false;\n if (PLACEHOLDER_RE.test(v)) return false;\n // A bare word with no digits is a variable name or a sentence fragment, not\n // a 32-character credential.\n if (WORDY_IDENTIFIER_RE.test(v) && shannonEntropy(v) < 4.0) return false;\n // Filler: `****`, `------`, `0000000000`.\n if (new Set(v).size <= 2) return false;\n // gitleaks' generic-api-key requires 3.5 bits on the captured value. 3.2\n // here: potsherd masks a token in an index rather than failing a build, so a\n // marginal hit costs one unreadable word in a search result and a marginal\n // miss costs a leaked credential.\n if (shannonEntropy(v) < 3.2) return false;\n return true;\n}\n\n/**\n * Entropy-rule allowlist: shapes that are high-entropy but never secret.\n *\n * Every `return false` is an exclusion rule with a letter, defined above with\n * the class it was measured against. Read the block comment there before\n * adding, removing or relaxing one.\n *\n * This is consulted **only** by the bare-token entropy rule. It is not part of\n * `valueLooksLikeSecret`, so nothing here can excuse a value that appears in a\n * credential-shaped position.\n */\nexport function entropyCandidateAllowed(token: string): boolean {\n if (token.length < ENTROPY_MIN_LENGTH) return false;\n // E2 \u2014 uuids. Session ids, request ids, trace ids. Capped at 4.0 bits by\n // their alphabet anyway; excluded explicitly so the intent is readable.\n if (UUID_RE.test(token)) return false;\n // E2b \u2014 a uuid under a prefix: `exec-<uuid>`, `agent-<uuid>`, `snapshot-\u2026`.\n if (UUID_RE.test(token.replace(/^[A-Za-z][A-Za-z0-9]{0,15}[-_]/, ''))) return false;\n // E3 \u2014 hex digests: git sha1s, sha256 sums, md5s, content hashes.\n if (HEX_RE.test(token)) return false;\n // E4 \u2014 a hex digest under a prefix (`sha256-\u2026` without the SRI base64 body,\n // `blake3-\u2026`, `md5-\u2026`). The base64 SRI form is an ALLOW_SPAN, above.\n if (/^(?:sha1|sha256|sha384|sha512|md5|blake3|crc32|xxh64)[-_:]/i.test(token)) return false;\n if (NUMERIC_RE.test(token)) return false;\n if (MASK_FRAGMENT_RE.test(token)) return false;\n if (PLACEHOLDER_RE.test(token)) return false;\n if (MINTED_ID_RE.test(token)) return false; // E1\n if (ULID_RE.test(token)) return false; // E5\n if (looksLikeProse(token)) return false; // E6\n if (looksLikeAlphabetConstant(token)) return false; // E7\n return true;\n}\n\n// ---------------------------------------------------------------- machinery\n\ninterface RegexRuleOptions {\n /** Capture group holding the bytes to mask. 0 = the whole match. */\n group?: number;\n /** Reject a candidate; returning false leaves the text untouched. */\n validate?: (value: string, m: RegExpExecArray) => boolean;\n}\n\n/** Build a scanning rule from one global regex. */\nfunction regexRule(\n id: string,\n type: SecretType,\n source: string,\n re: RegExp,\n opts: RegexRuleOptions = {},\n): Rule {\n const group = opts.group ?? 0;\n return {\n id,\n type,\n source,\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n // A fresh regex per scan: a module-level `lastIndex` is shared state and\n // this module promises purity.\n const rx = new RegExp(re.source, re.flags.includes('g') ? re.flags : re.flags + 'g');\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n if (m[0].length === 0) { rx.lastIndex++; continue; }\n const value = group === 0 ? m[0] : m[group];\n if (value === undefined || value.length === 0) continue;\n if (opts.validate && !opts.validate(value, m)) continue;\n const offset = group === 0 ? 0 : m[0].indexOf(value);\n if (offset < 0) continue;\n out.push({ start: m.index + offset, end: m.index + offset + value.length, value });\n }\n return out;\n },\n };\n}\n\n// ---------------------------------------------------------------- the rules\n\n/**\n * The generic `(KEY|TOKEN|SECRET|PASSWORD)\\s*[=:]` rule from `03` \u00A75, given the\n * shape of gitleaks' `generic-api-key`.\n *\n * It is written as a scanner rather than one regex for two reasons. Speed: a\n * pattern of the form `identifier{0,48}(keyword)[:=]` has to be retried at\n * every letter of a 10 MB corpus, while anchoring on the literal keyword lets\n * the engine skip. Correctness: only the *value* is masked, never the name, so\n * `TOKEN=\u2039redacted:generic:\u2026\u203A` still tells a reader which variable leaked.\n */\nconst GENERIC_ANCHOR =\n /(?:key|token|secret|password|passwd|pwd|credential|auth)s?[\"']?[ \\t]*(?::=|=>|[:=])/gi;\n\nconst GENERIC_VALUE =\n // The bare alternative stops at a backslash on purpose: transcripts carry\n // json-escaped text, where `TOKEN=abc\\nNEXT=\u2026` is one line and the `\\n` is\n // two literal characters. Without this the capture swallows the rest of the\n // record and the value is thrown out as code.\n /[ \\t]*(?:\"([^\"\\r\\n]{10,200})\"|'([^'\\r\\n]{10,200})'|`([^`\\r\\n]{10,200})`|([^\\s\"'`,;)\\](}>\\\\]{10,200}))/y;\n\nconst NAME_CHAR_RE = /[A-Za-z0-9_$.-]/;\n\nconst genericAssignmentRule: Rule = {\n id: 'generic-assignment',\n type: 'generic',\n source: '03 \u00A75, given the shape of gitleaks generic-api-key (MIT)',\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n const anchor = new RegExp(GENERIC_ANCHOR.source, GENERIC_ANCHOR.flags);\n let m: RegExpExecArray | null;\n while ((m = anchor.exec(text)) !== null) {\n const opEnd = m.index + m[0].length;\n const opLen = /(?::=|=>)$/.test(m[0]) ? 2 : 1;\n const before = text[opEnd - opLen - 1] ?? '';\n // `==`, `===`, `!=`, `<=`, `>=`, `+=` are comparisons and compound\n // assignment, not `TOKEN=\u2026`.\n if (text[opEnd] === '=' || (opLen === 1 && /[!<>+\\-*/%&|^=]/.test(before))) continue;\n\n // Walk back over the identifier the keyword ends: `AWS_SECRET_ACCESS_KEY`.\n const keywordEnd = m.index + m[0].replace(/[\"']?[ \\t]*(?::=|=>|[:=])$/, '').length;\n let nameStart = m.index;\n while (nameStart > 0 && NAME_CHAR_RE.test(text[nameStart - 1] ?? '')) nameStart--;\n const name = text.slice(nameStart, keywordEnd);\n if (!nameLooksLikeSecret(name)) continue;\n\n GENERIC_VALUE.lastIndex = opEnd;\n const v = GENERIC_VALUE.exec(text);\n if (!v) continue;\n const value = v[1] ?? v[2] ?? v[3] ?? v[4];\n if (value === undefined || !valueLooksLikeSecret(value)) continue;\n const start = v.index + v[0].lastIndexOf(value);\n out.push({ start, end: start + value.length, value });\n anchor.lastIndex = start + value.length;\n }\n return out;\n },\n};\n\n/** Explicit socket-auth command arguments are credential context, not hashes. */\nconst socketAuthRule:Rule={\n id:'socket-auth-argument',type:'generic',source:'03 \u00A75 credential context',\n scan(text:string):RuleMatch[]{const out:RuleMatch[]=[];const anchor=/(?:^|[\\s\"'`])--socket-auth[\"']?(?:[ \\t]*=[ \\t]*|[ \\t]+)/gi;let match:RegExpExecArray|null;\n while((match=anchor.exec(text))!==null){GENERIC_VALUE.lastIndex=anchor.lastIndex;const found=GENERIC_VALUE.exec(text);if(!found)continue;const value=found[1]??found[2]??found[3]??found[4];if(value===undefined||!valueLooksLikeSecret(value))continue;const start=found.index+found[0].lastIndexOf(value);out.push({start,end:start+value.length,value});anchor.lastIndex=start+value.length;}\n return out;}\n};\n\n/**\n * `Authorization: Bearer <token>` \u2014 a credential *context* rather than a\n * credential *shape*.\n *\n * The rule exists to make the entropy exclusions above safe to hold. They all\n * assume that a value in a position that shouts \"credential\" is claimed by an\n * earlier rule; `KEY=`, `?token=` and `https://user:pw@` were already covered,\n * and the http authorization header was the hole. It matters more now than it\n * did before T1.4b: a `Bearer toolu_\u2026`-shaped token is excluded by E1 as a\n * bare token, and must not be excluded here.\n *\n * The name is not masked, only the credential, so a redacted transcript still\n * says which scheme was used.\n */\nconst BEARER_RE =\n /(?:^|[^A-Za-z0-9_-])(?:Bearer|Token|ApiKey|Api-Key|Basic|DPoP)[ \\t]+([A-Za-z0-9+/._~-]{16,512}={0,2})/g;\n\nconst bearerRule: Rule = regexRule(\n 'authorization-bearer',\n 'generic',\n '03 \u00A75 (credential context), given the shape of gitleaks generic-api-key (MIT)',\n BEARER_RE,\n {\n group: 1,\n // Same value screen as the `KEY=` rule: `Bearer ${token}`, `Bearer <TOKEN>`\n // and `Bearer your-token-here` are documentation, not credentials.\n validate: (value) => valueLooksLikeSecret(value),\n },\n);\n\n/**\n * The entropy rule from `03` \u00A75 \u2014 \u2265 4.5 bits over tokens of \u2265 20 characters \u2014\n * written as a scanner rather than as one regex.\n *\n * `03` fixes the threshold and the length floor and both are honoured\n * unchanged. What T1.4b changed is **what counts as a token**, because that\n * was never specified and the naive reading was doing the damage:\n *\n * 1. `=` is base64 *padding*, so it is only a token character at the end.\n * Before, `ANTHROPIC_VERTEX_PROJECT_ID=example-project` was one\n * \"token\" \u2014 a variable glued to its value \u2014 and scored 4.7.\n * 2. `/` and `.` remain separators, so a long path or a dotted hostname is\n * not one token. (Unchanged from T1.4; the reasoning is that a real\n * base64 secret containing `/` still leaves a \u2265 23-character run, and 23\n * is the shortest string that can reach 4.5 bits at all.)\n * 3. Transcripts are json-inside-json, so the text often carries a *literal*\n * backslash-n where a newline belongs. `\\ntvly-dev-\u2026` used to yield the\n * token `ntvly-dev-\u2026` \u2014 the same secret with a different first character,\n * and therefore a different sha8 and a different mask. Escape residue is\n * trimmed, which is a correctness fix for the \"same secret, same mask\"\n * guarantee and not only a cosmetic one.\n * 4. Percent-escape residue (`%2F` leaving `2F\u2026`) and leading/trailing\n * separators are trimmed for the same reason.\n *\n * Shape exclusions live in {@link entropyCandidateAllowed}.\n */\nconst ENTROPY_TOKEN = /[A-Za-z0-9+_-]{20,}={0,2}/g;\n\n/** Characters a `\\x` json escape leaves glued to the front of a token. */\nconst ESCAPE_LETTERS = 'ntrbfv';\n\nconst highEntropyRule: Rule = {\n id: 'high-entropy-token',\n type: 'entropy',\n source: '03 \u00A75 (4.5 bits / 20 chars) + gitleaks entropy allowlists (MIT)',\n scan(text: string): RuleMatch[] {\n const out: RuleMatch[] = [];\n const rx = new RegExp(ENTROPY_TOKEN.source, ENTROPY_TOKEN.flags);\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n let start = m.index;\n let value = m[0];\n // `\\n`, `\\t`, `\\r` written literally by an outer json encoder.\n if (start > 0 && text[start - 1] === '\\\\' && ESCAPE_LETTERS.includes(value[0] ?? '')) {\n start += 1;\n value = value.slice(1);\n }\n // `%2F`, `%3D` \u2014 the `%` is a separator, but the two hex digits that\n // complete the escape are not part of the token that follows it.\n if (start > 0 && text[start - 1] === '%' && /^[0-9A-Fa-f]{2}/.test(value)) {\n start += 2;\n value = value.slice(2);\n }\n // Leading and trailing separators belong to the surrounding text.\n const lead = value.length - value.replace(/^[-_+]+/, '').length;\n start += lead;\n value = value.slice(lead).replace(/[-_+]+$/, '');\n\n if (value.length < ENTROPY_MIN_LENGTH) continue;\n if (!entropyCandidateAllowed(value)) continue;\n if (shannonEntropy(value) < ENTROPY_THRESHOLD) continue;\n out.push({ start, end: start + value.length, value });\n }\n return out;\n },\n};\n\nexport const RULES: Rule[] = [\n // ---- key material ------------------------------------------------------\n regexRule(\n // gitleaks `private-key`; secretlint `@secretlint/secretlint-rule-privatekey`.\n // The whole block is masked, header to footer: the base64 body alone would\n // otherwise be shredded into a dozen separate entropy hits.\n 'private-key-block',\n 'private-key',\n 'gitleaks private-key / secretlint-rule-privatekey (MIT)',\n /-----BEGIN[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----[\\s\\S]{0,200000}?-----END[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----/g,\n ),\n regexRule(\n // gitleaks `private-key`, unterminated variant: a transcript often quotes\n // the header and the first body lines and then elides the rest.\n //\n // The body is taken line by line and only where a line is \u2265 20 characters\n // of pure base64, so an unterminated header followed by prose masks the\n // header alone instead of swallowing the sentence after it. The separator\n // class carries the backslash so json-escaped `\\n` works, and it is\n // disjoint from the base64 class, which is what keeps this linear.\n 'private-key-header',\n 'private-key',\n 'gitleaks private-key (MIT)',\n /-----BEGIN[ A-Z0-9]{0,40}PRIVATE KEY(?: BLOCK)?-----(?:[\\r\\n \\t\\\\]+[A-Za-z0-9+/=]{20,})*/g,\n ),\n regexRule(\n // gitleaks `jwt`: three base64url segments, the first two starting `ey`\n // (the base64 of `{\"`). Session transcripts are full of these.\n 'jwt',\n 'jwt',\n 'gitleaks jwt (MIT)',\n /\\bey[A-Za-z0-9_-]{17,}\\.ey[A-Za-z0-9_-]{17,}\\.[A-Za-z0-9_-]{10,}={0,2}/g,\n ),\n\n // ---- vendor tokens -----------------------------------------------------\n regexRule(\n // gitleaks `aws-access-token`; secretlint-rule-aws `AWSAccessKeyID`.\n 'aws-access-key-id',\n 'aws',\n 'gitleaks aws-access-token / secretlint-rule-aws (MIT)',\n /\\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\\b/g,\n ),\n regexRule(\n // secretlint-rule-aws `AWSSecretAccessKey`: a 40-character base64 value\n // bound to an AWS-flavoured name. Typed `aws` and placed before the generic\n // rule so `doctor` reports it as what it is.\n 'aws-secret-access-key',\n 'aws',\n 'secretlint-rule-aws AWSSecretAccessKey (MIT)',\n /aws[_.-]?(?:secret|access)[_.-]?(?:access[_.-]?)?key(?:[_.-]?id)?[\"'\\s]{0,4}[:=][\"'\\s]{0,4}([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])/gi,\n { group: 1 },\n ),\n regexRule(\n // gitleaks `gcp-api-key`; secretlint-rule-gcp `GCPApiKey`.\n 'gcp-api-key',\n 'gcp',\n 'gitleaks gcp-api-key / secretlint-rule-gcp (MIT)',\n /\\bAIza[0-9A-Za-z_-]{35}\\b/g,\n ),\n regexRule(\n // gitleaks `gcp-oauth-client-secret`.\n 'gcp-oauth-client-secret',\n 'gcp',\n 'gitleaks gcp-oauth-client-secret (MIT)',\n /\\bGOCSPX-[a-zA-Z0-9_-]{28}\\b/g,\n ),\n regexRule(\n // gitleaks `github-pat` / `-oauth` / `-app-token` / `-refresh-token`;\n // secretlint-rule-github. ghp_ user, gho_ oauth, ghu_/ghs_ app, ghr_ refresh.\n 'github-token',\n 'github',\n 'gitleaks github-pat / secretlint-rule-github (MIT)',\n /\\bgh[pousr]_[A-Za-z0-9]{36,255}\\b/g,\n ),\n regexRule(\n // gitleaks `github-fine-grained-pat`.\n 'github-fine-grained-pat',\n 'github',\n 'gitleaks github-fine-grained-pat (MIT)',\n /\\bgithub_pat_[0-9a-zA-Z_]{82}\\b/g,\n ),\n regexRule(\n // gitleaks `slack-bot-token` / `-user-token` / `-app-token`;\n // secretlint-rule-slack.\n 'slack-token',\n 'slack',\n 'gitleaks slack-bot-token / secretlint-rule-slack (MIT)',\n /\\bxox[abprs]-[0-9a-zA-Z-]{10,72}\\b/g,\n ),\n regexRule(\n // gitleaks `slack-webhook-url`; secretlint-rule-slack `SlackWebhook`.\n 'slack-webhook',\n 'slack',\n 'gitleaks slack-webhook-url (MIT)',\n /https:\\/\\/hooks\\.slack\\.com\\/(?:services|workflows|triggers)\\/[A-Za-z0-9+/]{6,}\\/[A-Za-z0-9+/]{6,}\\/[A-Za-z0-9+/]{6,}/g,\n ),\n regexRule(\n // gitleaks `stripe-access-token`. `pk_` publishable keys are public by\n // design and are deliberately not matched.\n 'stripe-key',\n 'stripe',\n 'gitleaks stripe-access-token (MIT)',\n /\\b(?:sk|rk)_(?:test|live|prod)_[A-Za-z0-9]{10,99}\\b/g,\n ),\n regexRule(\n // gitleaks `anthropic-api-key`. Must precede the openai rules: both start\n // `sk-`, and whichever rule claims the span first wins.\n 'anthropic-api-key',\n 'anthropic',\n 'gitleaks anthropic-api-key (MIT)',\n /\\bsk-ant-(?:api|admin)[0-9]{2}-[A-Za-z0-9_-]{80,120}\\b/g,\n ),\n regexRule(\n // gitleaks `openai-api-key`: the `T3BlbkFJ` infix is the base64 of\n // \"OpenAI\" and is what makes this rule safe to run over prose.\n 'openai-api-key-project',\n 'openai',\n 'gitleaks openai-api-key (MIT)',\n /\\bsk-(?:proj-|svcacct-|admin-)?[A-Za-z0-9_-]{20,}T3BlbkFJ[A-Za-z0-9_-]{20,}\\b/g,\n ),\n regexRule(\n // gitleaks `openai-api-key`, legacy 48-character form with no infix.\n 'openai-api-key-legacy',\n 'openai',\n 'gitleaks openai-api-key (MIT)',\n /\\bsk-[A-Za-z0-9]{48}\\b/g,\n ),\n regexRule(\n // gitleaks `npm-access-token`; secretlint-rule-npm.\n 'npm-access-token',\n 'npm',\n 'gitleaks npm-access-token / secretlint-rule-npm (MIT)',\n /\\bnpm_[A-Za-z0-9]{36}\\b/g,\n ),\n\n // ---- credentials in urls -----------------------------------------------\n regexRule(\n // gitleaks `authenticated-url`; secretlint `-rule-basicauth`. Only the\n // password is masked: `postgres://app:\u2039redacted:basic-auth:\u2026\u203A@db:5432/x`\n // still says which host and which user, which is the point of an index that\n // stays searchable by shape.\n 'basic-auth-url',\n 'basic-auth',\n 'gitleaks authenticated-url / secretlint-rule-basicauth (MIT)',\n // The user half is `{0,64}`: `redis://:hunter2@host` has an empty user and\n // is exactly as leaked as the two-part form.\n /\\b[a-zA-Z][a-zA-Z0-9+.-]{1,20}:\\/\\/[^\\s:@/]{0,64}:([^\\s:@/]{1,128})@/g,\n {\n group: 1,\n validate: (value) => {\n if (INTERPOLATION_RE.test(value)) return false;\n if (PLACEHOLDER_RE.test(value)) return false;\n if (MASK_FRAGMENT_RE.test(value)) return false;\n if (/^(?:pass|pw|user|admin|root|test|guest|\\*+|x+|\\d{1,4})$/i.test(value)) return false;\n return true;\n },\n },\n ),\n\n // ---- credential context (03 \u00A75) ----------------------------------------\n bearerRule,\n genericAssignmentRule,\n socketAuthRule,\n\n // ---- entropy (03 \u00A75) ---------------------------------------------------\n // Last, so that anything a named rule understands is reported under its real\n // type and a bare token is the fallback rather than the default.\n highEntropyRule,\n];\n", "/**\n * Binary elision \u2014 the pass that runs **before** the redactor.\n *\n * ## Why this exists\n *\n * T1.4 landed the redactor and `potsherd index --full` promptly reported\n * *165,088 secrets masked* over 1,406 exchanges. Measuring where they were\n * (`scripts/redaction-benchmark.mjs`) settled it: 98.6% were in `tool_calls`,\n * and the single worst tool call was a **589 KB base64 JPEG** pasted into a\n * `Read` result, which alone produced 5,660 entropy hits.\n *\n * That is not a miscalibrated entropy rule. It is a picture. No secret scanner\n * ever written can look at 589 KB of base64 and tell you which 40 characters\n * of it are a credential, because none of them are \u2014 it is a JPEG. The fix is\n * not to make the detector blinder; it is to stop feeding it images.\n *\n * The codex adapter already established the convention for exactly this\n * problem (`adapters/codex.ts`, \"Trap 3\"): a binary payload becomes a short\n * marker, `\u2039elided:image/png:109362 bytes\u203A`. Its regex only recognises\n * `data:\u2026;base64,\u2026` URIs, which is the shape codex writes. Claude Code writes\n * the Anthropic content-block shape instead \u2014\n *\n * [{\"type\":\"image\",\"source\":{\"type\":\"base64\",\"data\":\"/9j/4AAQ\u2026\",\"media_type\":\"image/jpeg\"}}]\n *\n * \u2014 which that regex never sees. This module generalises the convention to\n * both shapes, plus to a bare base64 run that announces itself with a file\n * magic, and is called from `ingest.ts` on the way into the store, before\n * `redactExchange`.\n *\n * ## Why it is safe to run before redaction\n *\n * Every shape elided here is identified by something a *credential never has*:\n * a `data:` URI scheme, an image content-block wrapper, or the base64 of a\n * file-format magic number. A 40-character AWS secret is not a JPEG header,\n * and the {@link MIN_PAYLOAD} floor of 512 base64 characters is far above any\n * credential that has ever been issued. PEM private-key bodies are longer than\n * that but begin `MII\u2026` / `b3Blb\u2026` and carry a `-----BEGIN` header, so they\n * match no magic here and reach the redactor intact \u2014 `tests/redact.test.ts`\n * holds that case.\n *\n * The marker uses the same guillemets as the mask (`\u2039` U+2039, `\u203A` U+203A) and\n * for the same reason: those characters cannot occur in base64, in a shell\n * token or in a json key, so an elision can never be confused for content and\n * a second pass recognises its own output.\n *\n * Elision is **not** redaction and does not pretend to be. It removes bulk\n * that carries no meaning for retrieval; the redactor still runs afterwards\n * over everything that survives, and there is still no `--no-redact` flag.\n */\n\nimport type { Exchange, ExchangeToolCall } from './adapters/types.js';\n\n/** What one pass threw away, so a caller can say it out loud. */\nexport interface Elisions {\n /** Binary payloads replaced by a marker. */\n binaryParts: number;\n /** Characters dropped. */\n charsElided: number;\n}\n\nexport function emptyElisions(): Elisions {\n return { binaryParts: 0, charsElided: 0 };\n}\n\nexport function addElisions(a: Elisions, b: Elisions): Elisions {\n return {\n binaryParts: a.binaryParts + b.binaryParts,\n charsElided: a.charsElided + b.charsElided,\n };\n}\n\n/**\n * The shortest base64 run this module will elide, in characters. 512 base64\n * characters is 384 bytes.\n *\n * Chosen to sit far above every credential shape in `redact-rules.ts` \u2014 the\n * longest is an anthropic key at ~120 characters \u2014 so raising this floor can\n * never be the reason a secret is missed. A \"binary payload\" smaller than this\n * is not worth a marker anyway.\n */\nexport const MIN_PAYLOAD = 512;\n\n/** Matches this module's own marker, so a second pass is a no-op. */\nexport const ELISION_RE = /\u2039elided:[^\u203A]{1,120}\u203A/g;\n\n/**\n * base64 of the first bytes of a file format, longest prefix first.\n *\n * A base64 payload that starts with one of these *is* that file: base64 is a\n * fixed 3-bytes-to-4-characters encoding with no header of its own, so the\n * leading characters are a faithful transcription of the leading bytes, which\n * for every format below is a magic number the format spec mandates.\n *\n * Only formats that actually turn up pasted into an agent transcript are here.\n * Adding one is cheap; guessing one is not, so each names the bytes it encodes.\n */\nconst BASE64_MAGIC: Array<[prefix: string, mime: string, bytes: string]> = [\n ['iVBORw0KGgo', 'image/png', '89 50 4E 47 0D 0A 1A 0A'],\n ['/9j/', 'image/jpeg', 'FF D8 FF (JFIF/Exif SOI)'],\n ['R0lGODdh', 'image/gif', 'GIF87a'],\n ['R0lGODlh', 'image/gif', 'GIF89a'],\n ['Qk0', 'image/bmp', '42 4D (\"BM\")'],\n ['SUkqAA', 'image/tiff', '49 49 2A 00 (little-endian TIFF)'],\n ['TU0AK', 'image/tiff', '4D 4D 00 2A (big-endian TIFF)'],\n ['AAABAA', 'image/x-icon', '00 00 01 00 (ICO)'],\n ['UklGR', 'application/octet-stream', '52 49 46 46 (\"RIFF\" \u2014 webp/wav/avi)'],\n ['JVBERi0', 'application/pdf', '25 50 44 46 2D (\"%PDF-\")'],\n ['UEsDB', 'application/zip', '50 4B 03 04 (\"PK\\\\x03\\\\x04\" \u2014 zip/docx/xlsx)'],\n ['H4sI', 'application/gzip', '1F 8B 08'],\n ['SUQz', 'audio/mpeg', '49 44 33 (\"ID3\")'],\n ['T2dnU', 'application/ogg', '4F 67 67 53 (\"OggS\")'],\n ['d09GRg', 'font/woff', '77 4F 46 46 (\"wOFF\")'],\n ['d09GMg', 'font/woff2', '77 4F 46 32 (\"wOF2\")'],\n ['AAEAAA', 'font/ttf', '00 01 00 00 (TrueType)'],\n ['T1RUTw', 'font/otf', '4F 54 54 4F (\"OTTO\")'],\n];\n\n/** A payload character: base64, plus the `\\/` a json encoder writes for `/`. */\nconst B64_RUN = `(?:[A-Za-z0-9+/=]|\\\\\\\\/)`;\n\n/**\n * A payload, possibly hard-wrapped.\n *\n * Whitespace is tolerated *only between two long chunks*. Allowing it as a\n * plain payload character is the obvious way to write this and it is wrong:\n * `<900 characters of png>\\ndone` is then a single run, and the elision eats\n * the word after the payload. Requiring a continuation to be \u2265 40 characters\n * means prose on the next line ends the run instead of joining it.\n */\nconst B64_BODY = `${B64_RUN}{40,}(?:[\\\\r\\\\n \\\\t]+${B64_RUN}{40,})*`;\n\n/**\n * `data:image/png;base64,\u2026` \u2014 the shape the codex adapter already elides,\n * kept identical here so the two passes agree and the second is a no-op.\n */\nconst DATA_URI = new RegExp(\n `data:([a-zA-Z0-9.+-]+/[a-zA-Z0-9.+-]+)?(?:;[a-zA-Z0-9.+=-]+)*;base64,${B64_BODY}`,\n 'g',\n);\n\n/**\n * The Anthropic / OpenAI image **content block**, as the parser stringifies it\n * into `tool_calls.result`:\n *\n * {\"type\":\"image\",\"source\":{\"type\":\"base64\",\"data\":\"/9j/4AAQ\u2026\",\"media_type\":\"image/jpeg\"}}\n *\n * `media_type` may sit either side of `data` (both orders occur in the real\n * corpus), so the mime is recovered by a second look rather than by trying to\n * write one regex that matches both. The payload key is the union of the keys\n * the shapes in the wild use: `data` (anthropic), `image_data`, `b64_json`\n * (openai images), `base64`.\n *\n * The `\"base64\"` / `media_type` context is *required*: without it this would\n * be \"elide any long string called data\", which would swallow a base64\n * credential posted in a json body. That case is a planted fixture.\n */\nconst CONTENT_BLOCK = new RegExp(\n `\"(?:data|image_data|b64_json|base64)\"\\\\s*:\\\\s*\"(${B64_BODY})\"`,\n 'g',\n);\n\n/** `\"media_type\":\"image/jpeg\"`, `\"mimeType\": \"image/png\"`, `\"type\":\"base64\"`. */\nconst MEDIA_HINT = /\"(?:media_?type|mime_?type|mimeType)\"\\s*:\\s*\"([a-zA-Z0-9.+-]+\\/[a-zA-Z0-9.+-]+)\"|\"type\"\\s*:\\s*\"base64\"/gi;\n\n/** How far either side of a payload a media hint still counts as its own. */\nconst HINT_WINDOW = 200;\n\n/**\n * A bare base64 run that announces itself with a file magic \u2014 a payload pasted\n * without any wrapper at all, which is what `cat image.png | base64` in a Bash\n * tool result looks like.\n *\n * Anchored on the magic prefixes rather than on \"any base64 character\", which\n * is not a nicety: a `{512,}` quantifier over an unanchored character class\n * is retried at every letter of the corpus, and the corpus is 78 MB. With the\n * literal prefixes up front the engine skips to the next possible start.\n */\nconst MAGIC_PREFIXES = BASE64_MAGIC.map(([p]) => p.replace(/[.*+?^${}()|[\\]\\\\/]/g, '\\\\$&')).join('|');\nconst BARE_RUN = new RegExp(\n `(?<![A-Za-z0-9+/=])(?:${MAGIC_PREFIXES})${B64_BODY}`,\n 'g',\n);\n\ninterface Span {\n start: number;\n end: number;\n mime: string;\n}\n\n/** Strip json escapes and whitespace to get at the payload's real leading bytes. */\nfunction magicOf(payload: string): string | undefined {\n const head = payload.slice(0, 32).replace(/\\\\\\//g, '/').replace(/\\s+/g, '');\n for (const [prefix, mime] of BASE64_MAGIC) if (head.startsWith(prefix)) return mime;\n return undefined;\n}\n\n/** The mime named nearest to `[start,end)`, if the window holds a hint. */\nfunction mimeNear(text: string, start: number, end: number): string | undefined {\n const from = Math.max(0, start - HINT_WINDOW);\n const window = text.slice(from, start) + text.slice(end, Math.min(text.length, end + HINT_WINDOW));\n const rx = new RegExp(MEDIA_HINT.source, MEDIA_HINT.flags);\n let m: RegExpExecArray | null;\n let sawBase64 = false;\n while ((m = rx.exec(window)) !== null) {\n if (m[1]) return m[1];\n sawBase64 = true;\n }\n return sawBase64 ? 'application/octet-stream' : undefined;\n}\n\nfunction collect(re: RegExp, text: string, group: number, decide: (payload: string, start: number, end: number) => string | undefined, out: Span[]): void {\n const rx = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n while ((m = rx.exec(text)) !== null) {\n const payload = group === 0 ? m[0] : m[group];\n if (payload === undefined || payload.length === 0) { rx.lastIndex += 1; continue; }\n const start = m.index + (group === 0 ? 0 : m[0].indexOf(payload));\n const end = start + payload.length;\n const mime = decide(payload, start, end);\n if (mime === undefined) continue;\n out.push({ start, end, mime });\n }\n}\n\n/**\n * Replace every binary payload in `text` with `\u2039elided:<mime>:<n> bytes\u203A`.\n *\n * Idempotent: the marker contains no base64 run of its own, so a second call\n * finds nothing and returns the same string.\n */\nexport function elideBinary(text: string, tally: Elisions = emptyElisions()): string {\n if (typeof text !== 'string' || text.length < MIN_PAYLOAD) return text ?? '';\n // Cheap reject. Every shape below needs a long unbroken base64 run, and\n // that needs at least this much alphabet. Skipping here is what keeps the\n // pass off the 99% of transcript text that is prose and code.\n if (!/[A-Za-z0-9+/]{64}/.test(text)) return text;\n\n const spans: Span[] = [];\n // The regexes only require 40 payload characters so that a hard-wrapped\n // payload still matches as one run; the MIN_PAYLOAD floor is applied here,\n // to the whole run.\n const big = (payload: string) => payload.length >= MIN_PAYLOAD;\n // 1. data: URIs \u2014 mime is in the URI itself.\n collect(DATA_URI, text, 0, (payload) => {\n if (!big(payload)) return undefined;\n const m = /^data:([a-zA-Z0-9.+-]+\\/[a-zA-Z0-9.+-]+)?/.exec(payload);\n return m?.[1] ?? 'application/octet-stream';\n }, spans);\n // 2. image content blocks \u2014 the wrapper must say `base64` or name a mime,\n // otherwise a long value that merely happens to be called `data` is left\n // for the redactor to judge.\n collect(CONTENT_BLOCK, text, 1, (payload, start, end) => {\n if (!big(payload)) return undefined;\n const hint = mimeNear(text, start, end);\n if (hint === undefined) return undefined;\n return magicOf(payload) ?? hint;\n }, spans);\n // 3. bare runs that carry a file magic.\n collect(BARE_RUN, text, 0, (payload) => (big(payload) ? magicOf(payload) : undefined), spans);\n\n if (spans.length === 0) return text;\n\n // First span wins on overlap: a data: URI inside a content block is elided\n // once, as the URI, not twice.\n spans.sort((a, b) => a.start - b.start || b.end - a.end);\n const out: string[] = [];\n let cursor = 0;\n for (const s of spans) {\n if (s.start < cursor) continue;\n out.push(text.slice(cursor, s.start));\n const n = s.end - s.start;\n out.push(`\u2039elided:${s.mime}:${n} bytes\u203A`);\n tally.binaryParts += 1;\n tally.charsElided += n;\n cursor = s.end;\n }\n out.push(text.slice(cursor));\n return out.join('');\n}\n\n/**\n * {@link elideBinary} over every field of an exchange that `03` \u00A75 redacts.\n * Returns a new object; the input is never mutated, because the caller may\n * still be writing the byte-exact archive copy from it.\n */\nexport function elideExchange(ex: Exchange): { exchange: Exchange; elisions: Elisions } {\n const elisions = emptyElisions();\n const one = (s: string): string => elideBinary(s, elisions);\n\n const userText = one(ex.userText);\n const assistantText = one(ex.assistantText);\n const toolCalls: ExchangeToolCall[] = ex.toolCalls.map((tc) => {\n const next: ExchangeToolCall = { ...tc, input: one(tc.input) };\n if (tc.result !== undefined) next.result = one(tc.result);\n return next;\n });\n\n if (elisions.binaryParts === 0) return { exchange: ex, elisions };\n return { exchange: { ...ex, userText, assistantText, toolCalls }, elisions };\n}\n", "import fs from 'node:fs';\nimport {createHash} from 'node:crypto';\nimport {redact} from '../redact.js';\nimport {elideBinary} from '../redact-elide.js';\n\nexport const digest=(value:string|Buffer):string=>createHash('sha256').update(value).digest('hex');\nexport const clean=(text:string):string=>redact(elideBinary(text)).text;\nexport const clock=(value:unknown):string|null=>typeof value==='string'&&Number.isFinite(Date.parse(value))?new Date(value).toISOString():null;\nexport interface NativeEvent {observed?:boolean;languageEligible?:boolean;key:string;rawStart:number;rawEnd:number;role:'user';text:string;eventAt:string|null;project:string|null;origin:'claude_prompt_id'|'codex_human_marker'|'pi_user_projection'|'opencode_user_projection'|'unknown';eligible:boolean;excluded:string|null;identity:string;evidenceStart?:number;nativeRecordId?:string;recordCommitment?:string;declaredOrigin?:string;}\nexport interface NativeFacts {nativeId:string;project:string|null;parent:string|null;child:boolean;title:string|null;events:NativeEvent[];gaps:string[];hash:string;consumed:number;bytes:Buffer;}\n\n/** A size check and a bounded fd read, with identity rechecked after reading. */\nexport function boundedBytes(file:string,max:number):Buffer {\n const fd=fs.openSync(file,'r');\n try{const before=fs.fstatSync(fd);if(!before.isFile()||before.size>max)throw new Error('source_bytes_limit');\n const bytes=Buffer.alloc(before.size);let offset=0;\n while(offset<bytes.length){const n=fs.readSync(fd,bytes,offset,bytes.length-offset,offset);if(!n)throw new Error('source_changed');offset+=n;}\n const after=fs.fstatSync(fd);if(before.size!==after.size||before.mtimeMs!==after.mtimeMs||before.ctimeMs!==after.ctimeMs||before.dev!==after.dev||before.ino!==after.ino)throw new Error('source_changed');\n return bytes;\n }finally{fs.closeSync(fd);}\n}\n", "import type {AuditProfanity,AuditPrompt,AuditProseKind,AuditWordTerm} from './contracts.js';\n\n/** Exact v1 lexicon: fuck,fucked,fucking,shit,shitty,bullshit,asshole,bastard.\n * Literal English matches only; no language detection, mood or intent inference.\n */\nexport const ENGLISH_EXPLICIT_LEXICON=Object.freeze(['fuck','fucked','fucking','shit','shitty','bullshit','asshole','bastard'] as const);\nexport const PROFANITY_LEXICON_VERSION='en-explicit-8-v1';\nconst words=new Set<string>(ENGLISH_EXPLICIT_LEXICON);\n/** Cheap pre-check: every lexicon word contains one of these stems. */\nexport const LEXICON_HINT=/fuck|shit|asshole|bastard/i;\nconst CODE=2,QUOTE=1,UNKNOWN=3;\nconst kind=(label:number):AuditProseKind=>label===CODE?'code':label===QUOTE?'quoted':label===UNKNOWN?'unknown':'direct_prose';\nconst escaped=(text:string,index:number)=>{let count=0;for(let i=index-1;i>=0&&text[i]==='\\\\';i--)count++;return count%2===1;};\nconst wordChar=(char:string|undefined)=>char!==undefined&&/[\\p{L}\\p{N}\\p{M}_\\u200c\\u200d]/u.test(char);\n\nconst labelMemo=new Map<string,{labels:Uint8Array;ambiguous:boolean}>();\n/** Memoized: the same prompt text is labelled by several language passes. */\nfunction labels(text:string):{labels:Uint8Array;ambiguous:boolean}{\n let hit=labelMemo.get(text);if(hit)return hit;\n if(labelMemo.size>20000)labelMemo.clear();\n hit=computeLabels(text);labelMemo.set(text,hit);return hit;\n}\n/** Conservative textual spans, not a claim to parse every language or Markdown dialect. */\nfunction computeLabels(text:string):{labels:Uint8Array;ambiguous:boolean}{\n const map=new Uint8Array(text.length);let ambiguous=false,offset=0,fence:{char:string;length:number;start:number}|null=null;\n for(const line of text.split(/(?<=\\n)/u)){\n const marker=line.match(/^ {0,3}(`{3,}|~{3,})/u);\n if(fence){if(marker&&marker[1]![0]===fence.char&&marker[1]!.length>=fence.length&&line.slice(marker[0].length).trim()===''){map.fill(CODE,fence.start,offset+line.length);fence=null;}}\n else if(marker)fence={char:marker[1]![0]!,length:marker[1]!.length,start:offset};\n else if(/^ {0,3}>/u.test(line))map.fill(QUOTE,offset,offset+line.length);\n else if(/^(?: {4}|\\t)\\S/u.test(line)){map.fill(UNKNOWN,offset,offset+line.length);ambiguous=true;}\n offset+=line.length;\n }\n if(fence){map.fill(UNKNOWN,fence.start);ambiguous=true;}\n // Explicit imported-source structure is quoted material, not the user's own reaction.\n const sourceRows=text.split(/(?<=\\n)/u),timestamp=/^\\s*(?:(?:[-*#]+|\\*\\*)\\s*)?\\[?\\d{1,2}:\\d{2}(?::\\d{2})?(?:\\.\\d+)?\\]?/u;\n if(/(?:transcript|captions|youtube|youtu\\.be|video transcription)/iu.test(text)&&sourceRows.filter(line=>timestamp.test(line)).length>=3){let at=0;for(const line of sourceRows){if(timestamp.test(line))map.fill(QUOTE,at,at+line.length);at+=line.length;}}\n\n for(let i=0;i<text.length;i++){\n if(map[i]||escaped(text,i))continue;const char=text[i]!;\n if(char==='`'){\n let count=1;while(text[i+count]==='`')count++;const token='`'.repeat(count);let end=text.indexOf(token,i+count);\n while(end>=0&&(map[end]!==0||text[end-1]==='`'||text[end+count]==='`'))end=text.indexOf(token,end+count);\n if(end<0){map.fill(UNKNOWN,i);ambiguous=true;break;}map.fill(CODE,i,end+count);i=end+count-1;continue;\n }\n if(!['\"',\"'\",'\u201C','\u2018'].includes(char))continue;\n if((char===\"'\"||char==='\u2018')&&wordChar(text[i-1])&&wordChar(text[i+1]))continue;\n const closing=char==='\u201C'?'\u201D':char==='\u2018'?'\u2019':char;let end=i+1;\n while(end<text.length){if(text[end]===closing&&!escaped(text,end)&&map[end]===0&&!((closing===\"'\"||closing==='\u2019')&&wordChar(text[end-1])&&wordChar(text[end+1])))break;end++;}\n if(end>=text.length){map.fill(UNKNOWN,i);ambiguous=true;break;}map.fill(QUOTE,i,end+1);i=end;\n }\n return {labels:map,ambiguous};\n}\nexport function proseLabels(text:string):Uint8Array{return labels(text).labels;}\n/** One lexicon occurrence: [token as written, label (0 prose, 1 quoted, 2 code, 3 unknown), start, end] in UTF-16 of the prompt. */\nexport type ProfanityHit=[token:string,label:number,start:number,end:number];\nconst TOKEN=/[\\p{L}\\p{N}\\p{M}_\\u200c\\u200d]+(?:['\u2019][\\p{L}\\p{N}\\p{M}_\\u200c\\u200d]+)*/gu;\n/** Per-prompt lexicon hits; computed once (in the scan worker) so the text need not be kept. */\nexport function profanityHits(text:string):{hits:ProfanityHit[];ambiguous:boolean}|null{\n if(!LEXICON_HINT.test(text))return null;const spans=labels(text),hits:ProfanityHit[]=[];TOKEN.lastIndex=0;let token:RegExpExecArray|null;\n while((token=TOKEN.exec(text))!==null){if(!words.has(token[0].toLowerCase()))continue;hits.push([token[0],spans.labels[token.index]??0,token.index,token.index+token[0].length]);}\n return {hits,ambiguous:spans.ambiguous};\n}\nconst knownExcluded=new Set(['child_initialization','maintenance_exclusion_marker','tool_result','inherited_native_event','declared_meta_or_synthetic_input','declared_synthetic_input']);\nexport const languageEligibleInput=(p:AuditPrompt)=>p.languageEligible!==false&&(p.eligibleNativeInput===true&&!knownExcluded.has(p.excludedReason??'')||p.eligibleNativeInput===undefined&&p.eligibleHuman&&p.excludedReason===null&&['claude_prompt_id','codex_human_marker'].includes(p.originBasis));\n/** Hits of one prompt: precomputed lexical data when present, else from its text. */\nexport function hitsOf(p:AuditPrompt):{hits:ProfanityHit[];ambiguous:boolean}|null{\n if(p.lex)return p.lex.pt?{hits:p.lex.pt as ProfanityHit[],ambiguous:!!p.lex.pa}:null;\n return profanityHits(p.text);\n}\n/** Counts already-redacted, immutable eligible inputs; support ranges are redacted-prompt UTF-16. */\nexport function auditProfanity(prompts:readonly AuditPrompt[],partial=false):AuditProfanity{\n const eligible=prompts.filter(languageEligibleInput),bucketCounts=new Map<AuditProseKind,{occurrences:number;prompts:Set<string>}>((['direct_prose','quoted','code','unknown'] as const).map(k=>[k,{occurrences:0,prompts:new Set<string>()}])),containing=new Set<string>(),matches:NonNullable<AuditProfanity['matches']>[number][]=[];const terms=new Map<string,{term:string;kind:AuditProseKind;occurrences:number;ids:Set<string>;samples:AuditWordTerm['samples'][number][]}>();let occurrences=0,ambiguous=false;\n for(const prompt of eligible){const found=hitsOf(prompt);if(!found)continue;ambiguous||=found.ambiguous;\n for(const [raw,label,start,end] of found.hits){const bucket=kind(label),counter=bucketCounts.get(bucket)!;occurrences++;containing.add(prompt.id);counter.occurrences++;counter.prompts.add(prompt.id);\n const normalized=raw.toLowerCase(),key=normalized+'\\0'+bucket;const term=terms.get(key)??{term:normalized,kind:bucket,occurrences:0,ids:new Set<string>(),samples:[]};term.occurrences++;term.ids.add(prompt.id);if(term.samples.length<3)term.samples.push({promptId:prompt.id,conversationId:prompt.conversationId,startUtf16:start,endUtf16:end,route:prompt.route});terms.set(key,term);\n if(matches.length<8)matches.push({term:raw,kind:bucket,promptId:prompt.id,conversationId:prompt.conversationId,startUtf16:start,endUtf16:end,route:prompt.route});\n }\n }\n const measurementBasis='literal_english_lexicon_observed_native_input_utf16_v2',definition='Literal occurrences of the documented eight-word English lexicon in eligible observed native user-role inputs after existing redaction/elision; this does not attest universal human authorship. Unicode whole-word tokens; containing inputs counted once. No emotion, intent or universal-language inference. Ranges are relative to the immutable redacted containing input; routes identify that input.';\n return {lexiconVersion:PROFANITY_LEXICON_VERSION,language:'en-explicit-lexicon',measurementBasis,eligiblePrompts:eligible.length,occurrences:{value:occurrences,numerator:occurrences,denominator:eligible.length,unit:'english_lexicon_occurrence',measurementBasis,state:partial?'partial':'observed',definition},containingPrompts:{value:containing.size,numerator:containing.size,denominator:eligible.length,unit:'eligible_input_containing_english_lexicon_match',measurementBasis,state:partial?'partial':'observed',definition},buckets:[...bucketCounts].map(([kind,value])=>({kind,occurrences:value.occurrences,containingPrompts:value.prompts.size})),coverageGaps:['outside_english_lexicon_unassessed','hindi_hinglish_and_other_languages_unassessed',...(ambiguous?['ambiguous_quote_or_code_span']:[])],terms:[...terms.values()].map(t=>({term:t.term,kind:t.kind,occurrences:t.occurrences,containingPrompts:t.ids.size,samples:t.samples})).sort((a,b)=>b.occurrences-a.occurrences||a.term.localeCompare(b.term)||a.kind.localeCompare(b.kind)),matches};\n}\n", "import {createHash} from 'node:crypto';\nimport {auditProfanity,proseLabels,LEXICON_HINT} from './profanity.js';\nconst POSITIVE_HINT=/good (?:work|job)|well done|you understood|you (?:got|nailed)|you(?:['\u2019]re| are)/i;\nconst POSITIVE=/\\b(?:good (?:work|job)|well done|you understood (?:me|it)|you (?:got|nailed) (?:it|this)|you(?:['\u2019]re| are) (?:fucking )?(?:great|awesome))\\b/iu;\nconst NEGATED=/\\b(?:not|never|don['\u2019]?t|didn['\u2019]?t|no)\\b.{0,35}\\b(?:good|well done|understood|nailed|great|awesome)\\b/iu;\nconst NEGATIVE=/\\b(?:wrong|broken|stupid|missed|failed|why|mess|didn['\u2019]?t|not|bullshit|fuck(?:ed|ing)? (?:up|off))\\b/iu;\nconst YOU=/\\b(?:you|your|you['\u2019]re)\\b/iu;\nimport type {AuditLangLine,AuditPrompt,AuditPromptLex} from './contracts.js';\nimport type {ContextRecord,AuditLanguageLine,AuditModelFeedback} from './launch-contracts.js';\nexport type ProfaneLine=AuditLanguageLine;\nexport type ModelFeedback=AuditModelFeedback;\nconst words=(s:string)=>s.match(/[\\p{L}\\p{N}]+/gu)?.length??0;\n\n/** Models (of the prompt's conversation) named in its prose: whole first occurrence, prose label, not part of a longer identifier. */\nexport function namedModels(text:string,models:Iterable<string>):string[]{\n const out:string[]=[];let labels:Uint8Array|null=null;\n for(const model of models){const at=text.indexOf(model);if(at<0)continue;labels??=proseLabels(text);if(labels[at]!==0||/[\\p{L}\\p{N}_/-]/u.test(text[at-1]??'')||/[\\p{L}\\p{N}_/-]/u.test(text[at+model.length]??''))continue;out.push(model);}\n return out;\n}\n\n/**\n * Per-line lexical facts for the directed-language summary. Only lines with a\n * lexicon word or praise wording are kept; the rest cannot change any result.\n */\nexport function languageLines(text:string):AuditLangLine[]{\n const out:AuditLangLine[]=[];let labelCache:Uint8Array|null=null;const L=(i:number)=>(labelCache??=proseLabels(text))[i];let offset=0;\n for(const line of text.split('\\n')){const start=offset;offset+=line.length+1;const trimmed=line.trim();if(!trimmed)continue;const at=start+line.indexOf(trimmed),end=at+trimmed.length;\n if(!LEXICON_HINT.test(trimmed)&&!POSITIVE_HINT.test(trimmed))continue;\n // Classify this exact line independently so quotes/code never become feedback.\n const probe={id:'line',conversationId:'',role:'user' as const,originBasis:'claude_prompt_id' as const,identityBasis:'',eligibleHuman:true,excludedReason:null,eventAt:null,route:{basis:'canonical' as const,refs:[],scope:{} as never}};\n const local=auditProfanity([{...probe,text:line}]);const direct=local.terms?.some(t=>t.kind==='direct_prose'&&t.samples.some(sample=>L(start+sample.startUtf16)===0))??false;const nonprose=local.terms?.some(t=>t.kind!=='direct_prose')??false;\n const positiveMatch=trimmed.match(POSITIVE),positive=!!positiveMatch&&L(at+(positiveMatch.index??0))===0,negated=NEGATED.test(trimmed);\n const quoted=L(at)!==0||/^\\s*(?:>|[`~]{3}|[\"\u201C'])/u.test(line)||/^ {4}|^\\t/u.test(line);\n const row:AuditLangLine={};if(direct)row.d=1;if(nonprose)row.np=1;if(YOU.test(trimmed))row.y=1;if(positive)row.p=1;if(negated)row.ng=1;if(quoted)row.q=1;if(NEGATIVE.test(trimmed))row.n=1;\n if(direct&&!quoted&&words(trimmed)>=2){\n const spans=trimmed.length<=160?[{text:trimmed,start:at,end}]:[...trimmed.matchAll(/[^.!?;\\n]+[.!?;]?/gu)].map(match=>{const value=match[0].trim(),begin=at+match.index!+match[0].indexOf(value);return {text:value,start:begin,end:begin+value.length};}).filter(span=>span.text.length<=160&&words(span.text)>=2&&auditProfanity([{...probe,text:span.text}]).terms?.some(t=>t.kind==='direct_prose'&&L(span.start+t.samples[0]!.startUtf16)===0));\n if(spans.length)row.sp=spans.map(s=>[s.text,s.start,s.end] as const);else row.ns=1;\n }\n out.push(row);\n }\n return out;\n}\n\n/** Explicit lexical feedback, not inferred sentiment, authorship or coding quality. */\nexport function summarizeDirectedLanguage(prompts:readonly AuditPrompt[],records:readonly ContextRecord[]):{languageLines:ProfaneLine[];modelFeedback:ModelFeedback[];languageGaps:string[]}{\n const conversationModels=new Map<string,Map<string,Set<string|null>>>(),seenRecords=new Set<string>();const preceding=new Map<string,{model:string|null;provider:string|null}>(),groups=new Map<string,ContextRecord[]>();\n for(const r of records){const unique=`${r.conversationId}\\0${r.project}\\0${r.role}\\0${r.id}`;if(seenRecords.has(unique))continue;seenRecords.add(unique);if(r.role==='assistant'&&r.model){const names=conversationModels.get(r.conversationId)??new Map<string,Set<string|null>>(),providers=names.get(r.model)??new Set<string|null>();providers.add(r.provider);names.set(r.model,providers);conversationModels.set(r.conversationId,names);}const key=`${r.conversationId}\\0${r.project}`;const rows=groups.get(key)??[];rows.push(r);groups.set(key,rows);}\n for(const rows of groups.values()){let models=new Map<string,{model:string|null;provider:string|null}>();for(const r of rows){if(r.role==='user'){preceding.set(r.id,models.size===1?[...models.values()][0]!:{model:null,provider:null});models=new Map();}else if(r.role==='assistant')models.set(JSON.stringify([r.model,r.provider]),{model:r.model,provider:r.provider});}}\n const lines=new Map<string,{text:string;count:number;ids:Set<string>;models:Map<string,{provider:string|null;model:string|null;occurrences:number}>;samples:ProfaneLine['samples'][number][]}>(),feedback=new Map<string,{model:string|null;provider:string|null;negative:Set<string>;praise:Set<string>;associated:Set<string>;ids:Set<string>}>,gaps=new Set<string>(['lexical_directed_feedback_only','unknown_authorship_not_universally_attested']);\n const rowFor=(owner:{model:string|null;provider:string|null})=>{const key=JSON.stringify(owner);let row=feedback.get(key);if(!row){row={...owner,negative:new Set<string>(),praise:new Set<string>(),associated:new Set<string>(),ids:new Set<string>()};feedback.set(key,row);}return row;};\n for(const prompt of prompts){\n if(prompt.languageEligible===false||!(prompt.eligibleNativeInput??prompt.eligibleHuman))continue;\n const models=conversationModels.get(prompt.conversationId)??new Map<string,Set<string|null>>();\n const lex:AuditPromptLex=prompt.lex??{nm:namedModels(prompt.text,models.keys()),ll:languageLines(prompt.text)};\n const named=(lex.nm??[]).filter(m=>models.has(m));\n let owner=preceding.get(prompt.id)??{model:null,provider:null};\n if(named.length===1){const providers=models.get(named[0]!)!;owner={model:named[0]!,provider:providers.size===1?[...providers][0]!:null};}\n if(!preceding.has(prompt.id))gaps.add('language_context_capture_partial');\n if(owner.model)rowFor(owner).associated.add(prompt.id);\n let negative=false,praise=false;\n for(const line of lex.ll??[]){\n const explicitNegative=(named.length===1||!!line.y)&&!!line.d&&!line.p&&!!line.n;\n if(!line.q&&!line.np){negative||=explicitNegative;praise||=!!line.p&&!line.ng;}\n if(line.ns)gaps.add('long_profane_lines_not_displayed');\n for(const [text,start,end] of line.sp??[]){\n const key=text.toLocaleLowerCase('en').replace(/\\s+/gu,' ').replace(/[\\p{P}]+$/gu,'').trim(),item=lines.get(key)??{text,count:0,ids:new Set(),models:new Map(),samples:[] as ProfaneLine['samples'][number][]};item.count++;item.ids.add(prompt.id);if(item.samples.length<3)item.samples.push({promptId:prompt.id,conversationId:prompt.conversationId,startUtf16:start,endUtf16:end,route:prompt.route});\n if(explicitNegative&&!line.q&&!line.np&&owner.model){const k=JSON.stringify(owner),row=item.models.get(k)??{...owner,occurrences:0};row.occurrences++;item.models.set(k,row);}lines.set(key,item);\n }\n }\n if((negative||praise)&&owner.model){const row=rowFor(owner);if(negative)row.negative.add(prompt.id);if(praise)row.praise.add(prompt.id);row.ids.add(prompt.id);}else if(negative||praise)gaps.add('feedback_model_unattributed');\n }\n return {languageLines:[...lines.entries()].map(([key,row])=>({id:createHash('sha256').update(key).digest('hex').slice(0,20),text:row.text,occurrences:row.count,containingInputs:row.ids.size,models:[...row.models.values()].sort((a,b)=>b.occurrences-a.occurrences),samples:row.samples})).sort((a,b)=>b.occurrences-a.occurrences||a.text.localeCompare(b.text)).slice(0,6),modelFeedback:[...feedback.values()].map(row=>({provider:row.provider,model:row.model,associatedInputs:row.associated.size,directedNegativeInputs:row.negative.size,praiseInputs:row.praise.size,promptIds:[...row.ids].slice(0,12)})).sort((a,b)=>b.directedNegativeInputs-a.directedNegativeInputs||b.praiseInputs-a.praiseInputs||(a.model??'').localeCompare(b.model??'')),languageGaps:[...gaps]};\n}\n", "import type {AuditPrompt,AuditProjectFocus} from './contracts.js';\nimport {proseLabels} from './profanity.js';\n/** Explicit requested-task wording, never task completion or active time. */\nconst categories:readonly [string,RegExp][]=[\n ['Documentation',/\\b(?:write|update|fix|add|edit|draft|revise)\\b.{0,64}\\b(?:docs?|documentation|readme|guide|changelog)\\b/iu],\n ['Review',/\\b(?:review|audit|inspect)\\b.{0,64}\\b(?:code|diff|pr|pull request|implementation|tests?|changes|repo|repository)\\b/iu],\n ['Debugging',/\\b(?:fix|debug|repair|resolve|reproduce)\\b.{0,64}\\b(?:bug|error|crash|failure|issue|test|broken|timeout|memory|hang|problem)\\b/iu],\n ['Development',/\\b(?:build|implement|add|create|develop|refactor|ship|integrate)\\b.{0,64}\\b(?:feature|app|api|cli|function|component|command|module|tool|parser|service|code|support)\\b/iu],\n ['Research',/\\b(?:research|look up|investigate|compare|verify)\\b.{0,64}\\b(?:docs?|source|pricing|model|library|approach|behavior|format|implementation)\\b/iu],\n];\n/** Every category needs one of these verbs; a single cheap test skips most prompts. */\nconst VERBS=/\\b(?:write|update|fix|add|edit|draft|revise|review|audit|inspect|debug|repair|resolve|reproduce|build|implement|create|develop|refactor|ship|integrate|research|look up|investigate|compare|verify)\\b/iu;\n/** Requested-work labels of one prompt (prose only). */\nexport function focusLabels(raw:string):string[]{\n if(!VERBS.test(raw)||!categories.some(([,pattern])=>pattern.test(raw)))return [];\n const labels=proseLabels(raw),text=Array.from({length:raw.length},(_,i)=>labels[i]===0?raw[i]:' ').join('');\n return categories.filter(([,pattern])=>pattern.test(text)).map(([label])=>label);\n}\nexport function requestedProjectFocus(prompts:readonly AuditPrompt[]):AuditProjectFocus[]{\n const groups=new Map<string,AuditPrompt[]>();\n for(const prompt of prompts){if(prompt.languageEligible===false||!(prompt.eligibleNativeInput??prompt.eligibleHuman))continue;\n for(const label of prompt.lex?(prompt.lex.fc??[]):focusLabels(prompt.text)){const rows=groups.get(label)??[];if(!rows.some(p=>p.id===prompt.id))rows.push(prompt);groups.set(label,rows);}\n }\n // A label needs real support: at least 5 prompts and 10% of the project's prompts.\n const minimum=Math.max(5,Math.ceil(prompts.length*0.1));\n return [...groups].filter(([,rows])=>rows.length>=minimum).map(([label,rows])=>({label,inputs:rows.length,promptIds:rows.slice(0,3).map(p=>p.id),evidenceRoutes:rows.slice(0,3).map(p=>p.route),basis:'lexical_requested_work_v1' as const})).sort((a,b)=>b.inputs-a.inputs||a.label.localeCompare(b.label)).slice(0,2);\n}\n", "import {digest} from './source.js';\nimport type {AuditConversation,AuditEvidenceRoute,AuditInsight,AuditPhrase,AuditPrompt} from './contracts.js';\n\nexport const EXACT_REPEAT_LIMITS=Object.freeze({rows:20,supports:8,maxRowBytes:8192});\nconst inputBasis='normalized_short_prompt_equality_v2';\n/** Short prompts compared case- and whitespace-insensitively, paste/image placeholders removed. */\nconst PLACEHOLDER=/\\[(?:Pasted text|Image) #\\d+[^\\]]*\\]/gi;\nexport function normalizedLine(text:string):string|null{const n=text.replace(PLACEHOLDER,'').toLowerCase().replace(/\\s+/g,' ').trim().replace(/^[ .!?,]+|[ .!?,]+$/g,'');return n.length>0&&n.length<=60?n:null;}\nconst elapsedBasis='eligible_native_input_event_time_range_v1';\nconst eligible=(prompt:AuditPrompt)=>prompt.eligibleHuman&&prompt.excludedReason===null;\nconst plural=(n:number,word:string)=>`${n} ${word}${n===1?'':'s'}`;\nfunction duration(ms:number):string{\n const seconds=ms/1000;if(seconds<60)return `${Number(seconds.toFixed(3))}s`;\n const minutes=Math.floor(seconds/60);if(minutes<60)return `${minutes}m`;\n const hours=Math.floor(minutes/60);if(hours<24)return `${hours}h ${minutes%60}m`;\n return `${Math.floor(hours/24)}d ${hours%24}h`;\n}\n\n/** Final-view arithmetic only: literal equality and recorded clocks, never inferred work. */\nexport function deterministicFindings(conversations:readonly AuditConversation[],prompts:readonly AuditPrompt[],timezone:string,partial:boolean,scopeHash:string):{insights:AuditInsight[];phrases:AuditPhrase[]}{\n const inputs=prompts.filter(eligible),byConversation=new Map<string,AuditPrompt[]>(),wordings=new Map<string,AuditPrompt[]>();\n for(const prompt of inputs){const key=prompt.lex?prompt.lex.nl??null:normalizedLine(prompt.text);if(key!==null){const group=wordings.get(key)??[];group.push(prompt);wordings.set(key,group);}const conversation=byConversation.get(prompt.conversationId)??[];conversation.push(prompt);byConversation.set(prompt.conversationId,conversation);}\n const repeated=[...wordings].filter(([,group])=>group.length>=2).sort(([textA,a],[textB,b])=>b.length-a.length||textA.localeCompare(textB));\n const phrases:AuditPhrase[]=repeated.filter(([text])=>Buffer.byteLength(text)<=EXACT_REPEAT_LIMITS.maxRowBytes).slice(0,EXACT_REPEAT_LIMITS.rows).map(([text,group])=>{\n const ordered=[...group].sort((a,b)=>a.conversationId.localeCompare(b.conversationId)||a.id.localeCompare(b.id)),supports:AuditPrompt[]=[];const selected=new Set<string>();\n for(const prompt of ordered){if(supports.length>=EXACT_REPEAT_LIMITS.supports)break;if(!selected.has(prompt.conversationId)){supports.push(prompt);selected.add(prompt.conversationId);}}\n for(const prompt of ordered){if(supports.length>=EXACT_REPEAT_LIMITS.supports)break;if(!supports.some(p=>p.id===prompt.id))supports.push(prompt);}\n return {id:digest(`${scopeHash}:${inputBasis}:${text}`).slice(0,32),text,prompts:group.length,occurrences:group.length,denominator:inputs.length,measurementBasis:inputBasis,conversationIds:[...new Set(supports.map(p=>p.conversationId))],promptIds:supports.map(p=>p.id),evidenceRoutes:supports.map(p=>p.route)};\n });\n const insights:AuditInsight[]=[];let longest:{conversation:AuditConversation;first:AuditPrompt;last:AuditPrompt;ms:number;datesMissing:boolean}|null=null;\n for(const conversation of conversations){const group=byConversation.get(conversation.id)??[],dated=group.filter(p=>p.eventAt!==null&&Number.isFinite(Date.parse(p.eventAt))).sort((a,b)=>a.eventAt!.localeCompare(b.eventAt!)||a.id.localeCompare(b.id));if(dated.length<2)continue;\n const first=dated[0]!,last=dated.at(-1)!,ms=Date.parse(last.eventAt!)-Date.parse(first.eventAt!);if(longest===null||ms>longest.ms||ms===longest.ms&&conversation.id<longest.conversation.id)longest={conversation,first,last,ms,datesMissing:dated.length!==group.length};\n }\n if(longest){const definition='Elapsed span between the first and last dated eligible native inputs in one selected conversation. Original record clocks only; unknown dates excluded. This is an observed input span, not working time or proof of completion.';\n const date=new Intl.DateTimeFormat('en-US',{timeZone:timezone,year:'numeric',month:'short',day:'numeric'});const span=duration(longest.ms),caption=`${longest.conversation.alias}: ${span} observed input span \u00B7 ${date.format(new Date(longest.first.eventAt!))}\u2013${date.format(new Date(longest.last.eventAt!))}`;\n insights.push({id:'observed-conversation-input-span-v1',basis:'deterministic',caption,publicCaption:`Longest observed input span: ${span}`,value:{value:longest.ms,numerator:longest.ms,denominator:null,unit:'milliseconds_observed_input_span',measurementBasis:elapsedBasis,state:partial||longest.datesMissing?'partial':'observed',definition},conversationIds:[longest.conversation.id],promptIds:[longest.first.id,longest.last.id],definition});\n }\n if(repeated.length){const count=repeated.reduce((n,[,group])=>n+group.length,0),supports=repeated.flatMap(([,group])=>group.slice(0,EXACT_REPEAT_LIMITS.supports)).slice(0,EXACT_REPEAT_LIMITS.supports),definition='Short human prompts (60 characters or fewer) that repeat, compared ignoring case, whitespace, trailing punctuation and paste/image placeholders.';\n const caption=`${plural(count,'prompt')} in ${plural(repeated.length,'repeated line')} \u00B7 ${inputs.length} prompts`;\n insights.push({id:'exact-repeated-input-wording-v1',basis:'deterministic',caption,publicCaption:caption,value:{value:count,numerator:count,denominator:inputs.length,unit:'eligible_input_in_exact_repeat_group',measurementBasis:inputBasis,state:partial?'partial':'observed',definition},conversationIds:[...new Set(supports.map(p=>p.conversationId))],promptIds:supports.map(p=>p.id),definition});\n }\n return {insights:insights.slice(0,2),phrases};\n}\n", "/**\n * Per-prompt derived features for the 1.8 story (port of the insight\n * prototype's features.py). Deterministic, lexicon based, O(len(text)).\n *\n * Runs in the scan workers while the text is in memory; only the derived\n * numbers, sparse phrase indices and bounded, filtered short strings are\n * kept. Full prompt text is never cached.\n */\n\nexport const STORY_FEATURES_VERSION = 1;\n\n/** Compact per-prompt feature row. Short keys: thousands of these live in the derived cache. */\nexport interface PromptFeatures {\n /** Typed characters, words, lines. */\n ch: number; w: number; ln: number;\n /** Bit flags, see FLAG. */\n fl: number;\n /** Swear / insult counts measured on the tone window (paste guard applied). */\n sw: number; ins: number;\n /** First \u22646 swear words (lowercase, unmasked; masked on display). */\n sws?: string[];\n fr: number; cw: number; cr: number; ex: number;\n we: number; i: number; fi: number; pf: number; hi: number;\n /** First word of the prompt (lowercase, \u226424 chars). */\n fw: string;\n /** Normalized line (lowercase, placeholders removed, \u226460 chars) when the prompt is \u226480 chars. */\n sl?: string;\n /** Indices into TICS that occur in this prompt. */\n tc?: number[];\n /** Indices into ADDRESS used vocatively in this prompt. */\n ad?: number[];\n}\n\nexport const FLAG = {\n paste: 1, image: 2, code: 4, url: 8, pasteSuspect: 16, slur: 32, polite: 64, thanks: 128, sorry: 256,\n multiPunct: 512, question: 1024, delegate: 2048, lets: 4096, please: 8192, history: 16384,\n} as const;\nexport const has = (f: PromptFeatures, flag: number) => (f.fl & flag) !== 0;\n\nexport const PLACEHOLDER = /\\[(?:Pasted text|Image) #\\d+[^\\]]*\\]/gi;\nconst URL_RX = /https?:\\/\\/\\S+/g;\nconst CODEISH = /```[\\s\\S]*?```/g;\nexport const WORD = /[a-z][a-z']*/g;\n\nconst SWEAR_STEMS = ['fuck', 'shit', 'bullshit', 'wtf', 'damn', 'goddamn', 'crap', 'bitch', 'asshole', 'dumbass',\n 'stfu', 'ffs', 'piss', 'bastard', 'motherf', 'bloody',\n 'bsdk', 'chutiya', 'chutiye', 'madarchod', 'bhenchod', 'behenchod', 'gandu'];\nconst SWEAR_EXACT = new Set(['ffs', 'wtf', 'stfu']);\nconst SWEAR_PREFIX = SWEAR_STEMS.filter(s => !SWEAR_EXACT.has(s));\nconst INSULT = ['stupid', 'idiot', 'dumb', 'moron', 'useless', 'pathetic', 'lazy', 'incompetent', 'garbage', 'trash', 'retard'];\nconst SLUR_STEMS = ['retard'];\nconst POLITE = /\\b(please|pls|plz|thanks|thank you|thank u|thx|ty|appreciate|great job|good job|well done|awesome|amazing|love it|love this|nice work|brilliant|you're the best|perfect)\\b/;\nconst THANKS = /\\b(thanks|thank you|thank u|thx|ty|appreciate it|great job|good job|well done|nice work)\\b/;\nconst SORRY = /\\b(sorry|my bad|apologi[sz]e)\\b/;\nconst FRUSTRATION = /\\b(again|still not|still doesn't|still isn't|i told you|i said|i already|not working|doesn't work|didn't work|isn't working|why (?:the|did|are|is|would) |what the|seriously|come on|for the last time|how many times|are you (?:kidding|serious|dumb|stupid))\\b/g;\nconst DELEGATE = /\\b(sub-?agents?|agents? in parallel|parallel agents?|spawn|launch (?:\\w+ )?agents?|team of agents|multiple agents|\\d+ agents)\\b/;\nconst FILLER = /\\b(basically|kind of|sort of|i guess|i mean|you know|like,|um+|uh+|okay so|so yeah|whatever)\\b/g;\nconst PERFECTION = /\\b(best possible|perfect(?:ly)?|exactly|properly|every single|completely|100%|flawless|world[- ]class|insanely|extremely)\\b/g;\nconst QWORDS = new Set(['what', 'why', 'how', 'is', 'are', 'can', 'could', 'should', 'does', 'do', 'did', 'where', 'when', 'which', 'who', 'will', 'would']);\nconst WE = /\\b(we|we're|we've|let's|us|our)\\b/g;\nconst I_ = /\\b(i|i'm|i've|me|my)\\b/g;\nconst HINGLISH = /\\b(bhai|yaar|kya|hai|nahi|kar|karo|acha|accha|theek|matlab|abhi|bas|chal|haan)\\b/g;\nconst CAPS = /\\b[A-Z][A-Z']{2,}\\b/g;\nconst CAPS_OK = new Set(['API', 'URL', 'HTML', 'CSS', 'JSON', 'CLI', 'PR', 'UI', 'UX', 'MCP', 'LLM', 'SDK', 'README', 'TODO', 'IST', 'PDF', 'NPM', 'AWS', 'GPT', 'MD', 'SEO', 'JS', 'TS', 'ID', 'OK', 'AI', 'CEO', 'USA', 'SQL', 'DB', 'SSH', 'HTTP', 'HTTPS', 'PNG', 'SVG', 'CTA', 'FAQ']);\n\nexport function isSwearWord(w: string): boolean {\n if (SWEAR_EXACT.has(w)) return true;\n for (const s of SWEAR_PREFIX) if (w.startsWith(s)) return true;\n return false;\n}\nconst isInsult = (w: string) => INSULT.some(s => w.startsWith(s));\nexport const isSlur = (w: string) => SLUR_STEMS.some(s => w.startsWith(s));\nexport const isFWord = (w: string) => w.startsWith('fuck') || w.startsWith('motherf');\n\n/** f*****g style masking for display. */\nexport function mask(w: string): string {\n return w.length <= 2 ? w : w[0] + '*'.repeat(w.length - 2) + w[w.length - 1];\n}\n\n/** Placeholders, fenced code and URLs removed; curly apostrophes straightened. */\nexport function cleanForTone(text: string): string {\n return text.replace(PLACEHOLDER, ' ').replace(/[\u2018\u2019]/g, \"'\").replace(CODEISH, ' ').replace(URL_RX, ' ');\n}\n\nconst count = (rx: RegExp, s: string) => { rx.lastIndex = 0; let n = 0; while (rx.exec(s)) n++; rx.lastIndex = 0; return n; };\nconst words = (s: string): string[] => s.match(WORD) ?? [];\n\n/* ------------------------------------------------------------ catalogs --- */\n\nexport const TICS = ['one more thing', 'each and every', 'do one thing', 'every single thing', 'kind of a thing', 'and all', 'and stuff', 'or something',\n 'at the end of the day', 'to be honest', 'basically', 'you know what', 'let me know', 'best possible', 'world class', 'insanely',\n 'make it pop', 'help me out', 'what do you think', \"i don't know\", 'just do it', 'ship it', 'go ahead', 'lfg', \"let's go\", 'no worries',\n 'makes sense', 'figure it out', 'deep research', 'ultra think', 'ultrathink', 'step by step', 'one shot', 'whatever it takes',\n 'end to end', 'from scratch', 'like a pro', 'production ready', 'properly', 'exactly', 'and everything', 'all of that', 'the whole thing',\n 'you know', 'i mean', 'sort of', 'kind of', 'so yeah', 'okay so'] as const;\nconst CLAUSE_FINAL = new Set(['and all', 'and stuff', 'or something', 'and everything', 'all of that', 'and all that']);\n/** Expected rate per 100 prompts for a typical heavy user (initial priors). */\nexport const TIC_PRIOR: Readonly<Record<string, number>> = {\n 'kind of': 8, basically: 5, exactly: 6, properly: 3, 'you know': 3, 'i mean': 2, 'what do you think': 2, \"i don't know\": 3, 'go ahead': 3,\n 'let me know': 3, 'the whole thing': 2, 'sort of': 2, 'and all': 2, 'or something': 2, 'from scratch': 1, 'step by step': 1, 'makes sense': 1.5,\n 'deep research': 0.5,\n};\nconst esc = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n/** Phrases by first word: one walk over the words of a prompt finds every catchphrase. */\nconst TIC_BY_FIRST = new Map<string, {phrase: string; index: number; final: boolean}[]>();\nTICS.forEach((phrase, index) => {\n const first = phrase.split(' ')[0]!;\n const list = TIC_BY_FIRST.get(first) ?? [];\n list.push({phrase, index, final: CLAUSE_FINAL.has(phrase)});\n TIC_BY_FIRST.set(first, list);\n});\nconst CLAUSE_END = /^\\s*(?:[.,!?;:)\\n]|$|and\\b|so\\b|but\\b)/;\nconst isWordChar = (c: string | undefined) => c !== undefined && /[A-Za-z0-9_]/.test(c);\n/** Indices of TICS present in the (lowercase) text; clause-final hedges only before punctuation, the end, or and/so/but. */\nexport function ticsIn(low: string): number[] {\n const found = new Set<number>();\n const rx = /[a-z']+/g;\n let m: RegExpExecArray | null;\n while ((m = rx.exec(low)) !== null) {\n const list = TIC_BY_FIRST.get(m[0]);\n if (!list || isWordChar(low[m.index - 1])) continue;\n for (const t of list) {\n if (found.has(t.index) || !low.startsWith(t.phrase, m.index)) continue;\n const end = m.index + t.phrase.length;\n if (t.final ? CLAUSE_END.test(low.slice(end, end + 12)) : !isWordChar(low[end]) || !isWordChar(low[end - 1])) found.add(t.index);\n }\n }\n return [...found].sort((a, b) => a - b);\n}\n\nexport const ADDRESS = ['dude', 'bro', 'buddy', 'babe', 'baby', 'my friend', 'man', 'mate', 'boss', 'sir', 'brother', 'bhai', 'yaar', 'chief', 'champ', 'my guy', 'darling', 'love'] as const;\nconst ADDRESS_GATE = new RegExp('\\\\b(' + ADDRESS.map(esc).join('|') + ')\\\\b', 'g');\nconst ADDRESS_INDEX = new Map<string, number>(ADDRESS.map((a, i) => [a, i]));\nconst VOCATIVE_BEFORE = /(?:^|[,.!?]\\s*|\\b(?:hey|yo|ok|okay|thanks|no|come on)\\s+)$/;\n/** Indices of ADDRESS terms used vocatively: at a clause start or end, after hey/yo/ok/thanks, or before punctuation. */\nexport function addressIn(low: string): number[] {\n const found = new Set<number>();\n ADDRESS_GATE.lastIndex = 0;\n let m: RegExpExecArray | null;\n while ((m = ADDRESS_GATE.exec(low)) !== null) {\n const i = ADDRESS_INDEX.get(m[1]!)!;\n if (found.has(i)) continue;\n const end = m.index + m[0].length;\n if (VOCATIVE_BEFORE.test(low.slice(Math.max(0, m.index - 12), m.index)) || /^\\s*[,.!?]/.test(low.slice(end, end + 8)) || end === low.length) found.add(i);\n }\n return [...found].sort((a, b) => a - b);\n}\n\n/* ----------------------------------------------------------- featurize --- */\n\nexport interface FeaturizeInput {\n /** Typed text (Claude history display) or transcript text. */\n text: string;\n /** True when the text is what the user typed (history.jsonl), false for transcript text that may expand pastes. */\n typed: boolean;\n hasPaste?: boolean;\n hasImage?: boolean;\n}\n\nexport function featurize(input: FeaturizeInput): PromptFeatures {\n const raw = input.text;\n let t = cleanForTone(raw);\n const all = words(t.toLowerCase());\n // Paste guard: transcripts expand pastes inline, so a giant prompt is mostly pasted material.\n // Tone then only looks at the head and tail, where the typed framing lives.\n const pasteSuspect = all.length > 1500 || (all.length > 600 && !input.typed);\n if (pasteSuspect) {\n const toks = t.split(/\\s+/).filter(Boolean);\n t = toks.slice(0, 150).concat('\u2026', toks.slice(-150)).join(' ');\n }\n const low = t.toLowerCase();\n const tone = pasteSuspect ? words(low) : all;\n let letters = 0, upper = 0;\n for (let k = 0; k < t.length; k++) {\n const c = t.charCodeAt(k);\n if (c >= 65 && c <= 90) { letters++; upper++; } else if (c >= 97 && c <= 122) letters++;\n else if (c > 127 && /\\p{L}/u.test(t[k]!)) { letters++; if (t[k] !== t[k]!.toLowerCase()) upper++; }\n }\n let caps = 0;\n for (const m of t.match(CAPS) ?? []) if (!CAPS_OK.has(m)) caps++;\n const swears: string[] = [];\n let insults = 0, slur = false;\n for (const w of tone) {\n if (isSwearWord(w)) swears.push(w);\n if (isInsult(w)) insults++;\n if (!slur && isSlur(w)) slur = true;\n }\n const first = all[0] ?? '';\n const rawLow = raw.toLowerCase();\n const trimmed = raw.trim();\n let fl = 0;\n if (/\\[Pasted text #/.test(raw) || input.hasPaste) fl |= FLAG.paste;\n if (input.hasImage || raw.includes('[Image #')) fl |= FLAG.image;\n if (raw.includes('```')) fl |= FLAG.code;\n URL_RX.lastIndex = 0;\n if (URL_RX.test(raw)) fl |= FLAG.url;\n URL_RX.lastIndex = 0;\n if (pasteSuspect) fl |= FLAG.pasteSuspect;\n if (slur) fl |= FLAG.slur;\n if (POLITE.test(low)) fl |= FLAG.polite;\n if (THANKS.test(low)) fl |= FLAG.thanks;\n if (SORRY.test(low)) fl |= FLAG.sorry;\n if (/[!?]{3,}/.test(raw)) fl |= FLAG.multiPunct;\n if (trimmed.endsWith('?') || (QWORDS.has(first) && all.length < 40)) fl |= FLAG.question;\n if (DELEGATE.test(low)) fl |= FLAG.delegate;\n if (/\\blet'?s\\b/.test(rawLow)) fl |= FLAG.lets;\n if (/\\b(please|pls|plz)\\b/.test(rawLow)) fl |= FLAG.please;\n if (input.typed) fl |= FLAG.history;\n let excl = 0;\n for (let k = raw.indexOf('!'); k >= 0; k = raw.indexOf('!', k + 1)) excl++;\n let lines = 1;\n for (let k = raw.indexOf('\\n'); k >= 0; k = raw.indexOf('\\n', k + 1)) lines++;\n const f: PromptFeatures = {\n ch: raw.length, w: all.length, ln: lines, fl,\n sw: swears.length, ins: insults,\n fr: count(FRUSTRATION, low), cw: caps, cr: letters >= 12 ? Math.round((upper / letters) * 1000) / 1000 : 0, ex: excl,\n we: count(WE, low), i: count(I_, low), fi: count(FILLER, low), pf: count(PERFECTION, low), hi: count(HINGLISH, low),\n fw: first.slice(0, 24),\n };\n if (swears.length) f.sws = swears.slice(0, 6);\n if (raw.length <= 80) {\n const sl = raw.replace(PLACEHOLDER, '').toLowerCase().replace(/\\s+/g, ' ').trim().slice(0, 60);\n if (sl) f.sl = sl;\n }\n const tc = ticsIn(rawLow);\n if (tc.length) f.tc = tc;\n const ad = addressIn(rawLow);\n if (ad.length) f.ad = ad;\n return f;\n}\n\n/* -------------------------------------------------------------- quotes --- */\n\n/** Topics a quote must never touch (health, relationships, money stress, secrets, ...). */\nexport const SENSITIVE = /\\b(die|dying|suicid\\w*|kill (?:my|me)\\w*|depress\\w*|demons?|deserve|anxiety|therap\\w*|panic|lonely|worthless|hate myself|cry(?:ing)?|breakup|girlfriend|boyfriend|wife|husband|sex\\w*|porn|nude|drunk|password|token|secret|api[_ -]?key|ssn|salary|loan|debt|visa|lawyer|doctor|hospital|meds?)\\b/i;\nexport const SECRETISH = /(sk-[A-Za-z0-9]|tvly-|AKIA|ghp_|xox[bp]-|@[\\w.-]+\\.\\w{2,}|[A-Za-z0-9_-]{32,}|\\/Users\\/|\\/home\\/|~\\/|https?:\\/\\/|\\[REDACTED|<redacted)/;\n\n/**\n * An on-screen quote: one line, short, no secrets/paths/emails/keys, no\n * sensitive topics, swears masked. Null when the text must not be quoted.\n */\nexport function safeQuote(text: string, maxLength = 90): string | null {\n let t = text.replace(PLACEHOLDER, '').replace(/\\s+/g, ' ').trim();\n if (!t || SENSITIVE.test(t) || SECRETISH.test(t)) return null;\n // Masking keeps length, so only the part that can be shown needs it.\n t = t.slice(0, maxLength + 40).replace(/[A-Za-z']+/g, w => { const l = w.toLowerCase(); return isSwearWord(l) || isSlur(l) ? mask(w) : w; }) + t.slice(maxLength + 40);\n if (t.length <= maxLength) return t;\n const cut = t.slice(0, maxLength - 1);\n const space = cut.lastIndexOf(' ');\n return (space > 0 ? cut.slice(0, space) : cut) + '\u2026';\n}\n\n/** Masks swears in a short typed line for display (no other filtering). */\nexport function maskLine(text: string): string {\n return text.replace(/[A-Za-z']+/g, w => { const l = w.toLowerCase(); return isSwearWord(l) || isSlur(l) ? mask(w) : w; });\n}\n\n/* ------------------------------------------------------- side tables --- */\n\nexport const TOPIC_STOP = new Set((\"the a an and or of to in on for is it that this i you we be are was with as at by from so if but not do can me my your our just what how all also now like then there they them these those one some any more much very really thing things something everything get got make made want need see know think going go let lets let's okay ok yes no up out into about will would should could have has had been being he she his her him its it's i'm don't can't isn't doesn't which who when where why here same other only even still well right good way time new use using done try give take put come look\").split(' '));\n\n/** Words of a prompt for the vocabulary counter (typo fingerprint): \u22653 letters. */\nexport function vocabularyWords(text: string): string[] {\n return words(cleanForTone(text).toLowerCase()).filter(w => w.length >= 3 && w.length <= 24);\n}\n\n/** Distinct topic words of a prompt (day vs night topics). */\nexport function topicWords(text: string): Set<string> {\n const out = new Set<string>();\n for (const w of words(cleanForTone(text).toLowerCase())) if (w.length >= 3 && w.length <= 24 && !TOPIC_STOP.has(w) && !isSwearWord(w)) out.add(w);\n return out;\n}\n", "/** Local calendar parts of epoch milliseconds in a time zone, memoized per 15 minutes. */\nexport interface LocalParts {\n /** YYYY-MM-DD */\n day: string;\n /** YYYY-MM */\n month: string;\n /** 0..23 */\n hour: number;\n /** 0=Mon .. 6=Sun */\n dow: number;\n minute: number;\n}\n\nconst WEEKDAY: Record<string, number> = {Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6};\n\nexport function localClock(timezone: string): (at: number) => LocalParts {\n const format = new Intl.DateTimeFormat('en-US', {\n timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short', hourCycle: 'h23',\n });\n const memo = new Map<number, LocalParts>();\n return at => {\n const slot = Math.floor(at / 900_000);\n let hit = memo.get(slot);\n if (hit) return {...hit, minute: hit.minute + Math.floor((at - slot * 900_000) / 60_000)};\n const parts: Record<string, string> = {};\n for (const p of format.formatToParts(new Date(slot * 900_000))) parts[p.type] = p.value;\n const hour = Number(parts.hour) % 24;\n hit = {day: `${parts.year}-${parts.month}-${parts.day}`, month: `${parts.year}-${parts.month}`, hour, dow: WEEKDAY[parts.weekday!] ?? 0, minute: Number(parts.minute)};\n memo.set(slot, hit);\n return {...hit, minute: hit.minute + Math.floor((at - slot * 900_000) / 60_000)};\n };\n}\n\nexport const HOUR_NAME = (h: number) => `${h % 12 || 12}${h < 12 ? 'am' : 'pm'}`;\nexport const WEEKDAY_NAMES = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];\nconst MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];\nconst MONTHS_LONG = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];\n/** '2026-03' -> 'Mar 2026' (or 'Mar' without year, 'March' long). */\nexport function monthName(month: string, style: 'short' | 'year' | 'long' = 'year'): string {\n const [y, m] = month.split('-');\n const i = Number(m) - 1;\n return style === 'long' ? MONTHS_LONG[i]! : style === 'short' ? MONTHS[i]! : `${MONTHS[i]} ${y}`;\n}\n/** '2026-03-07' -> 'Mar 7' (with year: 'Mar 7, 2026'; long: 'March 7'). */\nexport function dayName(day: string, style: 'short' | 'year' | 'long' = 'short'): string {\n const [y, m, d] = day.split('-');\n const i = Number(m) - 1;\n if (style === 'long') return `${MONTHS_LONG[i]} ${Number(d)}`;\n return style === 'year' ? `${MONTHS[i]} ${Number(d)}, ${y}` : `${MONTHS[i]} ${Number(d)}`;\n}\n/** Whole days between two YYYY-MM-DD dates. */\nexport function daysBetween(a: string, b: string): number {\n return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000);\n}\n/** ISO week key 'YYYY-Www' and its Monday (YYYY-MM-DD) for a local day. */\nconst weekMemo = new Map<string, {key: string; monday: string}>();\nexport function isoWeek(day: string): {key: string; monday: string} {\n let hit = weekMemo.get(day);\n if (!hit) { hit = computeIsoWeek(day); if (weekMemo.size > 5000) weekMemo.clear(); weekMemo.set(day, hit); }\n return hit;\n}\nfunction computeIsoWeek(day: string): {key: string; monday: string} {\n const d = new Date(`${day}T00:00:00Z`);\n const dow = (d.getUTCDay() + 6) % 7;\n const monday = new Date(d.getTime() - dow * 86_400_000);\n const thursday = new Date(monday.getTime() + 3 * 86_400_000);\n const year = thursday.getUTCFullYear();\n const jan4 = new Date(Date.UTC(year, 0, 4));\n const week1 = new Date(jan4.getTime() - ((jan4.getUTCDay() + 6) % 7) * 86_400_000);\n const week = 1 + Math.round((monday.getTime() - week1.getTime()) / (7 * 86_400_000));\n return {key: `${year}-W${String(week).padStart(2, '0')}`, monday: monday.toISOString().slice(0, 10)};\n}\n", "/**\n * Story facts derived from one file while its text is in memory: per-prompt\n * features, the lexical data the legacy language passes need, per-turn\n * response stats, bounded quote candidates for fixed slots, and per-file\n * word counters. After this runs the prompt text can be dropped.\n */\nimport type {AuditPromptLex} from './contracts.js';\nimport {profanityHits} from './profanity.js';\nimport {languageLines, namedModels} from './language-feedback.js';\nimport {focusLabels} from './project-focus.js';\nimport {normalizedLine} from './findings.js';\nimport {featurize, safeQuote, topicWords, vocabularyWords, type PromptFeatures} from './story-lexicon.js';\nimport {localClock} from './story-time.js';\n\n/** Tools that start a subagent. */\nexport const AGENT_TOOLS = new Set(['Task', 'Agent', 'spawn_agent', 'spawn_agents', 'TaskCreate']);\nexport const isAgentTool = (name: string) => AGENT_TOOLS.has(name) || name.startsWith('spawn');\n\n/** One assistant-side event (a response line or a tool call). */\nexport interface TurnEvent {at: number; tools: number; subs: number; weight: number}\n\n/** Response stats of the turn a prompt started, from this file's events. */\nexport interface TurnStats {\n /** Assistant events until the next prompt. */ m: number;\n /** Tool calls. */ tl: number;\n /** Subagents launched. */ sa: number;\n /** Seconds from the prompt to the last assistant event of the turn. */ d: number | null;\n /** The turn was interrupted (Esc / turn_aborted). */ x: 0 | 1;\n /** Seconds since the last assistant event before this prompt. */ g: number | null;\n}\n\n/** Words per month and slot (0 = night 0\u20134h, 1 = day 9\u201318h) in documents (prompts). */\nexport interface TopicBag {month: string; night: number; day: number; words: Map<string, [number, number]>}\n\nexport interface StoryTextFacts {\n /** Word counts of this file's prompts (typo fingerprint); null for Claude transcripts (their typed text lives in history.jsonl). */\n vocab: Map<string, number> | null;\n topics: TopicBag[] | null;\n}\n\ninterface PromptLike {key: string; at: number | null; text: string; kind: string; reason: string | null; project: string | null;\n before: string | null; after: string | null; f?: PromptFeatures; lex?: AuditPromptLex; q?: string; t?: TurnStats}\n\nexport function promptLex(text: string, models: Iterable<string>): AuditPromptLex | undefined {\n const lex: {-readonly [K in keyof AuditPromptLex]: AuditPromptLex[K]} = {};\n const hits = profanityHits(text);\n if (hits?.hits.length) lex.pt = hits.hits;\n if (hits?.ambiguous) lex.pa = 1;\n const nl = normalizedLine(text);\n if (nl !== null) lex.nl = nl;\n const fc = focusLabels(text);\n if (fc.length) lex.fc = fc;\n const nm = namedModels(text, models);\n if (nm.length) lex.nm = nm;\n const ll = languageLines(text);\n if (ll.length) lex.ll = ll;\n return Object.keys(lex).length ? lex : undefined;\n}\n\nconst QUOTE_TOP = 8, QUOTE_SUBAGENT_TOP = 5, QUOTE_LAST_PER_PROJECT = 3;\n\n/**\n * Adds story fields to the human prompts of one file (in place) and returns\n * the file's word counters. `typed` marks text the user typed (no inline pastes).\n */\nexport function deriveStory(prompts: PromptLike[], events: TurnEvent[], interrupts: number[], options: {typed: boolean; counters: boolean; timezone: string; from?: number; previous?: StoryTextFacts}): StoryTextFacts {\n const human = prompts.filter(p => p.kind === 'human' && p.at !== null).sort((a, b) => a.at! - b.at!);\n const fresh = new Set(prompts.slice(options.from ?? 0));\n const models = new Set<string>();\n for (const p of prompts) { if (p.before) models.add(p.before); if (p.after) models.add(p.after); }\n const vocab = options.counters ? options.previous?.vocab ?? new Map<string, number>() : null;\n const topics = options.counters ? new Map<string, TopicBag>((options.previous?.topics ?? []).map(t => [t.month, t])) : null;\n const clock = localClock(options.timezone);\n for (const p of human) {\n if (!fresh.has(p)) continue;\n p.f = featurize({text: p.text, typed: options.typed});\n const lex = promptLex(p.text, models);\n if (lex) p.lex = lex;\n if (vocab) for (const w of vocabularyWords(p.text)) vocab.set(w, (vocab.get(w) ?? 0) + 1);\n if (topics) {\n const {hour, month} = clock(p.at!);\n const slot = hour < 5 ? 0 : hour >= 9 && hour < 19 ? 1 : -1;\n if (slot >= 0) {\n let bag = topics.get(month);\n if (!bag) { bag = {month, night: 0, day: 0, words: new Map()}; topics.set(month, bag); }\n if (slot === 0) bag.night++; else bag.day++;\n for (const w of topicWords(p.text)) { let c = bag.words.get(w); if (!c) { c = [0, 0]; bag.words.set(w, c); } c[slot as 0 | 1]++; }\n }\n }\n }\n turnStats(human, events, interrupts);\n // Quote candidates only for the fixed slots: first prompt, last words per project,\n // the costliest turns (by a token-weight proxy) and the biggest subagent launches.\n const weight = new Map<PromptLike, number>();\n const slots = new Set<PromptLike>();\n if (human.length) slots.add(human[0]!);\n const byProject = new Map<string, PromptLike[]>();\n for (const p of human) { const k = p.project ?? ''; const list = byProject.get(k) ?? []; list.push(p); byProject.set(k, list); }\n for (const list of byProject.values()) for (const p of list.slice(-QUOTE_LAST_PER_PROJECT)) slots.add(p);\n turnWeights(human, events, weight);\n for (const p of [...human].sort((a, b) => (weight.get(b) ?? 0) - (weight.get(a) ?? 0)).slice(0, QUOTE_TOP)) slots.add(p);\n for (const p of human.filter(p => (p.t?.sa ?? 0) > 0).sort((a, b) => b.t!.sa - a.t!.sa).slice(0, QUOTE_SUBAGENT_TOP)) slots.add(p);\n for (const p of slots) { if (!p.text) continue; const q = safeQuote(p.text, 90); if (q) p.q = q; }\n return {vocab, topics: topics ? [...topics.values()] : null};\n}\n\n/** Two-pointer assignment of assistant events and interrupts to the turn windows [prompt, next prompt). */\nfunction turnStats(human: PromptLike[], events: TurnEvent[], interrupts: number[]): void {\n const ev = events.filter(e => Number.isFinite(e.at)).sort((a, b) => a.at - b.at);\n const intr = interrupts.filter(Number.isFinite).sort((a, b) => a - b);\n let j = 0, k = 0, lastAt: number | null = null;\n human.forEach((p, i) => {\n const start = p.at!, next = i + 1 < human.length ? human[i + 1]!.at! : Infinity;\n while (j < ev.length && ev[j]!.at < start) lastAt = ev[j++]!.at;\n const t: TurnStats = {m: 0, tl: 0, sa: 0, d: null, x: 0, g: lastAt === null ? null : round1((start - lastAt) / 1000)};\n let end: number | null = null;\n while (j < ev.length && ev[j]!.at < next) { const e = ev[j++]!; t.m++; t.tl += e.tools; t.sa += e.subs; end = e.at; lastAt = e.at; }\n if (end !== null) t.d = round1((end - start) / 1000);\n while (k < intr.length && intr[k]! < start) k++;\n if (k < intr.length && intr[k]! < next) t.x = 1;\n p.t = t;\n });\n}\n\nfunction turnWeights(human: PromptLike[], events: TurnEvent[], out: Map<PromptLike, number>): void {\n const ev = events.filter(e => e.weight > 0).sort((a, b) => a.at - b.at);\n let j = 0;\n human.forEach((p, i) => {\n const next = i + 1 < human.length ? human[i + 1]!.at! : Infinity;\n while (j < ev.length && ev[j]!.at < p.at!) j++;\n let w = 0;\n while (j < ev.length && ev[j]!.at < next) w += ev[j++]!.weight;\n out.set(p, w);\n });\n}\n\nconst round1 = (x: number) => Math.round(x * 10) / 10;\n\n/** Token-weight proxy for turn cost ranking inside one file (output dearest, cache reads cheapest). */\nexport const usageWeight = (input: number, output: number, cacheRead: number, cacheWrite: number) => input + 5 * output + 1.25 * cacheWrite + 0.1 * cacheRead;\n", "import {runScanWorker} from '../../core/src/analytics/scan-pool.js';\nrunScanWorker();\n"],
|
|
5
|
+
"mappings": ";;;;AAOA,SAAQ,QAAQ,kBAAiB;;;ACOjC,OAAO,QAAQ;AACf,SAAQ,cAAAA,mBAAiB;AACzB,OAAO,UAAU;;;ACDV,IAAM,4BACX;AAGK,IAAM,uBACX;AAEK,IAAM,oBAAuC;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,SAAS,mBAAmB,MAAuB;AACxD,SAAO,kBAAkB,KAAK,CAAC,WAAW,KAAK,SAAS,MAAM,CAAC;AACjE;;;AChCA,SAAS,kBAAkB;;;AC8H3B,IAAM,UAAU,IAAI,OAAO,sBAAsB,GAAG;;;ACnB7C,SAAS,eAAe,GAAmB;AAChD,QAAM,IAAI,EAAE;AACZ,MAAI,MAAM,EAAG,QAAO;AACpB,QAAM,SAAS,oBAAI,IAAoB;AACvC,aAAW,MAAM,EAAG,QAAO,IAAI,KAAK,OAAO,IAAI,EAAE,KAAK,KAAK,CAAC;AAC5D,MAAI,IAAI;AACR,aAAW,KAAK,OAAO,OAAO,GAAG;AAC/B,UAAM,IAAI,IAAI;AACd,SAAK,IAAI,KAAK,KAAK,CAAC;AAAA,EACtB;AACA,SAAO;AACT;AAEO,IAAM,qBAAqB;AAC3B,IAAM,oBAAoB;AAc1B,IAAM,cAAwB;AAAA;AAAA,EAEnC;AAAA;AAAA,EAEA;AACF;AAEA,IAAM,UAAU;AAChB,IAAM,SAAS;AACf,IAAM,aAAa;AAkCnB,IAAM,eACJ;AAQF,IAAM,UAAU;AAwBhB,IAAM,mBAAmB;AACzB,IAAM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