Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions .claude/skills/create-skill/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,26 +181,33 @@ git show HEAD:$FILE 2>/dev/null | codegraph where --file -
**Correct:**
````markdown
```bash
PREV_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.js") # adjust extension to match the language of $FILE; template syntax is portable (macOS + Linux)
trap 'rm -f "$PREV_FILE"' EXIT
# mktemp -d with a trailing-X template, then a named file with the right
# extension inside it — a suffix directly after the X run (mktemp
# "tmp.XXXXXXXXXX.js") returns the template literally on macOS BSD mktemp
# instead of randomizing it (issue #2157); only a trailing X run is portable.
PREV_DIR=$(mktemp -d "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
PREV_FILE="$PREV_DIR/prev.js" # adjust extension to match the language of $FILE
trap 'rm -rf "$PREV_DIR"' EXIT
# $FILE is expected to be set by the surrounding loop, e.g. for FILE in $(git diff --name-only HEAD); do ... done
# 2>/dev/null: suppress git's "fatal: Path X does not exist in HEAD" — the else branch already warns the user
if git show HEAD:"$FILE" > "$PREV_FILE" 2>/dev/null; then
codegraph where --file "$PREV_FILE"
else
echo "WARN: $FILE is new or unreadable in HEAD — skipping before/after comparison"
fi
rm -f "$PREV_FILE"
rm -rf "$PREV_DIR"
trap - EXIT
```
````

### Pattern 3: Temp files need extensions

Codegraph's language detection is extension-based. Temp files passed to codegraph must have the correct extension:
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:

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

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

Avoid shell constructs that behave differently across platforms:
- Use `find ... -name "*.ext" | grep -q .` instead of `find ... -quit` (non-portable) or glob expansion (`ls *.ext`) which differs between bash versions
- Use `mktemp` with template syntax (`mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.ext"`) — GNU flags like `--suffix` and `-p` are not available on macOS BSD `mktemp`
- 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
- Use `sed -i.bak` instead of `sed -i ''` (GNU vs BSD incompatibility)
- Document any platform-specific behavior with a comment: `# NOTE: requires GNU coreutils`

Expand All @@ -290,7 +297,7 @@ Avoid shell constructs that behave differently across platforms:
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:

```bash
TMPFILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.json")
TMPFILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
trap 'rm -f "$TMPFILE"' EXIT
# ... operations that might fail ...
# Reset when done if more work follows:
Expand Down Expand Up @@ -556,7 +563,7 @@ trap - EXIT
Mentally trace a second execution of the skill on the same state:
- Does Phase 0 handle pre-existing artifacts (skip, warn, overwrite)?
- Do file-creation steps fail if the file already exists?
- Are `mktemp` paths unique across runs (they should be by default)?
- 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

Document any idempotency fix applied.

Expand Down
20 changes: 19 additions & 1 deletion .claude/skills/create-skill/scripts/lint-skill.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ warn() { echo "WARN: $1"; WARNINGS=$((WARNINGS + 1)); }
# Extract bash blocks (skip quadruple-backtick example regions) and check
# if UPPER_CASE variables assigned in one block are referenced in a later
# block without file-based persistence.
BLOCKS_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX.blocks")
# Trailing X's only (no suffix) — BSD mktemp (macOS) only randomizes a
# trailing X run; a suffix after it (e.g. ".blocks") returns the template
# literally instead of a unique path (issue #2157). The extension isn't
# load-bearing here (this file is only ever grepped/awked, never dispatched
# by codegraph's extension-based language detection).
BLOCKS_FILE=$(mktemp "${TMPDIR:-/tmp}/tmp.XXXXXXXXXX")
trap 'rm -f "$BLOCKS_FILE"' EXIT

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

# ── Check 10b: mktemp template with a non-trailing X run (issue #2157) ──
# BSD mktemp (macOS) only randomizes a TRAILING run of X's — a suffix
# directly after it (tmp.XXXXXXXXXX.ext) returns the template literally
# instead of creating a unique path, causing silent collisions across
# concurrent runs and "File exists" failures on re-runs. Matches any X{6,}
# run immediately followed by something other than another X, a closing
# quote/paren, or whitespace.
while IFS=$'\t' read -r bnum line; do
if [[ "$line" =~ mktemp ]] && [[ "$line" =~ X{6,}[^X\"\'\ \)] ]]; then
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)"
fi
done < "$BLOCKS_FILE"

# ── Check 11: Hardcoded /tmp/ paths ─────────────────────────────────
line_num=0
in_quad=false
Expand Down
6 changes: 5 additions & 1 deletion .claude/skills/create-skill/scripts/smoke-test-skill.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ if [ ! -f "$SKILL_FILE" ]; then
exit 1
fi

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

PASS=0
Expand Down
153 changes: 153 additions & 0 deletions tests/unit/lint-skill-mktemp-trailing-x.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/**
* Regression test for issue #2157: `.claude/skills/create-skill/SKILL.md`
* mandated `mktemp "/tmp/tmp.XXXXXXXXXX.ext"` as its "portable"
* temp-file template. BSD `mktemp` (macOS) only randomizes a TRAILING run
* of `X`s — a suffix directly after it returns the template literally
* instead of creating a unique path, so every skill generated by
* `/create-skill` following that pattern got a fixed, non-unique temp path
* on macOS: concurrent sessions collided on the same literal file, and
* re-runs failed outright with "mkstemp failed ... File exists".
*
* The fix rewrites every mandated example to use a trailing-X `mktemp -d`
* template (creating a temp directory) with the extensioned file placed
* inside it, and adds a `lint-skill.sh` check (this test's subject) so a
* future skill reintroducing the broken pattern is caught automatically.
*/
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(__dirname, '..', '..');
const LINT_SCRIPT = path.join(
REPO_ROOT,
'.claude',
'skills',
'create-skill',
'scripts',
'lint-skill.sh',
);

// lint-skill.sh requires bash 4+ (associative arrays). macOS ships bash 3.2
// (Apple stopped updating it at the GPLv2/v3 boundary) as the `bash` on
// PATH, including on GitHub Actions' macos-latest runner — resolve a real
// bash 4+ explicitly rather than assuming plain "bash" is adequate.
function resolveBash4(): string | null {
const candidates = ['/opt/homebrew/bin/bash', '/usr/local/bin/bash', 'bash'];
for (const candidate of candidates) {
try {
const version = execFileSync(candidate, ['--version'], { encoding: 'utf8' });
const match = version.match(/version (\d+)\./);
if (match && Number(match[1]) >= 4) return candidate;
} catch {
// candidate not on PATH — try the next one
}
}
return null;
}

const BASH4 = resolveBash4();

const FRONTMATTER = `---
name: lint-test-skill
description: test
argument-hint: none
allowed-tools: Bash
---

## Phase 0

pre-flight

## Rules

rules here

## Examples

example here
`;

function runLint(bashBlock: string): { stdout: string; ranSuccessfully: boolean } {
const content = `${FRONTMATTER}\n\`\`\`bash\n${bashBlock}\n\`\`\`\n\n**Exit condition:** done\n`;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'lint-skill-mktemp-'));
const skillPath = path.join(dir, 'SKILL.md');
Comment on lines +76 to +77

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Fixture Fails Unrelated Name Check

runLint writes SKILL.md under a randomly named directory while its frontmatter declares name: lint-test-skill, so the linter reports a name mismatch and exits non-zero. Because the negative cases inspect only stdout and ignore status, they pass despite this unrelated error and therefore do not establish that the recommended mktemp forms pass lint cleanly.

Fix in Claude Code

fs.writeFileSync(skillPath, content);
try {
const result = execFileSync(BASH4!, [LINT_SCRIPT, skillPath], { encoding: 'utf8' });
return { stdout: result, ranSuccessfully: true };
} catch (err) {
const e = err as { stdout?: string };
const stdout = e.stdout ?? '';
// lint-skill.sh only exits non-zero when it found an ERROR (as opposed
// to a warning) — this test's fixtures only ever trigger warnings, so a
// non-zero exit here means the script itself failed to run (e.g. a
// bash-version mismatch), not that it ran and found nothing.
return { stdout, ranSuccessfully: /lint-skill: \d+ error/.test(stdout) };
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
}

// Every "does not flag" assertion below is meaningless if the script never
// actually ran (e.g. execFileSync throwing before producing output) — an
// empty/missing stdout would vacuously satisfy `not.toContain(...)`.
// Asserting ranSuccessfully first turns a silent script failure into a
// loud, specific test failure instead of a false pass.
describe.skipIf(BASH4 === null)(
'lint-skill.sh flags mktemp templates with a non-trailing X run (#2157)',
() => {
it('flags a suffix directly after the X run (the exact bug reported)', () => {
const { stdout, ranSuccessfully } = runLint('TMPFILE=$(mktemp "/tmp/tmp.XXXXXXXXXX.js")');
expect(ranSuccessfully).toBe(true);
expect(stdout).toContain("mktemp template's X run is not trailing");
});

it('flags a non-extension suffix too (any character directly after the X run)', () => {
const { stdout, ranSuccessfully } = runLint(
'BLOCKS_FILE=$(mktemp "/tmp/tmp.XXXXXXXXXX.blocks")',
);
expect(ranSuccessfully).toBe(true);
expect(stdout).toContain("mktemp template's X run is not trailing");
});

it('does not flag a trailing-X-only template', () => {
const { stdout, ranSuccessfully } = runLint('TMPFILE=$(mktemp "/tmp/tmp.XXXXXXXXXX")');
expect(ranSuccessfully).toBe(true);
expect(stdout).not.toContain("mktemp template's X run is not trailing");
});

it('does not flag mktemp -d with a trailing-X template (the recommended fix)', () => {
const { stdout, ranSuccessfully } = runLint(
[
'TMP_DIR=$(mktemp -d "/tmp/tmp.XXXXXXXXXX")',
'trap \'rm -rf "$TMP_DIR"\' EXIT',
'TMP_FILE="$TMP_DIR/probe.js"',
].join('\n'),
);
expect(ranSuccessfully).toBe(true);
expect(stdout).not.toContain("mktemp template's X run is not trailing");
});

it('does not flag a bare mktemp -d with no template at all', () => {
const { stdout, ranSuccessfully } = runLint('WORK_DIR=$(mktemp -d)');
expect(ranSuccessfully).toBe(true);
expect(stdout).not.toContain("mktemp template's X run is not trailing");
});
},
);

describe.skipIf(BASH4 === null)(
'.claude/skills/create-skill/SKILL.md itself has no non-trailing-X mktemp templates',
() => {
it('passes lint-skill.sh with no mktemp-related warnings', () => {
const realSkillPath = path.join(REPO_ROOT, '.claude', 'skills', 'create-skill', 'SKILL.md');
const stdout = execFileSync(BASH4!, [LINT_SCRIPT, realSkillPath], { encoding: 'utf8' });
expect(stdout).toContain('lint-skill: 0 error');
expect(stdout).not.toContain("mktemp template's X run is not trailing");
});
},
);
Loading