Skip to content

Commit 3ea13c0

Browse files
chore: sync actions from [email protected] (#128)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 4c7307f commit 3ea13c0

6 files changed

Lines changed: 249 additions & 5 deletions

‎setup/js/check_daily_effective_workflow_guardrail.cjs‎

Lines changed: 116 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,35 @@ async function getArtifactClient() {
2626
return new DefaultArtifactClient();
2727
}
2828

29+
/**
30+
* @param {string} message
31+
* @param {Record<string, unknown>} [details]
32+
* @returns {string}
33+
*/
34+
function formatDailyGuardrailLogMessage(message, details) {
35+
if (!details || Object.keys(details).length === 0) {
36+
return `[daily-workflow-et] ${message}`;
37+
}
38+
let serializedDetails = "";
39+
try {
40+
serializedDetails = JSON.stringify(details);
41+
} catch {
42+
serializedDetails = JSON.stringify({ error: "failed to serialize log details" });
43+
}
44+
return `[daily-workflow-et] ${message}: ${serializedDetails}`;
45+
}
46+
47+
/**
48+
* Emit a consistently prefixed daily workflow ET diagnostic log line.
49+
*
50+
* @param {string} message
51+
* @param {Record<string, unknown>} [details]
52+
* @returns {void}
53+
*/
54+
function logDailyGuardrail(message, details) {
55+
core.info(formatDailyGuardrailLogMessage(message, details));
56+
}
57+
2958
/**
3059
* @returns {boolean}
3160
*/
@@ -66,12 +95,34 @@ async function getRunEffectiveTokens(artifactClient, runId, token, owner, repo)
6695
repositoryName: repo,
6796
},
6897
});
98+
const artifactSummaries = artifacts.map(item => ({ id: item?.id ?? null, name: item?.name || "" }));
99+
logDailyGuardrail("Listed workflow artifacts", {
100+
runId,
101+
artifactCount: artifacts.length,
102+
artifacts: artifactSummaries,
103+
});
69104

70-
const artifact = artifacts.find(item => matchesGuardrailArtifactName(item.name));
105+
const artifact = artifacts.find(item => item?.name && matchesGuardrailArtifactName(item.name));
71106
if (!artifact) {
107+
logDailyGuardrail("No matching guardrail artifact found", {
108+
runId,
109+
availableArtifacts: artifactSummaries,
110+
});
111+
return 0;
112+
}
113+
if (!artifact.id) {
114+
logDailyGuardrail("Skipping guardrail artifact without an id", {
115+
runId,
116+
artifactName: artifact.name,
117+
});
72118
return 0;
73119
}
74120

121+
logDailyGuardrail("Selected guardrail artifact", {
122+
runId,
123+
artifactId: artifact.id,
124+
artifactName: artifact.name,
125+
});
75126
const downloadRoot = fs.mkdtempSync(path.join(os.tmpdir(), `gh-aw-daily-guardrail-${runId}-`));
76127
const download = await artifactClient.downloadArtifact(artifact.id, {
77128
path: downloadRoot,
@@ -84,7 +135,20 @@ async function getRunEffectiveTokens(artifactClient, runId, token, owner, repo)
84135
});
85136

86137
const tokenUsageFile = findTokenUsageFile(download.downloadPath || downloadRoot);
87-
return sumEffectiveTokensFromTokenUsageFile(tokenUsageFile);
138+
logDailyGuardrail("Downloaded guardrail artifact", {
139+
runId,
140+
artifactId: artifact.id,
141+
artifactName: artifact.name,
142+
downloadPath: download.downloadPath || downloadRoot,
143+
tokenUsageFile,
144+
});
145+
const effectiveTokens = sumEffectiveTokensFromTokenUsageFile(tokenUsageFile);
146+
logDailyGuardrail("Computed run ET from artifact", {
147+
runId,
148+
artifactId: artifact.id,
149+
effectiveTokens,
150+
});
151+
return effectiveTokens;
88152
}
89153

90154
/**
@@ -251,6 +315,17 @@ async function main() {
251315
return;
252316
}
253317

318+
logDailyGuardrail("Resolved current workflow ET guardrail context", {
319+
owner,
320+
repo,
321+
currentRunId: context.runId,
322+
workflowId: currentRun.data.workflow_id,
323+
workflowName,
324+
actorLogin,
325+
threshold,
326+
rateLimitRemaining: rateLimit.remaining,
327+
rateLimitLimit: rateLimit.limit,
328+
});
254329
const maxInspectableRuns = computeMaxInspectableRuns(rateLimit.remaining);
255330
if (maxInspectableRuns <= 0) {
256331
core.warning(`Skipping daily workflow ET guardrail because the GitHub API rate limit is too low (${rateLimit.remaining} remaining, reserve ${RATE_LIMIT_RESERVE}).`);
@@ -265,6 +340,13 @@ async function main() {
265340
let page = 1;
266341
let truncatedByRateLimit = false;
267342
while (page <= MAX_WORKFLOW_RUN_PAGES) {
343+
logDailyGuardrail("Querying completed workflow runs", {
344+
workflowId: currentRun.data.workflow_id,
345+
actorLogin,
346+
page,
347+
perPage: 100,
348+
cutoff: new Date(cutoffMs).toISOString(),
349+
});
268350
const response = await githubClient.rest.actions.listWorkflowRuns({
269351
owner,
270352
repo,
@@ -275,6 +357,11 @@ async function main() {
275357
page,
276358
});
277359
runs = response.data.workflow_runs || [];
360+
logDailyGuardrail("Received workflow runs page", {
361+
page,
362+
runCount: runs.length,
363+
runIds: runs.map(run => run?.id).filter(Boolean),
364+
});
278365
if (runs.length === 0) {
279366
break;
280367
}
@@ -297,6 +384,12 @@ async function main() {
297384
}
298385
page += 1;
299386
}
387+
logDailyGuardrail("Prepared candidate workflow runs for artifact inspection", {
388+
candidateRunsCount: candidateRuns.length,
389+
candidateRunIds: candidateRuns.map(run => run.id),
390+
maxInspectableRuns,
391+
truncatedByRateLimit,
392+
});
300393

301394
const artifactClient = await getArtifactClient();
302395
let totalEffectiveTokens = 0;
@@ -310,6 +403,11 @@ async function main() {
310403
try {
311404
const runEffectiveTokens = await getRunEffectiveTokens(artifactClient, run.id, token, owner, repo);
312405
if (runEffectiveTokens <= 0) {
406+
logDailyGuardrail("Skipping run without ET usage artifact data", {
407+
runId: run.id,
408+
currentEffectiveTokens: totalEffectiveTokens,
409+
threshold,
410+
});
313411
continue;
314412
}
315413
totalEffectiveTokens += runEffectiveTokens;
@@ -320,6 +418,13 @@ async function main() {
320418
conclusion: run.conclusion || "",
321419
effective_tokens: runEffectiveTokens,
322420
});
421+
logDailyGuardrail("Updated current ET state", {
422+
runId: run.id,
423+
runEffectiveTokens,
424+
currentEffectiveTokens: totalEffectiveTokens,
425+
threshold,
426+
countedRunIds: countedRuns.map(item => item.id),
427+
});
323428
} catch (error) {
324429
core.warning(`Failed to inspect token usage for run ${run.id}: ${getErrorMessage(error)}`);
325430
}
@@ -334,6 +439,14 @@ async function main() {
334439
inspectedRunsCount: countedRuns.length,
335440
truncatedByRateLimit,
336441
};
442+
logDailyGuardrail("Completed ET inspection window", {
443+
candidateRunsCount: summaryMeta.candidateRunsCount,
444+
inspectedRunsCount: summaryMeta.inspectedRunsCount,
445+
countedRunIds: countedRuns.map(run => run.id),
446+
currentEffectiveTokens: totalEffectiveTokens,
447+
threshold,
448+
exceeded: totalEffectiveTokens > threshold,
449+
});
337450

338451
if (totalEffectiveTokens <= threshold) {
339452
await appendDailyEffectiveWorkflowSummary(workflowName, actorLogin, threshold, countedRuns, rateLimit, summaryMeta);
@@ -355,4 +468,5 @@ module.exports = {
355468
calculateDailyEffectiveWorkflowStats,
356469
computeMaxInspectableRuns,
357470
renderDailyEffectiveWorkflowSummary,
471+
formatDailyGuardrailLogMessage,
358472
};

‎setup/js/close_expired_discussions.cjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
const { executeExpiredEntityCleanup } = require("./expired_entity_main_flow.cjs");
55
const { generateExpiredEntityFooter, getExpiredEntityCautionAlert } = require("./generate_footer.cjs");
6+
const { formatDateInProjectTimeZone } = require("./project_timezone.cjs");
67
const { sanitizeContent } = require("./sanitize_content.cjs");
78
const { getWorkflowMetadata } = require("./workflow_metadata_helpers.cjs");
89
const { resolveExecutionOwnerRepo } = require("./repo_helpers.cjs");
@@ -139,7 +140,7 @@ async function main() {
139140
}
140141

141142
const cautionAlert = getExpiredEntityCautionAlert(workflowName, runUrl);
142-
const expirationText = `This discussion was automatically closed because it expired on ${discussion.expirationDate.toISOString()}.`;
143+
const expirationText = `This discussion was automatically closed because it expired on ${formatDateInProjectTimeZone(discussion.expirationDate) || discussion.expirationDate.toISOString()}.`;
143144
const closingMessage = (cautionAlert ? cautionAlert + "\n\n" : "") + expirationText + generateExpiredEntityFooter(workflowName, runUrl, workflowId) + "\n\n<!-- gh-aw-closed -->";
144145

145146
core.info(` Adding closing comment to discussion #${discussion.number}`);

‎setup/js/close_expired_issues.cjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
const { executeExpiredEntityCleanup } = require("./expired_entity_main_flow.cjs");
55
const { generateExpiredEntityFooter, getExpiredEntityCautionAlert } = require("./generate_footer.cjs");
6+
const { formatDateInProjectTimeZone } = require("./project_timezone.cjs");
67
const { sanitizeContent } = require("./sanitize_content.cjs");
78
const { getWorkflowMetadata } = require("./workflow_metadata_helpers.cjs");
89
const { resolveExecutionOwnerRepo } = require("./repo_helpers.cjs");
@@ -62,7 +63,7 @@ async function main() {
6263
summaryHeading: "Expired Issues Cleanup",
6364
processEntity: async issue => {
6465
const cautionAlert = getExpiredEntityCautionAlert(workflowName, runUrl);
65-
const expirationText = `This issue was automatically closed because it expired on ${issue.expirationDate.toISOString()}.`;
66+
const expirationText = `This issue was automatically closed because it expired on ${formatDateInProjectTimeZone(issue.expirationDate) || issue.expirationDate.toISOString()}.`;
6667
const closingMessage = (cautionAlert ? cautionAlert + "\n\n" : "") + expirationText + generateExpiredEntityFooter(workflowName, runUrl, workflowId);
6768

6869
await addIssueComment(github, owner, repo, issue.number, closingMessage);

‎setup/js/close_expired_pull_requests.cjs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
const { executeExpiredEntityCleanup } = require("./expired_entity_main_flow.cjs");
55
const { generateExpiredEntityFooter, getExpiredEntityCautionAlert } = require("./generate_footer.cjs");
6+
const { formatDateInProjectTimeZone } = require("./project_timezone.cjs");
67
const { sanitizeContent } = require("./sanitize_content.cjs");
78
const { getWorkflowMetadata } = require("./workflow_metadata_helpers.cjs");
89
const { resolveExecutionOwnerRepo } = require("./repo_helpers.cjs");
@@ -61,7 +62,7 @@ async function main() {
6162
summaryHeading: "Expired Pull Requests Cleanup",
6263
processEntity: async pr => {
6364
const cautionAlert = getExpiredEntityCautionAlert(workflowName, runUrl);
64-
const expirationText = `This pull request was automatically closed because it expired on ${pr.expirationDate.toISOString()}.`;
65+
const expirationText = `This pull request was automatically closed because it expired on ${formatDateInProjectTimeZone(pr.expirationDate) || pr.expirationDate.toISOString()}.`;
6566
const closingMessage = (cautionAlert ? cautionAlert + "\n\n" : "") + expirationText + generateExpiredEntityFooter(workflowName, runUrl, workflowId);
6667

6768
await addPullRequestComment(github, owner, repo, pr.number, closingMessage);

‎setup/js/ephemerals.cjs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// @ts-check
22
/// <reference types="@actions/github-script" />
33

4+
const { formatDateInProjectTimeZone, resolveProjectTimeZone } = require("./project_timezone.cjs");
5+
46
/**
57
* Regex pattern to match expiration marker with checked checkbox and HTML comment (new format)
68
* Format: > - [x] expires <!-- gh-aw-expires: ISO_DATE --> on HUMAN_DATE UTC
@@ -22,6 +24,11 @@ const LEGACY_EXPIRATION_PATTERN = /^>\s*-\s*\[x\]\s+expires\s+on\s+(.+?)\s+UTC\s
2224
* @returns {string} Human-readable date string (e.g., "Jan 25, 2026, 1:53 PM")
2325
*/
2426
function formatExpirationDate(date) {
27+
const projectDate = formatDateInProjectTimeZone(date);
28+
if (projectDate) {
29+
return projectDate;
30+
}
31+
2532
return date.toLocaleString("en-US", {
2633
dateStyle: "medium",
2734
timeStyle: "short",
@@ -37,6 +44,9 @@ function formatExpirationDate(date) {
3744
function createExpirationLine(expirationDate) {
3845
const expirationISO = expirationDate.toISOString();
3946
const humanReadableDate = formatExpirationDate(expirationDate);
47+
if (resolveProjectTimeZone()) {
48+
return `- [x] expires <!-- gh-aw-expires: ${expirationISO} --> on ${humanReadableDate}`;
49+
}
4050
return `- [x] expires <!-- gh-aw-expires: ${expirationISO} --> on ${humanReadableDate} UTC`;
4151
}
4252

‎setup/js/project_timezone.cjs‎

Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
// @ts-check
2+
3+
const fs = require("fs");
4+
const path = require("path");
5+
6+
const REPO_CONFIG_PATH = [".github", "workflows", "aw.json"];
7+
8+
function normalizeUTCOffset(utcOffset) {
9+
const trimmed = typeof utcOffset === "string" ? utcOffset.trim() : "";
10+
const match = trimmed.match(/^([+-])(\d{2}):(\d{2})$/);
11+
if (!match) {
12+
return "";
13+
}
14+
15+
const [, sign, hours, minutes] = match;
16+
const hourValue = Number.parseInt(hours, 10);
17+
const minuteValue = Number.parseInt(minutes, 10);
18+
if (hourValue > 14 || minuteValue > 59 || (hourValue === 14 && minuteValue !== 0)) {
19+
return "";
20+
}
21+
22+
return `${sign}${hours}:${minutes}`;
23+
}
24+
25+
function parseUTCOffsetMinutes(utcOffset) {
26+
const normalized = normalizeUTCOffset(utcOffset);
27+
if (!normalized) {
28+
return Number.NaN;
29+
}
30+
31+
const sign = normalized.startsWith("-") ? -1 : 1;
32+
const hours = Number.parseInt(normalized.slice(1, 3), 10);
33+
const minutes = Number.parseInt(normalized.slice(4, 6), 10);
34+
return sign * (hours * 60 + minutes);
35+
}
36+
37+
function getRepoConfigPath() {
38+
return path.join(process.env.GITHUB_WORKSPACE || process.cwd(), ...REPO_CONFIG_PATH);
39+
}
40+
41+
function warn(message) {
42+
global.core?.warning?.(message);
43+
}
44+
45+
function readRepoConfigTimeZone() {
46+
const repoConfigPath = getRepoConfigPath();
47+
48+
try {
49+
const raw = fs.readFileSync(repoConfigPath, "utf8");
50+
const parsed = JSON.parse(raw);
51+
const rawUTCOffset = typeof parsed?.utc === "string" ? parsed.utc.trim() : "";
52+
if (!rawUTCOffset) {
53+
return "";
54+
}
55+
const utcOffset = normalizeUTCOffset(rawUTCOffset);
56+
if (!utcOffset) {
57+
warn(`Ignoring invalid repo UTC offset in ${repoConfigPath}: ${rawUTCOffset}`);
58+
return "";
59+
}
60+
return utcOffset;
61+
} catch (error) {
62+
if (error && typeof error === "object" && "code" in error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
63+
return "";
64+
}
65+
if (error instanceof SyntaxError) {
66+
warn(`Ignoring invalid JSON in ${repoConfigPath}: ${error.message}`);
67+
return "";
68+
}
69+
warn(`Failed to read ${repoConfigPath}: ${error instanceof Error ? error.message : String(error)}`);
70+
return "";
71+
}
72+
}
73+
74+
function readDefaultTimeZone() {
75+
const raw = process.env.GH_AW_DEFAULT_UTC || "";
76+
if (!raw.trim()) {
77+
return "";
78+
}
79+
const utcOffset = normalizeUTCOffset(raw);
80+
if (!utcOffset) {
81+
warn(`Ignoring invalid GH_AW_DEFAULT_UTC offset: ${raw.trim()}`);
82+
return "";
83+
}
84+
return utcOffset;
85+
}
86+
87+
function resolveProjectTimeZone() {
88+
return readRepoConfigTimeZone() || readDefaultTimeZone();
89+
}
90+
91+
function formatDateInProjectTimeZone(date) {
92+
const utcOffset = resolveProjectTimeZone();
93+
if (!utcOffset) {
94+
return "";
95+
}
96+
97+
const offsetMinutes = parseUTCOffsetMinutes(utcOffset);
98+
if (Number.isNaN(offsetMinutes)) {
99+
return "";
100+
}
101+
102+
const shiftedDate = new Date(date.getTime() + offsetMinutes * 60 * 1000);
103+
const formatted = new Intl.DateTimeFormat("en-US", {
104+
year: "numeric",
105+
month: "short",
106+
day: "numeric",
107+
hour: "numeric",
108+
minute: "2-digit",
109+
timeZone: "UTC",
110+
}).format(shiftedDate);
111+
return `${formatted} UTC${utcOffset}`;
112+
}
113+
114+
module.exports = {
115+
formatDateInProjectTimeZone,
116+
resolveProjectTimeZone,
117+
};

0 commit comments

Comments
 (0)