Skip to content

Commit 63197d7

Browse files
authored
fix(skills): mktemp templates with a non-trailing X suffix break on macOS (#2343)
* fix(skills): mktemp templates with a non-trailing X suffix break on macOS (#2157) BSD mktemp (macOS) only randomizes a TRAILING run of X's — a suffix directly after it (mktemp "tmp.XXXXXXXXXX.ext") returns the template literally instead of creating a unique path. create-skill/SKILL.md mandated exactly this broken pattern in Patterns 2/3/13/14 and the Phase 5 checklist, so every generated skill following it got a fixed, non-unique temp path on macOS: concurrent sessions collided on the same literal file, and re-runs failed with "mkstemp failed ... File exists". lint-skill.sh and smoke-test-skill.sh reproduced the same broken pattern in their own mktemp calls. Fix: rewrite every mandated example to mktemp -d a trailing-X directory template, placing the extensioned file inside it when an extension is required. Add a lint-skill.sh check that flags any mktemp template whose X run is not trailing, so a future skill reintroducing this is caught automatically instead of silently shipping. docs check acknowledged. * fix(test): resolve a real bash 4+ for lint-skill.sh, verify it actually ran (#2157 CI) Two bugs in the new regression test: 1. lint-skill.sh requires bash 4+; macOS ships bash 3.2 as the `bash` on PATH (including GitHub Actions' macos-latest runner), so execFileSync('bash', ...) invoked a bash that rejects the script outright. Resolve a real bash 4+ explicitly (checking common Homebrew install paths) and skip the suite if none is found, rather than assuming plain "bash" is adequate. 2. The "does not flag ..." assertions used stdout.not.toContain(...), which passes vacuously on an EMPTY stdout — exactly what happens when the script fails to even start. This is why only the "flags ..." tests (which assert toContain, not not.toContain) surfaced the bash-version failure in CI; the others silently "passed" for the wrong reason. Every case now also asserts the script actually reached its own summary line. docs check acknowledged.
1 parent fc33049 commit 63197d7

4 files changed

Lines changed: 192 additions & 10 deletions

File tree

‎.claude/skills/create-skill/SKILL.md‎

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -181,26 +181,33 @@ git show HEAD:$FILE 2>/dev/null | codegraph where --file -
181181
**Correct:**
182182
````markdown
183183
```bash
184-
PREV_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.js") # adjust extension to match the language of $FILE; template syntax is portable (macOS + Linux)
185-
trap 'rm -f "$PREV_FILE"' EXIT
184+
# mktemp -d with a trailing-X template, then a named file with the right
185+
# extension inside it — a suffix directly after the X run (mktemp
186+
# "tmp.XXXXXXXXXX.js") returns the template literally on macOS BSD mktemp
187+
# instead of randomizing it (issue #2157); only a trailing X run is portable.
188+
PREV_DIR=$(mktemp -d "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
189+
PREV_FILE="$PREV_DIR/prev.js" # adjust extension to match the language of $FILE
190+
trap 'rm -rf "$PREV_DIR"' EXIT
186191
# $FILE is expected to be set by the surrounding loop, e.g. for FILE in $(git diff --name-only HEAD); do ... done
187192
# 2>/dev/null: suppress git's "fatal: Path X does not exist in HEAD" — the else branch already warns the user
188193
if git show HEAD:"$FILE" > "$PREV_FILE" 2>/dev/null; then
189194
codegraph where --file "$PREV_FILE"
190195
else
191196
echo "WARN: $FILE is new or unreadable in HEAD — skipping before/after comparison"
192197
fi
193-
rm -f "$PREV_FILE"
198+
rm -rf "$PREV_DIR"
194199
trap - EXIT
195200
```
196201
````
197202

198203
### Pattern 3: Temp files need extensions
199204

200-
Codegraph's language detection is extension-based. Temp files passed to codegraph must have the correct extension:
205+
Codegraph's language detection is extension-based. Temp files passed to codegraph must have the correct extension — but `mktemp`'s own template can only end in a trailing `X` run (a suffix directly after the X's, like `tmp.XXXXXXXXXX.js`, returns the template literally instead of randomizing it on macOS BSD `mktemp` — issue #2157). Create a temp directory instead and place the named, extensioned file inside it:
201206

202207
```bash
203-
mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.js" # NOT just mktemp — template syntax is cross-platform (macOS + Linux)
208+
TMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX") # NOT just mktemp — template syntax is cross-platform (macOS + Linux)
209+
trap 'rm -rf "$TMP_DIR"' EXIT
210+
TMP_FILE="$TMP_DIR/probe.js" # extension lives on the file name, not the mktemp template
204211
```
205212

206213
### Pattern 4: No hardcoded temp paths
@@ -281,7 +288,7 @@ This supports both idempotent re-runs and resume-after-failure.
281288

282289
Avoid shell constructs that behave differently across platforms:
283290
- Use `find ... -name "*.ext" | grep -q .` instead of `find ... -quit` (non-portable) or glob expansion (`ls *.ext`) which differs between bash versions
284-
- Use `mktemp` with template syntax (`mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.ext"`) — GNU flags like `--suffix` and `-p` are not available on macOS BSD `mktemp`
291+
- Use `mktemp` with template syntax (`mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX"`) — GNU flags like `--suffix` and `-p` are not available on macOS BSD `mktemp`. The `X` run must be **trailing** — a suffix directly after it (`tmp.XXXXXXXXXX.ext`) returns the template literally instead of randomizing it on macOS BSD `mktemp` (issue #2157); when an extension is required (Pattern 3), `mktemp -d` a directory and place the named file inside it instead
285292
- Use `sed -i.bak` instead of `sed -i ''` (GNU vs BSD incompatibility)
286293
- Document any platform-specific behavior with a comment: `# NOTE: requires GNU coreutils`
287294

@@ -290,7 +297,7 @@ Avoid shell constructs that behave differently across platforms:
290297
Any phase that creates temp files or modifies repo state must set a cleanup trap. Without it, errors mid-phase leak temp files or leave dirty state:
291298

292299
```bash
293-
TMPFILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.json")
300+
TMPFILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
294301
trap 'rm -f "$TMPFILE"' EXIT
295302
# ... operations that might fail ...
296303
# Reset when done if more work follows:
@@ -556,7 +563,7 @@ trap - EXIT
556563
Mentally trace a second execution of the skill on the same state:
557564
- Does Phase 0 handle pre-existing artifacts (skip, warn, overwrite)?
558565
- Do file-creation steps fail if the file already exists?
559-
- Are `mktemp` paths unique across runs (they should be by default)?
566+
- Are `mktemp` paths unique across runs? Check every template's `X` run is **trailing** (`tmp.XXXXXXXXXX`, not `tmp.XXXXXXXXXX.ext`) — a suffix after the X's breaks uniqueness on macOS BSD `mktemp` (issue #2157) even though it works on Linux
560567

561568
Document any idempotency fix applied.
562569

‎.claude/skills/create-skill/scripts/lint-skill.sh‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,12 @@ warn() { echo "WARN: $1"; WARNINGS=$((WARNINGS + 1)); }
3131
# Extract bash blocks (skip quadruple-backtick example regions) and check
3232
# if UPPER_CASE variables assigned in one block are referenced in a later
3333
# block without file-based persistence.
34-
BLOCKS_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.blocks")
34+
# Trailing X's only (no suffix) — BSD mktemp (macOS) only randomizes a
35+
# trailing X run; a suffix after it (e.g. ".blocks") returns the template
36+
# literally instead of a unique path (issue #2157). The extension isn't
37+
# load-bearing here (this file is only ever grepped/awked, never dispatched
38+
# by codegraph's extension-based language detection).
39+
BLOCKS_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
3540
trap 'rm -f "$BLOCKS_FILE"' EXIT
3641

3742
# Extract bash blocks with block index, skipping those inside ```` regions.
@@ -296,6 +301,19 @@ while IFS=$'\t' read -r bnum line; do
296301
fi
297302
done < "$BLOCKS_FILE"
298303

304+
# ── Check 10b: mktemp template with a non-trailing X run (issue #2157) ──
305+
# BSD mktemp (macOS) only randomizes a TRAILING run of X's — a suffix
306+
# directly after it (tmp.XXXXXXXXXX.ext) returns the template literally
307+
# instead of creating a unique path, causing silent collisions across
308+
# concurrent runs and "File exists" failures on re-runs. Matches any X{6,}
309+
# run immediately followed by something other than another X, a closing
310+
# quote/paren, or whitespace.
311+
while IFS=$'\t' read -r bnum line; do
312+
if [[ "$line" =~ mktemp ]] && [[ "$line" =~ X{6,}[^X\"\'\ \)] ]]; then
313+
warn "bash block $bnum: mktemp template's X run is not trailing — BSD mktemp (macOS) won't randomize it; use a trailing-X template, or mktemp -d a directory and place the named/extensioned file inside it (Pattern 3/13)"
314+
fi
315+
done < "$BLOCKS_FILE"
316+
299317
# ── Check 11: Hardcoded /tmp/ paths ─────────────────────────────────
300318
line_num=0
301319
in_quad=false

‎.claude/skills/create-skill/scripts/smoke-test-skill.sh‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,11 @@ if [ ! -f "$SKILL_FILE" ]; then
1717
exit 1
1818
fi
1919

20-
TMPBLOCK=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.sh")
20+
# Trailing X's only (no suffix) — BSD mktemp (macOS) only randomizes a
21+
# trailing X run; a suffix after it (e.g. ".sh") returns the template
22+
# literally instead of a unique path (issue #2157). bash -n below doesn't
23+
# need the .sh extension anyway.
24+
TMPBLOCK=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
2125
trap 'rm -f "$TMPBLOCK"' EXIT
2226

2327
PASS=0
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
/**
2+
* Regression test for issue #2157: `.claude/skills/create-skill/SKILL.md`
3+
* mandated `mktemp "/tmp/tmp.XXXXXXXXXX.ext"` as its "portable"
4+
* temp-file template. BSD `mktemp` (macOS) only randomizes a TRAILING run
5+
* of `X`s — a suffix directly after it returns the template literally
6+
* instead of creating a unique path, so every skill generated by
7+
* `/create-skill` following that pattern got a fixed, non-unique temp path
8+
* on macOS: concurrent sessions collided on the same literal file, and
9+
* re-runs failed outright with "mkstemp failed ... File exists".
10+
*
11+
* The fix rewrites every mandated example to use a trailing-X `mktemp -d`
12+
* template (creating a temp directory) with the extensioned file placed
13+
* inside it, and adds a `lint-skill.sh` check (this test's subject) so a
14+
* future skill reintroducing the broken pattern is caught automatically.
15+
*/
16+
import { execFileSync } from 'node:child_process';
17+
import fs from 'node:fs';
18+
import os from 'node:os';
19+
import path from 'node:path';
20+
import { fileURLToPath } from 'node:url';
21+
import { describe, expect, it } from 'vitest';
22+
23+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
24+
const REPO_ROOT = path.resolve(__dirname, '..', '..');
25+
const LINT_SCRIPT = path.join(
26+
REPO_ROOT,
27+
'.claude',
28+
'skills',
29+
'create-skill',
30+
'scripts',
31+
'lint-skill.sh',
32+
);
33+
34+
// lint-skill.sh requires bash 4+ (associative arrays). macOS ships bash 3.2
35+
// (Apple stopped updating it at the GPLv2/v3 boundary) as the `bash` on
36+
// PATH, including on GitHub Actions' macos-latest runner — resolve a real
37+
// bash 4+ explicitly rather than assuming plain "bash" is adequate.
38+
function resolveBash4(): string | null {
39+
const candidates = ['/opt/homebrew/bin/bash', '/usr/local/bin/bash', 'bash'];
40+
for (const candidate of candidates) {
41+
try {
42+
const version = execFileSync(candidate, ['--version'], { encoding: 'utf8' });
43+
const match = version.match(/version (\d+)\./);
44+
if (match && Number(match[1]) >= 4) return candidate;
45+
} catch {
46+
// candidate not on PATH — try the next one
47+
}
48+
}
49+
return null;
50+
}
51+
52+
const BASH4 = resolveBash4();
53+
54+
const FRONTMATTER = `---
55+
name: lint-test-skill
56+
description: test
57+
argument-hint: none
58+
allowed-tools: Bash
59+
---
60+
61+
## Phase 0
62+
63+
pre-flight
64+
65+
## Rules
66+
67+
rules here
68+
69+
## Examples
70+
71+
example here
72+
`;
73+
74+
function runLint(bashBlock: string): { stdout: string; ranSuccessfully: boolean } {
75+
const content = `${FRONTMATTER}\n\`\`\`bash\n${bashBlock}\n\`\`\`\n\n**Exit condition:** done\n`;
76+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-skill-mktemp-'));
77+
const skillPath = path.join(dir, 'SKILL.md');
78+
fs.writeFileSync(skillPath, content);
79+
try {
80+
const result = execFileSync(BASH4!, [LINT_SCRIPT, skillPath], { encoding: 'utf8' });
81+
return { stdout: result, ranSuccessfully: true };
82+
} catch (err) {
83+
const e = err as { stdout?: string };
84+
const stdout = e.stdout ?? '';
85+
// lint-skill.sh only exits non-zero when it found an ERROR (as opposed
86+
// to a warning) — this test's fixtures only ever trigger warnings, so a
87+
// non-zero exit here means the script itself failed to run (e.g. a
88+
// bash-version mismatch), not that it ran and found nothing.
89+
return { stdout, ranSuccessfully: /lint-skill: \d+ error/.test(stdout) };
90+
} finally {
91+
fs.rmSync(dir, { recursive: true, force: true });
92+
}
93+
}
94+
95+
// Every "does not flag" assertion below is meaningless if the script never
96+
// actually ran (e.g. execFileSync throwing before producing output) — an
97+
// empty/missing stdout would vacuously satisfy `not.toContain(...)`.
98+
// Asserting ranSuccessfully first turns a silent script failure into a
99+
// loud, specific test failure instead of a false pass.
100+
describe.skipIf(BASH4 === null)(
101+
'lint-skill.sh flags mktemp templates with a non-trailing X run (#2157)',
102+
() => {
103+
it('flags a suffix directly after the X run (the exact bug reported)', () => {
104+
const { stdout, ranSuccessfully } = runLint('TMPFILE=$(mktemp "/tmp/tmp.XXXXXXXXXX.js")');
105+
expect(ranSuccessfully).toBe(true);
106+
expect(stdout).toContain("mktemp template's X run is not trailing");
107+
});
108+
109+
it('flags a non-extension suffix too (any character directly after the X run)', () => {
110+
const { stdout, ranSuccessfully } = runLint(
111+
'BLOCKS_FILE=$(mktemp "/tmp/tmp.XXXXXXXXXX.blocks")',
112+
);
113+
expect(ranSuccessfully).toBe(true);
114+
expect(stdout).toContain("mktemp template's X run is not trailing");
115+
});
116+
117+
it('does not flag a trailing-X-only template', () => {
118+
const { stdout, ranSuccessfully } = runLint('TMPFILE=$(mktemp "/tmp/tmp.XXXXXXXXXX")');
119+
expect(ranSuccessfully).toBe(true);
120+
expect(stdout).not.toContain("mktemp template's X run is not trailing");
121+
});
122+
123+
it('does not flag mktemp -d with a trailing-X template (the recommended fix)', () => {
124+
const { stdout, ranSuccessfully } = runLint(
125+
[
126+
'TMP_DIR=$(mktemp -d "/tmp/tmp.XXXXXXXXXX")',
127+
'trap \'rm -rf "$TMP_DIR"\' EXIT',
128+
'TMP_FILE="$TMP_DIR/probe.js"',
129+
].join('\n'),
130+
);
131+
expect(ranSuccessfully).toBe(true);
132+
expect(stdout).not.toContain("mktemp template's X run is not trailing");
133+
});
134+
135+
it('does not flag a bare mktemp -d with no template at all', () => {
136+
const { stdout, ranSuccessfully } = runLint('WORK_DIR=$(mktemp -d)');
137+
expect(ranSuccessfully).toBe(true);
138+
expect(stdout).not.toContain("mktemp template's X run is not trailing");
139+
});
140+
},
141+
);
142+
143+
describe.skipIf(BASH4 === null)(
144+
'.claude/skills/create-skill/SKILL.md itself has no non-trailing-X mktemp templates',
145+
() => {
146+
it('passes lint-skill.sh with no mktemp-related warnings', () => {
147+
const realSkillPath = path.join(REPO_ROOT, '.claude', 'skills', 'create-skill', 'SKILL.md');
148+
const stdout = execFileSync(BASH4!, [LINT_SCRIPT, realSkillPath], { encoding: 'utf8' });
149+
expect(stdout).toContain('lint-skill: 0 error');
150+
expect(stdout).not.toContain("mktemp template's X run is not trailing");
151+
});
152+
},
153+
);

0 commit comments

Comments
 (0)