@@ -9,7 +9,7 @@ const fs = require('fs');
99const os = require ( 'os' ) ;
1010const path = require ( 'path' ) ;
1111
12- const SCHEMA_VERSION = 4 ;
12+ const SCHEMA_VERSION = 5 ;
1313const AGENT_LABELS = [ 'agent/code' , 'agent/fixme' , 'agent/lgtm' ] ;
1414const AGGREGATE_USAGE_FILE = 'agent_usage.json' ;
1515const TOKEN_USAGE_FILE = 'agent/token_usage.jsonl' ;
@@ -142,6 +142,47 @@ function aggregateRepository(items, workflows) {
142142
143143function finiteNonnegative ( value ) { return typeof value === 'number' && Number . isFinite ( value ) && value >= 0 ; }
144144
145+ function itemIdentityFromUrl ( url , org , repository ) {
146+ if ( typeof url !== 'string' ) return null ;
147+ const escapedOrg = org . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
148+ const escapedRepository = repository . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
149+ const match = new RegExp ( `^https://(?:api\\.)?github\\.com/${ url . includes ( 'api.github.com' ) ? 'repos/' : '' } ${ escapedOrg } /${ escapedRepository } /(?:issues|pulls)/(\\d+)$` ) . exec ( url ) ;
150+ if ( ! match ) return null ;
151+ const number = Number ( match [ 1 ] ) ;
152+ return Number . isSafeInteger ( number ) && number > 0 ? { number } : null ;
153+ }
154+
155+ function commentItemIdentity ( issueUrl , commentUrl , org , repository ) {
156+ const issue = itemIdentityFromUrl ( issueUrl , org , repository ) ;
157+ if ( ! issue || typeof commentUrl !== 'string' ) return null ;
158+ const escapedOrg = org . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
159+ const escapedRepository = repository . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
160+ const match = new RegExp ( `^(https://github\\.com/${ escapedOrg } /${ escapedRepository } /(issues|pull)/(\\d+))(?:#issuecomment-\\d+)?$` ) . exec ( commentUrl ) ;
161+ if ( ! match || Number ( match [ 3 ] ) !== issue . number ) return null ;
162+ return { number : issue . number , url : match [ 1 ] } ;
163+ }
164+
165+ function runUrlForRepository ( url , org , repository ) {
166+ if ( typeof url !== 'string' ) return null ;
167+ const escapedOrg = org . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
168+ const escapedRepository = repository . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
169+ const match = new RegExp ( `^https://github\\.com/${ escapedOrg } /${ escapedRepository } /actions/runs/(\\d+)$` ) . exec ( url ) ;
170+ return match && Number . isSafeInteger ( Number ( match [ 1 ] ) ) && Number ( match [ 1 ] ) > 0 ? Number ( match [ 1 ] ) : null ;
171+ }
172+
173+ function normalizedPullRequests ( run , org , repository ) {
174+ const escapedOrg = org . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
175+ const escapedRepository = repository . replace ( / [ . * + ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) ;
176+ const pattern = new RegExp ( `^https://api\\.github\\.com/repos/${ escapedOrg } /${ escapedRepository } /pulls/(\\d+)$` ) ;
177+ const references = new Map ( ) ;
178+ for ( const pullRequest of run . pull_requests || [ ] ) {
179+ const match = pattern . exec ( pullRequest . url ) ;
180+ const number = match && Number ( match [ 1 ] ) ;
181+ if ( Number . isSafeInteger ( number ) && number > 0 ) references . set ( number , { number, url : `https://github.com/${ org } /${ repository } /pull/${ number } ` } ) ;
182+ }
183+ return [ ...references . values ( ) ] . sort ( ( a , b ) => a . number - b . number ) ;
184+ }
185+
145186function cumulativeUsage ( files , filename , component ) {
146187 const selected = files . filter ( ( file ) => file . name === filename ) ;
147188 if ( ! selected . length ) return { known : false , aic : null , records : 0 , source : `${ component } _missing` } ;
@@ -191,7 +232,7 @@ function normalizeAic(value) { return Number(value.toFixed(6)); }
191232// Only read the machine-produced footer, not arbitrary discussion of AIC in a
192233// comment. The optional hidden marker is emitted by newer gh-aw versions and
193234// gives an independently labelled run identity.
194- function parseCommentAic ( comment ) {
235+ function parseCommentAic ( comment , org , repository ) {
195236 const body = typeof comment . body === 'string' ? comment . body : '' ;
196237 const footers = [ ...body . matchAll ( / ^ > \s * G e n e r a t e d b y \s + \[ [ ^ \] ] + \] \( ( h t t p s : \/ \/ g i t h u b \. c o m \/ [ ^ \s ) ] + \/ a c t i o n s \/ r u n s \/ ( \d + ) ) \) ( [ ^ \r \n ] * ) $ / gim) ] ;
197238 const hiddenMarkers = [ ...body . matchAll ( / < ! - - \s * g h - a w - a g e n t i c - w o r k f l o w : \s * [ ^ > ] * ?\b i d : \s * ( \d + ) \s * , \s * w o r k f l o w _ i d : \s * [ ^ , \s ] + \s * , \s * r u n : \s * ( h t t p s : \/ \/ g i t h u b \. c o m \/ [ ^ \s > ] + \/ a c t i o n s \/ r u n s \/ ( \d + ) ) \s * - - > / gi) ] ;
@@ -210,12 +251,14 @@ function parseCommentAic(comment) {
210251 const expandAic = ( token ) => Number ( token [ 2 ] ) * ( token [ 3 ] === 'K' ? 1_000 : token [ 3 ] === 'M' ? 1_000_000 : 1 ) ;
211252 const agentAic = expandAic ( agent [ 0 ] ) ;
212253 const detectionAic = detection . length ? expandAic ( detection [ 0 ] ) : null ;
213- if ( ! Number . isSafeInteger ( Number ( footerRunId ) ) || Number ( footerRunId ) <= 0 || ! Number . isSafeInteger ( comment . id ) || comment . id <= 0 || ! finiteNonnegative ( agentAic ) || ( detectionAic !== null && ! finiteNonnegative ( detectionAic ) ) ) return null ;
254+ const item = commentItemIdentity ( comment . issue_url , comment . html_url , org , repository ) ;
255+ if ( ! Number . isSafeInteger ( Number ( footerRunId ) ) || Number ( footerRunId ) <= 0 || runUrlForRepository ( footer [ 1 ] , org , repository ) !== Number ( footerRunId ) || ( hidden && runUrlForRepository ( hidden [ 2 ] , org , repository ) !== Number ( hiddenRunId ) ) || ! Number . isSafeInteger ( comment . id ) || comment . id <= 0 || ! item || ! finiteNonnegative ( agentAic ) || ( detectionAic !== null && ! finiteNonnegative ( detectionAic ) ) ) return null ;
214256 return {
215257 runId : Number ( footerRunId ) , agentAic : normalizeAic ( agentAic ) , detectionAic : detectionAic === null ? null : normalizeAic ( detectionAic ) ,
216258 aic : normalizeAic ( agentAic + ( detectionAic === null ? 0 : detectionAic ) ) ,
217259 actor : comment . user && comment . user . login || null , createdAt : comment . created_at || null , updatedAt : comment . updated_at || null ,
218260 footerRunUrl : footer [ 1 ] , commentUrl : comment . html_url || comment . url || null , commentId : comment . id ,
261+ itemNumber : item . number , itemUrl : item . url ,
219262 bodySha256 : crypto . createHash ( 'sha256' ) . update ( body ) . digest ( 'hex' ) ,
220263 } ;
221264}
@@ -237,13 +280,14 @@ function deduplicateCommentAic(records) {
237280 const first = ordered [ 0 ] ;
238281 if ( ordered . some ( ( record ) => record . agentAic !== first . agentAic || record . detectionAic !== first . detectionAic || record . aic !== first . aic ) ) {
239282 errors . push ( { runId, message : 'conflicting comment AIC records' } ) ;
240- } else accepted . push ( first ) ;
283+ } else accepted . push ( ... ordered ) ;
241284 }
242285 return { records : accepted , errors } ;
243286}
244287
245288function applyCommentAicFallback ( runs , records ) {
246- const byRun = new Map ( records . map ( ( record ) => [ record . runId , record ] ) ) ;
289+ const byRun = new Map ( ) ;
290+ for ( const record of records ) if ( ! byRun . has ( record . runId ) ) byRun . set ( record . runId , record ) ;
247291 let commentBackedRuns = 0 ;
248292 for ( const run of runs ) {
249293 const record = byRun . get ( run . id ) ;
@@ -258,9 +302,9 @@ function applyCommentAicFallback(runs, records) {
258302 return commentBackedRuns ;
259303}
260304
261- function integrateCommentAic ( comments , bot , interval , relevantRuns ) {
305+ function integrateCommentAic ( comments , bot , interval , relevantRuns , org , repository ) {
262306 const eligibleById = new Map ( relevantRuns . filter ( aicEligible ) . map ( ( run ) => [ run . id , run ] ) ) ;
263- const parsed = botCommentsInInterval ( comments , bot , interval ) . map ( parseCommentAic )
307+ const parsed = botCommentsInInterval ( comments , bot , interval ) . map ( ( comment ) => parseCommentAic ( comment , org , repository ) )
264308 . filter ( ( record ) => record && eligibleById . has ( record . runId ) ) ;
265309 const usage = deduplicateCommentAic ( parsed ) ;
266310 return {
@@ -270,6 +314,50 @@ function integrateCommentAic(comments, bot, interval, relevantRuns) {
270314 } ;
271315}
272316
317+ function aicLinkedItems ( items , runs , commentAic , org ) {
318+ const itemsByKey = new Map ( items . map ( ( item ) => [ `${ item . repository } /${ item . number } ` , item ] ) ) ;
319+ const runById = new Map ( runs . filter ( ( run ) => ( run . kind || classifyWorkflow ( run ) ) && finiteNonnegative ( run . aic ) ) . map ( ( run ) => [ run . id , run ] ) ) ;
320+ const links = new Map ( ) ;
321+ const link = ( repository , number , runId ) => {
322+ const item = itemsByKey . get ( `${ repository } /${ number } ` ) ;
323+ const run = runById . get ( runId ) ;
324+ if ( ! item || ! run || run . repository !== repository ) return ;
325+ const ids = links . get ( item ) || new Set ( ) ;
326+ ids . add ( runId ) ;
327+ links . set ( item , ids ) ;
328+ } ;
329+ for ( const evidence of commentAic ) link ( evidence . repository , evidence . itemNumber , evidence . runId ) ;
330+ for ( const run of runById . values ( ) ) {
331+ for ( const pullRequest of normalizedPullRequests ( run , org , run . repository ) ) {
332+ const candidate = itemsByKey . get ( `${ run . repository } /${ pullRequest . number } ` ) ;
333+ if ( candidate && candidate . type === 'pull_request' && candidate . url === pullRequest . url ) {
334+ link ( run . repository , pullRequest . number , run . id ) ;
335+ }
336+ }
337+ }
338+ return [ ...links . entries ( ) ] . map ( ( [ item , runIds ] ) => ( { ...item , aicRunIds : [ ...runIds ] . sort ( ( a , b ) => a - b ) } ) )
339+ . sort ( ( a , b ) => a . repository . localeCompare ( b . repository ) || a . number - b . number ) ;
340+ }
341+
342+ function validateDetailedItems ( items , workflowRuns , commentAic , org ) {
343+ const runById = new Map ( workflowRuns . map ( ( run ) => [ run . id , run ] ) ) ;
344+ for ( const item of items ) {
345+ if ( ! Array . isArray ( item . aicRunIds ) || ! item . aicRunIds . length ) throw new Error ( `Detailed item ${ item . repository } #${ item . number } has no AIC runs` ) ;
346+ const itemPath = item . type === 'pull_request' ? 'pull' : item . type === 'issue' ? 'issues' : null ;
347+ const canonicalItemUrl = itemPath && `https://github.com/${ org } /${ item . repository } /${ itemPath } /${ item . number } ` ;
348+ if ( item . url !== canonicalItemUrl ) throw new Error ( `Detailed item ${ item . repository } #${ item . number } has a mismatched canonical URL` ) ;
349+ const sortedUnique = [ ...new Set ( item . aicRunIds ) ] . sort ( ( a , b ) => a - b ) ;
350+ if ( JSON . stringify ( item . aicRunIds ) !== JSON . stringify ( sortedUnique ) ) throw new Error ( `Detailed item ${ item . repository } #${ item . number } has unsorted or duplicate AIC runs` ) ;
351+ for ( const runId of item . aicRunIds ) {
352+ const run = runById . get ( runId ) ;
353+ if ( ! run || run . repository !== item . repository || ! finiteNonnegative ( run . aic ) ) throw new Error ( `Detailed item ${ item . repository } #${ item . number } references unknown-AIC run ${ runId } ` ) ;
354+ const commentEvidence = ( commentAic || [ ] ) . some ( ( record ) => record . repository === item . repository && record . runId === runId && record . itemNumber === item . number && record . itemUrl === item . url ) ;
355+ const pullRequestEvidence = item . type === 'pull_request' && ( run . pullRequests || [ ] ) . some ( ( reference ) => reference . number === item . number && reference . url === item . url ) ;
356+ if ( ! commentEvidence && ! pullRequestEvidence ) throw new Error ( `Detailed item ${ item . repository } #${ item . number } lacks exact evidence for run ${ runId } ` ) ;
357+ }
358+ }
359+ }
360+
273361function summarizeAicCoverage ( runs ) {
274362 const coverage = { relevantRuns : runs . length , eligibleRuns : 0 , ineligibleRuns : 0 , runsWithValues : 0 , artifactBackedRuns : 0 , commentBackedRuns : 0 , missingOrExpired : 0 , total : null } ;
275363 for ( const run of runs ) {
@@ -400,7 +488,7 @@ function collect(org, interval, bot, repositoryFilter) {
400488 const pull = prByNumber . get ( item . number ) ;
401489 return pull ? { ...item , ...pull , pull_request : item . pull_request } : item ;
402490 } ) , name , interval ) . filter ( ( item ) => inInterval ( item . updatedAt , interval ) || item . createdInPeriod || item . mergedInPeriod ) ;
403- const runs = fetchWorkflowRuns ( org , name , interval ) . filter ( ( run ) => inInterval ( run . created_at , interval ) ) ;
491+ const runs = fetchWorkflowRuns ( org , name , interval ) . filter ( ( run ) => inInterval ( run . created_at , interval ) ) . map ( ( run ) => ( { ... run , repository : name } ) ) ;
404492 const relevant = runs . filter ( classifyWorkflow ) ;
405493 for ( const run of relevant ) {
406494 if ( ! aicEligible ( run ) ) continue ;
@@ -409,14 +497,14 @@ function collect(org, interval, bot, repositoryFilter) {
409497 }
410498 if ( bot ) {
411499 try {
412- const commentUsage = integrateCommentAic ( paged ( `repos/${ org } /${ name } /issues/comments?since=${ encodeURIComponent ( issueSince ( interval ) ) } &per_page=100` ) , bot , interval , relevant ) ;
500+ const commentUsage = integrateCommentAic ( paged ( `repos/${ org } /${ name } /issues/comments?since=${ encodeURIComponent ( issueSince ( interval ) ) } &per_page=100` ) , bot , interval , relevant , org , name ) ;
413501 for ( const error of commentUsage . errors ) repositoryErrors . push ( { repository : name , operation : `comment/${ error . runId } ` , message : error . message } ) ;
414502 snapshot . commentAic . push ( ...commentUsage . evidence . map ( ( record ) => ( { repository : name , ...record } ) ) ) ;
415503 } catch ( error ) { repositoryErrors . push ( { repository : name , operation : 'comments' , message : error . message } ) ; }
416504 }
417505 repositoryAic = summarizeAicCoverage ( relevant ) ;
418- const workflowRuns = runs . map ( ( run ) => ( { repository : name , id : run . id , url : run . html_url , name : run . name , path : run . path , createdAt : run . created_at , conclusion : run . conclusion , kind : classifyWorkflow ( run ) , aic : run . aic === undefined ? null : run . aic , aicSource : run . aicSource || null , aicRecords : run . aicRecords === undefined ? null : run . aicRecords , aicAgent : run . aicAgent === undefined ? null : run . aicAgent , aicDetection : run . aicDetection === undefined ? null : run . aicDetection , aicCommentActor : run . aicCommentActor || null , aicCommentCreatedAt : run . aicCommentCreatedAt || null , aicCommentUpdatedAt : run . aicCommentUpdatedAt || null , aicFooterRunUrl : run . aicFooterRunUrl || null , aicCommentUrl : run . aicCommentUrl || null , aicCommentId : run . aicCommentId === undefined ? null : run . aicCommentId , aicCommentBodySha256 : run . aicCommentBodySha256 || null } ) ) . filter ( ( run ) => run . kind ) ;
419- snapshot . items . push ( ...items ) ;
506+ const workflowRuns = runs . map ( ( run ) => ( { repository : name , id : run . id , url : run . html_url , name : run . name , path : run . path , createdAt : run . created_at , conclusion : run . conclusion , kind : classifyWorkflow ( run ) , pullRequests : normalizedPullRequests ( run , org , name ) , aic : run . aic === undefined ? null : run . aic , aicSource : run . aicSource || null , aicRecords : run . aicRecords === undefined ? null : run . aicRecords , aicAgent : run . aicAgent === undefined ? null : run . aicAgent , aicDetection : run . aicDetection === undefined ? null : run . aicDetection , aicCommentActor : run . aicCommentActor || null , aicCommentCreatedAt : run . aicCommentCreatedAt || null , aicCommentUpdatedAt : run . aicCommentUpdatedAt || null , aicFooterRunUrl : run . aicFooterRunUrl || null , aicCommentUrl : run . aicCommentUrl || null , aicCommentId : run . aicCommentId === undefined ? null : run . aicCommentId , aicCommentBodySha256 : run . aicCommentBodySha256 || null } ) ) . filter ( ( run ) => run . kind ) ;
507+ snapshot . items . push ( ...aicLinkedItems ( items , runs , snapshot . commentAic . filter ( ( record ) => record . repository === name ) , org ) ) ;
420508 snapshot . workflowRuns . push ( ...workflowRuns ) ;
421509 snapshot . repositories . push ( { name, url : repo . html_url , ...aggregateRepository ( items , runs ) } ) ;
422510 snapshot . errors . push ( ...repositoryErrors ) ;
@@ -469,4 +557,4 @@ function main(argv) {
469557}
470558if ( require . main === module ) { try { main ( process . argv . slice ( 2 ) ) ; } catch ( error ) { console . error ( `org-history: ${ error . message } ` ) ; process . exitCode = 1 ; } }
471559
472- module . exports = { parsePeriod, previousCompleteIsoWeek, historyFilename } ;
560+ module . exports = { aicLinkedItems , deduplicateCommentAic , historyFilename , normalizedPullRequests , parseCommentAic , parsePeriod, previousCompleteIsoWeek, validateDetailedItems } ;
0 commit comments