Skip to content

Commit 2ad2a51

Browse files
chore: sync actions from [email protected] (#176)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent ba6380c commit 2ad2a51

31 files changed

Lines changed: 1036 additions & 167 deletions

‎setup/clean.sh‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,3 +40,21 @@ if [ -d "${tmpDir}" ]; then
4040
echo "Warning: failed to clean up ${tmpDir}" >&2
4141
fi
4242
fi
43+
44+
# Remove AWF chroot home directories under /tmp (e.g. /tmp/awf-*-chroot-home).
45+
# These are created by AWF when running with --enable-host-access on GitHub-hosted runners.
46+
# Files inside may be owned by root (written by Docker containers or privileged AWF processes),
47+
# causing EACCES failures if cleanup is attempted without sudo.
48+
if awf_chroot_home_dirs="$(sudo find /tmp -maxdepth 1 -name 'awf-*-chroot-home' -type d -print 2>/dev/null)"; then
49+
if [ -n "${awf_chroot_home_dirs}" ]; then
50+
if sudo find /tmp -maxdepth 1 -name 'awf-*-chroot-home' -type d -exec rm -rf -- {} + 2>/dev/null; then
51+
echo "Cleaned up /tmp/awf-*-chroot-home directories (sudo)"
52+
else
53+
echo "Warning: failed to clean /tmp/awf-*-chroot-home directories" >&2
54+
fi
55+
else
56+
echo "No /tmp/awf-*-chroot-home directories found"
57+
fi
58+
else
59+
echo "Warning: unable to inspect /tmp/awf-*-chroot-home directories with sudo" >&2
60+
fi

‎setup/js/add_workflow_run_comment.cjs‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,18 @@ function reportCommentError(rawContext, message) {
171171
core.setFailed(message);
172172
}
173173

174+
/**
175+
* @param {Record<string, any>|null} awContext
176+
* @param {string} key
177+
* @returns {string}
178+
*/
179+
function readAwContextString(awContext, key) {
180+
if (!awContext || typeof awContext[key] !== "string") {
181+
return "";
182+
}
183+
return awContext[key].trim();
184+
}
185+
174186
/**
175187
* @param {ReusableStatusComment} reusableComment
176188
* @param {{
@@ -184,8 +196,11 @@ function reportCommentError(rawContext, message) {
184196
* @returns {Promise<string>}
185197
*/
186198
async function updateReusableStatusComment(reusableComment, invocationContext, rawContext) {
187-
const runUrl = buildWorkflowRunUrl(rawContext, invocationContext.workflowRepo);
188-
const commentBody = buildCommentBody(invocationContext.eventName, runUrl);
199+
const awContext = extractAwContextFromPayload(rawContext?.payload);
200+
const dispatchedRunUrl = readAwContextString(awContext, "dispatched_run_url");
201+
const dispatchedWorkflowName = readAwContextString(awContext, "dispatched_workflow_name");
202+
const runUrl = dispatchedRunUrl || buildWorkflowRunUrl(rawContext, invocationContext.workflowRepo);
203+
const commentBody = buildCommentBody(invocationContext.eventName, runUrl, dispatchedWorkflowName || undefined);
189204

190205
// Discussion comments use GraphQL node IDs and a dedicated update mutation.
191206
if (reusableComment.id.startsWith("DC_")) {
@@ -337,10 +352,13 @@ async function main() {
337352
* Sanitizes the content and appends all required markers.
338353
* @param {string} eventName - The event type
339354
* @param {string} runUrl - The URL of the workflow run
355+
* @param {string} [workflowNameOverride] - Optional dispatched workflow name override
340356
* @returns {string} The assembled comment body
341357
*/
342-
function buildCommentBody(eventName, runUrl) {
343-
const workflowName = process.env.GH_AW_WORKFLOW_NAME || process.env.GITHUB_WORKFLOW || "Workflow";
358+
function buildCommentBody(eventName, runUrl, workflowNameOverride) {
359+
// Whitespace-only overrides are treated as absent and fall back to env defaults.
360+
const normalizedWorkflowNameOverride = workflowNameOverride?.trim();
361+
const workflowName = normalizedWorkflowNameOverride || process.env.GH_AW_WORKFLOW_NAME || process.env.GITHUB_WORKFLOW || "Workflow";
344362
const eventTypeDescription = EVENT_TYPE_DESCRIPTIONS[eventName] ?? "event";
345363

346364
// Sanitize before adding markers (defense in depth for custom message templates)

‎setup/js/ai_credits_context.cjs‎

Lines changed: 20 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -235,10 +235,7 @@ function parseMaxAICreditsExceededFromAuditEntry(entry) {
235235
if (key === "reason") reason = value;
236236
if (key === "forced_termination") forcedTermination = value;
237237
}
238-
if (typeof event === "string" && event === BUDGET_EXCEEDED_EVENT && typeof reason === "string" && reason === "hard_limit" && isTrueLike(forcedTermination)) {
239-
return true;
240-
}
241-
return false;
238+
return typeof event === "string" && event === BUDGET_EXCEEDED_EVENT && typeof reason === "string" && reason === "hard_limit" && isTrueLike(forcedTermination);
242239
}
243240

244241
/**
@@ -315,6 +312,23 @@ function parseAuditLogCombined(auditJsonlPathOverride) {
315312
});
316313
}
317314

315+
/**
316+
* Logs the provenance source and value for a single AI credits field.
317+
* Outputs exactly one line regardless of which source resolved the value.
318+
*
319+
* @param {string} label
320+
* @param {string} auditValue
321+
* @param {string} stdioValue
322+
* @param {string} envValue
323+
* @param {string} envVarName
324+
*/
325+
function logAICreditSource(label, auditValue, stdioValue, envValue, envVarName) {
326+
if (auditValue) console.log(`[ai-credits] ${label} source=audit_log value=${auditValue}`);
327+
else if (stdioValue) console.log(`[ai-credits] ${label} source=agent_stdio value=${stdioValue}`);
328+
else if (envValue) console.log(`[ai-credits] ${label} source=env(${envVarName}) value=${envValue}`);
329+
else console.log(`[ai-credits] ${label} source=none ${envVarName}=${process.env[envVarName] || "(unset)"}`);
330+
}
331+
318332
/**
319333
* @param {{ logProvenance?: boolean }} [options]
320334
* @returns {{ aiCredits: string, maxAICredits: string, aiCreditsRateLimitError: boolean, maxAICreditsExceeded: boolean }}
@@ -329,25 +343,8 @@ function resolveAICreditsFailureState({ logProvenance = true } = {}) {
329343

330344
// Log provenance so failing issues can be diagnosed when credit data is missing.
331345
if (logProvenance) {
332-
if (auditAICredits) {
333-
console.log(`[ai-credits] aiCredits source=audit_log value=${auditAICredits}`);
334-
} else if (stdioSignals.aiCredits) {
335-
console.log(`[ai-credits] aiCredits source=agent_stdio value=${stdioSignals.aiCredits}`);
336-
} else if (envAICredits) {
337-
console.log(`[ai-credits] aiCredits source=env(GH_AW_AIC) value=${envAICredits}`);
338-
} else {
339-
console.log(`[ai-credits] aiCredits source=none GH_AW_AIC=${process.env.GH_AW_AIC || "(unset)"}`);
340-
}
341-
342-
if (auditMaxAICredits) {
343-
console.log(`[ai-credits] maxAICredits source=audit_log value=${auditMaxAICredits}`);
344-
} else if (stdioSignals.maxAICredits) {
345-
console.log(`[ai-credits] maxAICredits source=agent_stdio value=${stdioSignals.maxAICredits}`);
346-
} else if (envMaxAICredits) {
347-
console.log(`[ai-credits] maxAICredits source=env(GH_AW_MAX_AI_CREDITS) value=${envMaxAICredits}`);
348-
} else {
349-
console.log(`[ai-credits] maxAICredits source=none GH_AW_MAX_AI_CREDITS=${process.env.GH_AW_MAX_AI_CREDITS || "(unset)"}`);
350-
}
346+
logAICreditSource("aiCredits", auditAICredits, stdioSignals.aiCredits, envAICredits, "GH_AW_AIC");
347+
logAICreditSource("maxAICredits", auditMaxAICredits, stdioSignals.maxAICredits, envMaxAICredits, "GH_AW_MAX_AI_CREDITS");
351348

352349
const rawRateLimitSignalSource = auditRateLimitError
353350
? "audit_log"

‎setup/js/apply_samples.cjs‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -223,10 +223,19 @@ async function derivePrHeadRef(entry) {
223223
return directRef.trim();
224224
}
225225

226-
// Determine the target repo for any API lookups. Prefer the entry's repo if
227-
// the sample sets one (cross-repo workflows), otherwise fall back to
228-
// GITHUB_REPOSITORY.
229-
const repoSlug = (typeof entry.arguments.repo === "string" && entry.arguments.repo.trim()) || process.env.GITHUB_REPOSITORY || "";
226+
// Determine the target repo for any API lookups.
227+
// Resolution order:
228+
// a. entry.arguments.repo — explicit per-sample override (cross-repo workflows).
229+
// b. target-repo from the safe-outputs config file (GH_AW_SAFE_OUTPUTS_CONFIG_PATH)
230+
// for the tool — covers siderepo workflow_dispatch where the sample arguments
231+
// carry `pull_request_number` but not a `repo` override (issue #41292).
232+
// c. GITHUB_REPOSITORY — host repo fallback.
233+
let repoSlug = "";
234+
if (typeof entry.arguments.repo === "string" && entry.arguments.repo.trim()) {
235+
repoSlug = entry.arguments.repo.trim();
236+
} else {
237+
repoSlug = readConfiguredTargetRepo(entry.tool) || process.env.GITHUB_REPOSITORY || "";
238+
}
230239
const [owner, repo] = repoSlug.split("/");
231240
if (!owner || !repo) return null;
232241

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import { afterEach, describe, expect, it } from "vitest";
2+
import fs from "fs";
3+
import os from "os";
4+
import path from "path";
5+
import { spawnSync } from "child_process";
6+
import { fileURLToPath } from "url";
7+
8+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
9+
const POST_SCRIPT_PATH = path.join(__dirname, "..", "post.js");
10+
const CLEAN_SCRIPT_PATH = path.join(__dirname, "..", "clean.sh");
11+
12+
const tempDirs = [];
13+
14+
function createTempDir(prefix) {
15+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
16+
tempDirs.push(dir);
17+
return dir;
18+
}
19+
20+
function createFakeSudoEnvironment() {
21+
const root = createTempDir("chroot-home-cleanup-");
22+
const fakeBin = path.join(root, "fake-bin");
23+
fs.mkdirSync(fakeBin, { recursive: true });
24+
25+
const logPath = path.join(root, "sudo.log");
26+
const fakeSudoPath = path.join(fakeBin, "sudo");
27+
fs.writeFileSync(
28+
fakeSudoPath,
29+
`#!/usr/bin/env bash
30+
set -euo pipefail
31+
echo "$*" >> "$FAKE_SUDO_LOG"
32+
if [ "$1" = "find" ]; then
33+
if printf '%s\\n' "$*" | grep -q -- '-print'; then
34+
printf '%b' "\${FAKE_FIND_PRINT_OUTPUT:-}"
35+
exit "\${FAKE_FIND_PRINT_STATUS:-0}"
36+
fi
37+
if printf '%s\\n' "$*" | grep -q -- '-exec'; then
38+
exit "\${FAKE_FIND_EXEC_STATUS:-0}"
39+
fi
40+
fi
41+
exit 0
42+
`,
43+
{ mode: 0o755 }
44+
);
45+
46+
return {
47+
fakeBin,
48+
logPath,
49+
root,
50+
};
51+
}
52+
53+
function runPostScript(env) {
54+
return spawnSync(process.execPath, [POST_SCRIPT_PATH], {
55+
encoding: "utf8",
56+
env: { ...process.env, ...env },
57+
});
58+
}
59+
60+
function runCleanScript(env) {
61+
return spawnSync("bash", [CLEAN_SCRIPT_PATH], {
62+
encoding: "utf8",
63+
env: { ...process.env, ...env },
64+
});
65+
}
66+
67+
afterEach(() => {
68+
while (tempDirs.length > 0) {
69+
const dir = tempDirs.pop();
70+
if (dir && fs.existsSync(dir)) {
71+
fs.rmSync(dir, { recursive: true, force: true });
72+
}
73+
}
74+
});
75+
76+
describe("post.js chroot-home cleanup", () => {
77+
it("logs that no directories were found when find output is empty", () => {
78+
const { fakeBin, logPath } = createFakeSudoEnvironment();
79+
const result = runPostScript({
80+
PATH: `${fakeBin}:${process.env.PATH}`,
81+
FAKE_SUDO_LOG: logPath,
82+
FAKE_FIND_PRINT_OUTPUT: "",
83+
});
84+
85+
expect(result.status).toBe(0);
86+
expect(result.stdout).toContain("No /tmp/awf-*-chroot-home directories found");
87+
expect(fs.readFileSync(logPath, "utf8")).not.toContain("-exec rm -rf -- {} +");
88+
});
89+
90+
it("logs count of cleaned chroot-home directories", () => {
91+
const { fakeBin, logPath } = createFakeSudoEnvironment();
92+
const result = runPostScript({
93+
PATH: `${fakeBin}:${process.env.PATH}`,
94+
FAKE_SUDO_LOG: logPath,
95+
FAKE_FIND_PRINT_OUTPUT: "/tmp/awf-1-chroot-home\n/tmp/awf-2-chroot-home\n",
96+
});
97+
98+
expect(result.status).toBe(0);
99+
expect(result.stdout).toContain("Cleaned up 2 /tmp/awf-*-chroot-home directories");
100+
expect(fs.readFileSync(logPath, "utf8")).toContain("-exec rm -rf -- {} +");
101+
});
102+
});
103+
104+
describe("clean.sh chroot-home cleanup", () => {
105+
it("logs when no chroot-home directories are found", () => {
106+
const { fakeBin, logPath, root } = createFakeSudoEnvironment();
107+
const destination = path.join(root, "destination");
108+
fs.mkdirSync(destination, { recursive: true });
109+
110+
const result = runCleanScript({
111+
PATH: `${fakeBin}:${process.env.PATH}`,
112+
FAKE_SUDO_LOG: logPath,
113+
FAKE_FIND_PRINT_OUTPUT: "",
114+
INPUT_DESTINATION: destination,
115+
});
116+
117+
expect(result.status).toBe(0);
118+
expect(result.stdout).toContain("No /tmp/awf-*-chroot-home directories found");
119+
expect(fs.readFileSync(logPath, "utf8")).not.toContain("-exec rm -rf -- {} +");
120+
});
121+
122+
it("logs successful cleanup when chroot-home directories are found", () => {
123+
const { fakeBin, logPath, root } = createFakeSudoEnvironment();
124+
const destination = path.join(root, "destination");
125+
fs.mkdirSync(destination, { recursive: true });
126+
127+
const result = runCleanScript({
128+
PATH: `${fakeBin}:${process.env.PATH}`,
129+
FAKE_SUDO_LOG: logPath,
130+
FAKE_FIND_PRINT_OUTPUT: "/tmp/awf-1-chroot-home\n",
131+
INPUT_DESTINATION: destination,
132+
});
133+
134+
expect(result.status).toBe(0);
135+
expect(result.stdout).toContain("Cleaned up /tmp/awf-*-chroot-home directories (sudo)");
136+
expect(fs.readFileSync(logPath, "utf8")).toContain("-exec rm -rf -- {} +");
137+
});
138+
});

0 commit comments

Comments
 (0)