Files
msd-core/scripts/workflow-policy.cjs
Tom Boucher d83e58eea0 fix(#437,#439,#440): restore defaults.run.shell + 'zsh {0}' format + Windows .cmd shell:true (PR #434 fallout) (#438)
* fix(#437): restore defaults.run.shell at job level (step-level matrix expr rejected by GHA)

Per actions/runner workflow-v1.0.json schema, `jobs.<job_id>.defaults.run.shell`
allows `matrix` context (job-defaults-run has context:[matrix,...]); step-level
`shell:` does not (run-step's shell field is plain string with no context array).
PR #434 used step-level shell:${{matrix.shell}}, which GHA's parser rejects with
"Unrecognized named-value: 'matrix'" — blocking every push to next and every
release.yml dispatch.

This commit:
- Removes step-level `shell: ${{ matrix.shell }}` from test-full (test.yml)
  and smoke (install-smoke.yml) jobs (17 directives).
- Adds `defaults.run.shell: ${{ matrix.shell }}` at job level in those two jobs.
- Fixes pre-existing shellcheck SC2129 in test.yml (individual >> redirects →
  grouped brace form) and SC2010 in install-smoke.yml (ls|grep → glob loop).

Verified locally with actionlint 1.7.12 (exit 0). Policy linter still 0 violations
(matrix.shell now resolves via job.defaults.run.shell which the linter already
handles per workflow-policy.cjs:effectiveShell).

Refs: actions/runner#444 (open since 2020), GHA contexts page section "Context availability".

* fix(#439): inline ci-smoke-skip back to shell (Node port required pre-checkout file resolution)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#440): use platform-correct npm.cmd on Windows for spawn (and surface-check other Node ports)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#437): use 'zsh {0}' format string in matrix.shell for macOS (zsh not in GHA built-ins)

Per https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
(jobs.<job_id>.defaults.run.shell section):

  "You can use built-in shell keywords like bash, pwsh, python, sh, cmd, and
  powershell, or define a custom set of shell options."

zsh is not in the built-ins list. GHA accepts custom shells via a format string
containing '{0}', which it replaces with the temporary script file path at
runtime (same pattern as the perl {0} example in the docs).

Bare `shell: zsh` triggers: "Invalid shell option. Shell must be a valid
built-in or a format string containing '{0}'".

Precursor: 514cb429 introduced the matrix shell-pinning pattern; this completes
it by switching the macOS rows from the bare value to the required format string.

Also updates scripts/workflow-policy.cjs to normalise 'zsh {0}' to 'zsh' before
the policy comparison, so the repo-baseline test continues to pass (the linter
was correctly treating 'zsh {0}' as a distinct value from the policy 'zsh').

Affects:
- .github/workflows/test.yml: test-full matrix (node 22 + node 24 macOS rows)
- .github/workflows/install-smoke.yml: smoke matrix (macOS node 24 row)
- scripts/workflow-policy.cjs: detectViolation strips ' {0}' format suffix

* fix(#440): add shell:true to spawnSync on Windows for .cmd files (Node docs requirement)

Per https://nodejs.org/docs/latest-v22.x/api/child_process.html:

  ".bat and .cmd files require a terminal to run and cannot be launched
  directly with execFile(). To run these scripts on Windows, use
  child_process.spawn() with the shell option, child_process.exec(), or
  spawn cmd.exe with the script as an argument."

  "On Windows, .bat and .cmd files require a shell to execute. Use
  child_process.exec() or child_process.spawn() with the shell: true option."

On Windows, npm is installed as npm.cmd (a batch wrapper). Without
shell: true, spawnSync resolves the binary directly and fails with
ENOENT / "npm binary not found on PATH" because the OS cannot execute
a .cmd file without cmd.exe as the intermediary.

The fix uses `shell: process.platform === 'win32'` so the shell spawning
is only activated on Windows; macOS/Linux continue to resolve the plain
npm binary directly with shell: false, preserving the existing behaviour
on non-Windows platforms.

Updated both spawnSync(npmCmd, ...) call sites:
- npm --version check (line 182)
- npm ci --dry-run lockfile-sync check (line 215)

* fix(#437): bug-410 defaults test — set USERPROFILE for Windows os.homedir() redirect

On Windows, os.homedir() reads USERPROFILE (not HOME), so the test's
process.env.HOME = FAKE_HOME redirect was silently ignored. finishInstall's
path.join(os.homedir(), '.gsd') resolved to the real user home and the
defaults.json write either failed (permissions) or landed outside the temp
dir, causing the existsSync assertion to return false.

Fix: also set process.env.USERPROFILE = FAKE_HOME so os.homedir() returns
the sandboxed directory on Windows. Node.js docs (os.homedir):
https://nodejs.org/docs/latest-v22.x/api/os.html#oshomedir

Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#437): precommit-alias-drift hook test — use path.delimiter for PATH

Hardcoded ':' PATH separator breaks Windows where process.env.PATH uses ';'.
The malformed PATH passed to bash caused the mock git/npm stubs in binDir
to be invisible to the hook script; npm was never called and the marker
file never written.

Fix: replace ':' with path.delimiter in both PATH constructions so the
env var is well-formed on Windows (';') and POSIX (':') alike.

Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#437): prepush-enterprise-email hook test — use path.delimiter for PATH

Same root cause as precommit-alias-drift: hardcoded ':' PATH separator is
invalid on Windows (';' required). The malformed PATH meant bash ran the
real git binary instead of the mock stub, which rejected the placeholder
SHAs 'refs-local-sha' / 'refs-remote-sha' with a fatal ambiguous-argument
error rather than returning the fixture commit list.

Fix: replace ':' with path.delimiter in both execFileSync PATH env values.

Refs: #437 (fix/437-restore-defaults-run-shell), Windows pwsh compat

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#437): set MSYS2_PATH_TYPE=inherit so mock stubs take precedence in Git Bash PATH

Root cause: Git Bash (MSYS2) on Windows prepends its own system directories
(/mingw64/bin, /usr/bin, /bin) to the PATH at process startup before the
user-supplied Windows PATH entries. This placed the real git/npm binaries
ahead of the mock stubs in binDir even though binDir was first in the Windows
PATH passed to execFileSync. The path.delimiter fix (0042fe0d) made the PATH
syntactically correct for Windows (semicolons) but did not change the MSYS2
system-dir prepend order.

The real git rejected placeholder SHAs (refs-local-sha, refs-remote-sha) with
"fatal: ambiguous argument", producing the observed Windows CI failure. For the
pre-commit test, the real git output nothing (no staged files on a fresh
checkout), so the grep match failed and npm was never called.

Fix: set MSYS2_PATH_TYPE=inherit in the env passed to both bash spawns.
With inherit, MSYS2 uses only the converted Windows PATH without prepending
system directories, so binDir (converted from Windows to POSIX) is first in
the search path and the mock stubs are found.

grep/tr/printf remain available: the GHA Windows runner PATH includes
C:\Program Files\Git\usr\bin which contains these utilities; MSYS2 converts
that Windows entry to a POSIX path on startup. The /usr/bin/env shebang in
mock stubs resolves through MSYS2's virtual filesystem mount (not via PATH)
and is always accessible regardless of MSYS2_PATH_TYPE.

On macOS/Linux this variable is ignored; no behaviour change on those platforms.

Source: https://www.msys2.org/wiki/MSYS2-introduction/#path
(MSYS2_PATH_TYPE controls whether system dirs are prepended to converted PATH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(#437): hook test mocks — use cmd-shim pattern for Windows bin resolution

On Windows, bash (Git Bash / MSYS2) resolves PATH commands by scanning for
extensionless files, but cmd.exe and Win32 process creation resolve via
PATHEXT (.CMD, .BAT, .EXE). When execFileSync('bash', [hookPath]) runs a
hook that calls `git` or `npm`, both resolution paths may fire. The previous
approach set MSYS2_PATH_TYPE=inherit in the child env, but that variable is
only read in /etc/profile (login-shell path) — bash launched without --login
never sources /etc/profile, so the variable had no effect:
https://github.com/msys2/MSYS2-packages/blob/master/filesystem/profile

Fix: adopt the cmd-shim three-file pattern used by npm itself:
https://github.com/npm/cmd-shim
For each mock binary, write:
  <name>          extensionless bash script (bash PATH scan)
  <name>.cmd      batch wrapper delegating to bash (PATHEXT / cmd.exe)
  <name>.ps1      PowerShell wrapper (completeness)

This is the same approach used by stevemao/mock-bin for test mocking with
Windows CI green on AppVeyor:
https://github.com/stevemao/mock-bin

The .cmd and .ps1 files are only written on process.platform === 'win32'.
MSYS2_PATH_TYPE is removed from the child env — it was ineffective and is
no longer needed with the shim files in place.

* fix(#437): tarball-smoke — raise CHILD_TIMEOUT_MS on Windows to 600 s

The CI failure showed a test duration of 120003.1812 ms — matching the
previous CHILD_TIMEOUT_MS = 120_000 exactly. When spawnSync hits its
timeout, it sends SIGTERM and returns { status: null, stdout: '', stderr: '' }
per the Node.js docs:
https://nodejs.org/docs/latest-v22.x/api/child_process.html
  "status: <number> | <null> — The exit code of the subprocess, or null if
   the subprocess terminated due to a signal."

The installResult check is `status !== 0`; null !== 0 is true, so the
timeout fired the INSTALL_FAILED path with empty stdout/stderr, which made
the root cause invisible in CI logs.

GitHub-hosted Windows runners are slower than Linux/macOS for
filesystem-heavy operations (npm install -g of a 1499-file tarball):
https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners/about-github-hosted-runners#standard-github-hosted-runners-for-public-repositories

Fix: use 600_000 ms (10 min) on Windows, keeping 120_000 ms on POSIX.
600 s matches the SLOW_HOST_TIMEOUT already used in the test before() helper
for the pack + install fixture step.

Also expose `signal` and `installError` in the INSTALL_FAILED details object
so a future timeout (status=null, signal='SIGTERM', stdout='') is immediately
diagnosable in CI logs without guesswork.

* fix(#437): chmod +x via bash on Windows for hook test mocks (root cause: fs.writeFileSync mode=0o755 no-op on NTFS)

Root cause: Node's fs.writeFileSync mode=0o755 is a no-op for the execute
bit on Windows NTFS. Per https://nodejs.org/docs/latest-v22.x/api/fs.html:
"on Windows only the write permission can be changed." Bash's access(X_OK)
therefore skips the mock file; the real git/npm binary is found later in PATH
and the hook runs against real state instead of the test double.

Fix: after writeFileSync, invoke Git Bash's chmod via the POSIX emulation
layer (Cygwin/MSYS2), which sets the NTFS execute ACL that Node cannot reach:

    const posixPath = filePath.replace(/\\/g, '/');
    execFileSync('bash', ['-c', `chmod +x "${posixPath}"`], { stdio: 'pipe' });

execFileSync('bash', ...) works because Git for Windows ships bash on PATH in
all GHA Windows runners. Forward-slash conversion is required because MSYS2
bash auto-converts /c/foo paths but not mixed-separator paths.

Why prior approaches didn't take effect:
- MSYS2_PATH_TYPE=inherit: only read in /etc/profile (login-shell path);
  execFileSync('bash', ...) launches non-interactively without --login, so
  /etc/profile is never sourced.
  Ref: https://github.com/msys2/MSYS2-packages/blob/master/filesystem/profile
- .cmd/.ps1 cmd-shim wrappers: bash does POSIX command resolution and does
  not honor PATHEXT, so wrappers are not found by bash's own PATH scan.
  They are not wrong (kept for non-bash callers) but do not fix bash's X_OK.

Files changed: tests/precommit-alias-drift-hook.test.cjs,
               tests/prepush-enterprise-email-hook.test.cjs

* refactor(#437): hooks use GIT_OVERRIDE/NPM_OVERRIDE env-var DI; tests drop PATH-mocking

Four prior rounds (path.delimiter join, MSYS2_PATH_TYPE=inherit, cmd-shim
.cmd/.ps1 wrappers, chmod-via-bash post-write) all failed to make MSYS2
bash's PATH-lookup find the mock executables. The root cause is that none
of those approaches can reliably override bash's own command-resolution
on NTFS without fighting NTFS execute-ACLs or login-shell profile sourcing.

The simplest robust solution is to bypass PATH entirely:

Hooks: each hook now binds GIT_CMD="${GIT_OVERRIDE:-git}" (and NPM_CMD for
pre-commit) at the top. When env vars are unset the hooks invoke bare
`git`/`npm` exactly as before — zero behavior change for users.

Tests: writeMockBin/binDir/PATH manipulation replaced by writeMock(), which
writes a .sh mock to a tmpDir and passes its absolute path via GIT_OVERRIDE
/ NPM_OVERRIDE in the execFileSync env. Bash inside the hook executes the
path directly via the seam — no PATH scan, no NTFS ACL check, no MSYS2
profile dependency.

Test-rigor principle: the new seam (env-var injection) is platform-
independent and doesn't rely on bash's command-resolution mechanism on
the host OS.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: CI Rebase Check <ci@gsd-redux>
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-28 18:06:19 -04:00

451 lines
15 KiB
JavaScript

'use strict';
const fs = require('fs');
const path = require('path');
const yaml = require('js-yaml');
// ---------------------------------------------------------------------------
// Policy: native shell per OS
// ---------------------------------------------------------------------------
const POLICY = Object.freeze({
'ubuntu-latest': 'bash',
'ubuntu-22.04': 'bash',
'ubuntu-24.04': 'bash',
'macos-latest': 'zsh',
'macos-13': 'zsh',
'macos-14': 'zsh',
'macos-15': 'zsh',
'windows-latest': 'pwsh',
'windows-2022': 'pwsh',
'windows-2025': 'pwsh',
});
const VIOLATION = Object.freeze({
WRONG_SHELL_FOR_OS: 'wrong_shell_for_os',
MACOS_MISSING_EXPLICIT_ZSH: 'macos_missing_explicit_zsh',
UNKNOWN_RUNNER: 'unknown_runner',
UNRESOLVABLE_MATRIX: 'unresolvable_matrix',
});
// ---------------------------------------------------------------------------
// Runner default (GitHub Actions documented defaults, not policy)
// ---------------------------------------------------------------------------
function runnerDefault(runner) {
if (!runner) return null;
if (runner.startsWith('windows-')) return 'pwsh';
return 'bash'; // ubuntu-* and macos-* both default to bash on GHA
}
// ---------------------------------------------------------------------------
// Matrix expansion
// ---------------------------------------------------------------------------
/**
* Expand a runs-on expression against a job's strategy.matrix.
* Returns an array of { runner: string, resolvable: boolean, context: object }
* objects where `context` holds ALL key→value pairs for the realization row
* (so shell expressions like ${{ matrix.shell }} can be resolved against it).
* 'resolvable: false' means the expression was an unresolved matrix ref.
*/
function expandRunsOn(runsOnRaw, matrix) {
if (!runsOnRaw) return [];
const raw = String(runsOnRaw).trim();
// Detect matrix expression: ${{ matrix.X }} or ${{ matrix['X'] }}
const matrixExprRe = /\$\{\{\s*matrix\.(\w+)\s*\}\}/;
const match = raw.match(matrixExprRe);
if (!match) {
// Literal runner label
return [{ runner: raw, resolvable: true, context: {} }];
}
const key = match[1];
if (!matrix) {
return [{ runner: raw, resolvable: false, context: {} }];
}
const realizations = [];
// matrix.include entries carry complete row context — prefer them as they
// contain all keys (os, node-version, shell, full_only, etc.).
// Each include row is a distinct CI realization and must be validated
// independently — even if two rows share the same runner label, their
// contexts (and therefore effective shells) may differ.
if (Array.isArray(matrix.include)) {
for (const entry of matrix.include) {
if (entry && entry[key] != null) {
const runner = String(entry[key]);
// Clone all keys from include row as the realization context
const context = {};
for (const [k, v] of Object.entries(entry)) {
context[k] = v != null ? String(v) : '';
}
realizations.push({ runner, resolvable: true, context });
}
}
}
// Collect values from matrix.<key> list (e.g. matrix.os: [ubuntu, macos])
// These base-list entries have no extra context beyond the key itself.
// Each entry is pushed unconditionally — deduplicating by runner alone
// would collapse distinct Cartesian rows (e.g. duplicate os values paired
// with different shell values) and hide policy violations on later rows.
if (Array.isArray(matrix[key])) {
for (const val of matrix[key]) {
const runner = String(val);
realizations.push({ runner, resolvable: true, context: { [key]: runner } });
}
}
// matrix.exclude: remove matches
if (Array.isArray(matrix.exclude)) {
for (const excl of matrix.exclude) {
if (excl && excl[key] != null) {
const exclRunner = String(excl[key]);
const idx = realizations.findIndex(r => r.runner === exclRunner);
if (idx !== -1) realizations.splice(idx, 1);
}
}
}
if (realizations.length === 0) {
// Could not resolve — no concrete values found
return [{ runner: raw, resolvable: false, context: {} }];
}
return realizations;
}
// ---------------------------------------------------------------------------
// Matrix expression resolution
// ---------------------------------------------------------------------------
/**
* If `expr` is a `${{ matrix.<key> }}` expression, look up the value in
* `realizationContext` (a plain-object snapshot of one matrix.include row).
* Returns:
* { resolved: true, value: string } — expression resolved to a concrete value
* { resolved: false, key: string } — matrix key absent in this realization
* null — `expr` is not a matrix expression
*/
function resolveMatrixExpr(expr, realizationContext) {
if (!expr || typeof expr !== 'string') return null;
const m = expr.match(/^\s*\$\{\{\s*matrix\.(\w+)\s*\}\}\s*$/);
if (!m) return null;
const key = m[1];
if (!realizationContext || !(key in realizationContext)) {
return { resolved: false, key };
}
return { resolved: true, value: String(realizationContext[key]) };
}
// ---------------------------------------------------------------------------
// Effective-shell resolution
// ---------------------------------------------------------------------------
/**
* Given a step's shell, job defaults, workflow defaults, runner, and the
* current matrix realization context, return the effective shell that will
* actually execute.
*
* Matrix expressions (`${{ matrix.shell }}`) in any shell field are resolved
* against `realizationContext` (a plain object of key→value for the current
* matrix.include row).
*
* Returns:
* { shell: string, unresolvable: false } — concrete shell value
* { shell: null, unresolvable: true, key: string } — matrix expr present but key missing
*/
function effectiveShell(stepShell, jobDefaultsShell, workflowDefaultsShell, runner, realizationContext) {
for (const raw of [stepShell, jobDefaultsShell, workflowDefaultsShell]) {
if (!raw) continue;
const mx = resolveMatrixExpr(raw, realizationContext);
if (mx !== null) {
// It's a matrix expression
if (!mx.resolved) {
return { shell: null, unresolvable: true, key: mx.key };
}
return { shell: mx.value, unresolvable: false };
}
// Literal value
return { shell: raw, unresolvable: false };
}
// Nothing set at any level — use runner default
return { shell: runnerDefault(runner), unresolvable: false };
}
// ---------------------------------------------------------------------------
// Violation detection
// ---------------------------------------------------------------------------
/**
* Determines whether a step/runner combination violates shell policy.
*
* `rawStepShell`, `rawJobDefaultsShell`, `rawWorkflowDefaultsShell` are the
* raw (possibly matrix-expression) values before resolution. They're used
* only for the MACOS_MISSING_EXPLICIT_ZSH sub-classification: that violation
* fires only when nothing is set at any level (all three are null/empty AND
* the runner default is wrong).
*/
function detectViolation(runner, resolvedShell, rawStepShell, rawJobDefaultsShell, rawWorkflowDefaultsShell) {
if (!(runner in POLICY)) {
return VIOLATION.UNKNOWN_RUNNER;
}
const expected = POLICY[runner];
// GHA accepts custom shells as a format string containing '{0}' (e.g. 'zsh {0}').
// Per https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions
// the shell name before the space is the executable; strip the format suffix before
// comparing against the policy so 'zsh {0}' satisfies the 'zsh' requirement.
const normalizedShell = resolvedShell ? resolvedShell.replace(/\s+\{0\}$/, '') : resolvedShell;
if (normalizedShell !== expected) {
// Specific subtype for macOS missing explicit zsh:
// fires only when no shell is set at any level (inherited runner default).
if (runner.startsWith('macos-') && !rawStepShell && !rawJobDefaultsShell && !rawWorkflowDefaultsShell) {
return VIOLATION.MACOS_MISSING_EXPLICIT_ZSH;
}
return VIOLATION.WRONG_SHELL_FOR_OS;
}
return null;
}
// ---------------------------------------------------------------------------
// Source map: find line numbers
// ---------------------------------------------------------------------------
/**
* Find the line number of a string in YAML text.
* Returns 1-based line number of the first occurrence at or after startLine.
*/
function findLineNumber(yamlText, searchStr, startLine) {
const lines = yamlText.split('\n');
const start = Math.max(0, (startLine || 1) - 1);
for (let i = start; i < lines.length; i++) {
if (lines[i].includes(searchStr)) {
return i + 1;
}
}
// Fall back to scanning from beginning
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(searchStr)) {
return i + 1;
}
}
return 1;
}
// ---------------------------------------------------------------------------
// Core inspector
// ---------------------------------------------------------------------------
/**
* inspectWorkflow(yamlText, { filePath }) → structured inspection result
*/
function inspectWorkflow(yamlText, { filePath = '<unknown>' } = {}) {
let doc;
try {
doc = yaml.load(yamlText, { schema: yaml.DEFAULT_SCHEMA });
} catch (e) {
return {
filePath,
jobs: [],
workflowDefaultsShell: null,
parseError: e.message,
};
}
if (!doc || typeof doc !== 'object') {
return { filePath, jobs: [], workflowDefaultsShell: null };
}
const workflowDefaultsShell =
doc.defaults?.run?.shell ?? null;
const jobs = [];
for (const [jobId, jobDef] of Object.entries(doc.jobs || {})) {
if (!jobDef || typeof jobDef !== 'object') continue;
const runsOnRaw = jobDef['runs-on'];
const matrix = jobDef.strategy?.matrix ?? null;
const jobDefaultsShell = jobDef.defaults?.run?.shell ?? null;
const runsOnStr = runsOnRaw != null ? String(runsOnRaw) : '';
const runsOnExpressions = [runsOnStr];
const runnerRealizations = expandRunsOn(runsOnStr, matrix);
const steps = [];
for (const [stepIndex, step] of (jobDef.steps || []).entries()) {
if (!step || typeof step !== 'object') continue;
// Only check steps that actually run shell scripts (have `run:`)
if (!step.run) continue;
const stepShell = step.shell ?? null;
const stepName = step.name ?? `step-${stepIndex}`;
for (const { runner, resolvable, context: realizationContext } of runnerRealizations) {
if (!resolvable) {
// Can't resolve runner — emit UNRESOLVABLE_MATRIX
const lineNum = findLineNumber(yamlText, stepName !== `step-${stepIndex}` ? stepName : String(step.run).slice(0, 20));
steps.push({
index: stepIndex,
name: stepName,
stepShell,
effectiveShell: null,
runner,
violation: VIOLATION.UNRESOLVABLE_MATRIX,
evidence: {
line: lineNum,
snippet: `runs-on: ${runsOnStr} (unresolvable matrix expression)`,
},
});
continue;
}
const effResult = effectiveShell(stepShell, jobDefaultsShell, workflowDefaultsShell, runner, realizationContext);
// If a matrix expression referenced a key not present in this realization row
if (effResult.unresolvable) {
const lineNum = findLineNumber(yamlText, stepName !== `step-${stepIndex}` ? stepName : String(step.run).slice(0, 20));
steps.push({
index: stepIndex,
name: stepName,
stepShell,
effectiveShell: null,
runner,
violation: VIOLATION.UNRESOLVABLE_MATRIX,
evidence: {
line: lineNum,
snippet: `matrix.${effResult.key} not present in realization for runner=${runner}`,
},
});
continue;
}
const eff = effResult.shell;
const violation = detectViolation(runner, eff, stepShell, jobDefaultsShell, workflowDefaultsShell);
// Find evidence line: prefer step name, then shell:, then run: content
let evidenceLine = 1;
let evidenceSnippet = '';
if (stepName !== `step-${stepIndex}`) {
evidenceLine = findLineNumber(yamlText, stepName);
evidenceSnippet = `name: ${stepName}`;
} else if (stepShell) {
evidenceLine = findLineNumber(yamlText, `shell: ${stepShell}`);
evidenceSnippet = `shell: ${stepShell}`;
} else {
const runSnippet = String(step.run).split('\n')[0].slice(0, 40);
evidenceLine = findLineNumber(yamlText, runSnippet);
evidenceSnippet = runSnippet;
}
steps.push({
index: stepIndex,
name: stepName,
stepShell,
effectiveShell: eff,
runner,
violation: violation ?? null,
evidence: {
line: evidenceLine,
snippet: evidenceSnippet,
},
});
}
}
const resolvedRunners = runnerRealizations
.filter(r => r.resolvable)
.map(r => r.runner);
jobs.push({
jobId,
runsOnExpressions,
resolvedRunners,
defaultsShell: jobDefaultsShell,
steps,
});
}
return {
filePath,
jobs,
workflowDefaultsShell,
};
}
/**
* inspectWorkflowFile(absPath) — reads file from disk and calls inspectWorkflow.
*/
function inspectWorkflowFile(absPath) {
const text = fs.readFileSync(absPath, 'utf8');
return inspectWorkflow(text, { filePath: absPath });
}
// ---------------------------------------------------------------------------
// runPolicyLint
// ---------------------------------------------------------------------------
/**
* runPolicyLint({ workflowsDir }) → { violations, summary }
*/
function runPolicyLint({ workflowsDir }) {
const absDir = path.resolve(workflowsDir);
const files = fs.readdirSync(absDir)
.filter(f => f.endsWith('.yml') || f.endsWith('.yaml'))
.map(f => path.join(absDir, f))
.sort();
const violations = [];
for (const filePath of files) {
const result = inspectWorkflowFile(filePath);
for (const job of result.jobs) {
for (const step of job.steps) {
if (step.violation) {
violations.push({
filePath: result.filePath,
jobId: job.jobId,
stepIndex: step.index,
stepName: step.name,
runner: step.runner,
effectiveShell: step.effectiveShell,
stepShell: step.stepShell,
violation: step.violation,
evidence: step.evidence,
});
}
}
}
}
const perViolationType = {};
for (const v of violations) {
perViolationType[v.violation] = (perViolationType[v.violation] || 0) + 1;
}
return {
violations,
summary: {
total: violations.length,
perViolationType,
},
};
}
// ---------------------------------------------------------------------------
// Exports
// ---------------------------------------------------------------------------
module.exports = {
POLICY,
VIOLATION,
inspectWorkflow,
inspectWorkflowFile,
runPolicyLint,
};