Skip to content

Commit d05d91c

Browse files
history: Retain only AIC-linked item details (#99)
Canonical snapshots should preserve the AIC evidence that is difficult for consumers to reconstruct instead of duplicating general GitHub activity. Keep full activity aggregates while making every retained item-to-run association auditable from serialized evidence. Assisted-by: AI Signed-off-by: Colin Walters <walters@verbum.org> Co-authored-by: Colin Walters <walters@verbum.org>
1 parent b8fff48 commit d05d91c

5 files changed

Lines changed: 189 additions & 20 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,11 +69,13 @@ jobs:
6969
node - "$RUNNER_TEMP/org-history.json" "$SNAPSHOT_PERIOD" <<'NODE'
7070
const assert = require('node:assert/strict');
7171
const snapshot = require(process.argv[2]);
72-
assert.equal(snapshot.schemaVersion, 4);
72+
assert.equal(snapshot.schemaVersion, 5);
7373
assert.equal(snapshot.org, 'bootc-dev');
7474
assert.equal(snapshot.period, process.argv[3]);
7575
assert.equal(snapshot.repositoryFilter, 'gh-agentic-workflows');
7676
for (const key of ['repositories', 'items', 'workflowRuns', 'commentAic', 'errors']) assert.ok(Array.isArray(snapshot[key]), `${key} is an array`);
77+
const { validateDetailedItems } = require('./scripts/org-history.js');
78+
validateDetailedItems(snapshot.items, snapshot.workflowRuns, snapshot.commentAic, snapshot.org);
7779
assert.equal(snapshot.repositories.length, 1);
7880
assert.equal(snapshot.repositories[0].name, 'gh-agentic-workflows');
7981
assert.deepEqual(Object.keys(snapshot.coverage).sort(), ['aic', 'repositories']);
@@ -106,7 +108,7 @@ jobs:
106108
const assert = require('node:assert/strict');
107109
const childProcess = require('node:child_process');
108110
const fs = require('node:fs');
109-
const { historyFilename, parsePeriod } = require('./scripts/org-history.js');
111+
const { historyFilename, parsePeriod, validateDetailedItems } = require('./scripts/org-history.js');
110112
const base = process.argv[2];
111113
const fields = childProcess.execFileSync('git', ['diff', '--name-status', '-z', base, 'HEAD'], { encoding: 'utf8' }).split('\0');
112114
const weekly = /^history\/\d{4}-\d{2}\.json$/;
@@ -120,9 +122,10 @@ jobs:
120122
if (!added || !weekly.test(added)) continue;
121123
const snapshot = JSON.parse(fs.readFileSync(added, 'utf8'));
122124
const period = added.slice('history/'.length, -'.json'.length).replace('-', '-W');
123-
assert.equal(snapshot.schemaVersion, 4, `${added} schema version`);
125+
assert.equal(snapshot.schemaVersion, 5, `${added} schema version`);
124126
assert.equal(snapshot.period, period, `${added} period`);
125127
assert.equal(historyFilename(snapshot.period), added.slice('history/'.length), `${added} filename`);
126128
parsePeriod(snapshot.period);
129+
validateDetailedItems(snapshot.items, snapshot.workflowRuns, snapshot.commentAic, snapshot.org);
127130
}
128131
NODE

‎.github/workflows/weekly-history.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,13 @@ jobs:
9595
const assert = require('node:assert/strict');
9696
const fs = require('node:fs');
9797
const snapshot = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
98-
assert.equal(snapshot.schemaVersion, 4);
98+
assert.equal(snapshot.schemaVersion, 5);
9999
assert.equal(snapshot.org, 'bootc-dev');
100100
assert.equal(snapshot.period, process.argv[3]);
101101
assert.match(snapshot.period, /^\d{4}-W\d{2}$/);
102102
for (const key of ['repositories', 'items', 'workflowRuns', 'commentAic', 'errors']) assert.ok(Array.isArray(snapshot[key]));
103+
const { validateDetailedItems } = require('./scripts/org-history.js');
104+
validateDetailedItems(snapshot.items, snapshot.workflowRuns, snapshot.commentAic, snapshot.org);
103105
NODE
104106
105107
- name: Open or update history pull request

‎scripts/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,11 @@ node scripts/org-history.js ORG 2026-09 --output /tmp/ORG-2026-09-history.json -
1616
node scripts/org-history.js --previous-iso-week
1717
```
1818

19-
Schema v4 replaces `month` with `period`, `createdInMonth`/`mergedInMonth` with
20-
`createdInPeriod`/`mergedInPeriod`, and the attribution cohort
21-
`items_created_in_month` with `items_created_in_period`.
19+
Schema v5 retains the v4 period field names and changes detailed `items`: it contains
20+
only items with exact evidence linking them to a relevant workflow run with known AIC.
21+
Each detailed item has sorted, unique `aicRunIds`. Repository aggregates still describe
22+
the full collected activity cohort, not just these AIC-linked detailed items; the linked
23+
run evidence is serialized for audit.
2224

2325
Pass `--repo REPO` to collect one non-archived, non-fork repository within `ORG` instead
2426
of the full visible organization. The resulting snapshot records the repository filter.

‎scripts/org-history.js‎

Lines changed: 100 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ const fs = require('fs');
99
const os = require('os');
1010
const path = require('path');
1111

12-
const SCHEMA_VERSION = 4;
12+
const SCHEMA_VERSION = 5;
1313
const AGENT_LABELS = ['agent/code', 'agent/fixme', 'agent/lgtm'];
1414
const AGGREGATE_USAGE_FILE = 'agent_usage.json';
1515
const TOKEN_USAGE_FILE = 'agent/token_usage.jsonl';
@@ -142,6 +142,47 @@ function aggregateRepository(items, workflows) {
142142

143143
function 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+
145186
function 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*Generated by\s+\[[^\]]+\]\((https:\/\/github\.com\/[^\s)]+\/actions\/runs\/(\d+))\)([^\r\n]*)$/gim)];
197238
const hiddenMarkers = [...body.matchAll(/<!--\s*gh-aw-agentic-workflow:\s*[^>]*?\bid:\s*(\d+)\s*,\s*workflow_id:\s*[^,\s]+\s*,\s*run:\s*(https:\/\/github\.com\/[^\s>]+\/actions\/runs\/(\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

245288
function 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+
273361
function 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
}
470558
if (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

Comments
 (0)