@alxwlw/stack 1.17.0 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,9 +10,9 @@
10
10
  "dependency-cruiser": "18.8.0",
11
11
  "vitest": "5.1.0",
12
12
  "@playwright/test": "1.65.1",
13
- "@alxwlw/stack": "1.17.0",
14
- "@alxwlw/oxlint-config": "1.17.0",
15
- "@alxwlw/tsconfig": "1.17.0"
13
+ "@alxwlw/stack": "1.18.0",
14
+ "@alxwlw/oxlint-config": "1.18.0",
15
+ "@alxwlw/tsconfig": "1.18.0"
16
16
  },
17
17
  "libs": {
18
18
  "@nestjs/core": "12.5.1",
@@ -0,0 +1,21 @@
1
+ name = "hadolint"
2
+ type = "cli"
3
+
4
+ [resolve]
5
+ git-url = "https://github.com/hadolint/hadolint"
6
+
7
+ [platform.linux]
8
+ download-file = "hadolint-linux-{arch}"
9
+ checksum-file = "checksums.sha256"
10
+
11
+ [platform.macos]
12
+ download-file = "hadolint-macos-{arch}"
13
+ checksum-file = "checksums.sha256"
14
+
15
+ [install]
16
+ download-url = "https://github.com/hadolint/hadolint/releases/download/v{version}/{download_file}"
17
+ checksum-url = "https://github.com/hadolint/hadolint/releases/download/v{version}/{checksum_file}"
18
+
19
+ [install.arch]
20
+ aarch64 = "arm64"
21
+ x86_64 = "x86_64"
@@ -10,9 +10,11 @@ uv = "0.13.9"
10
10
  actionlint = "1.7.12"
11
11
  shellcheck = "0.11.0"
12
12
  gitleaks = "8.30.1"
13
+ hadolint = "2.15.1"
13
14
 
14
15
  [plugins]
15
16
  # Vendored: upstream github.com/Phault/proto-toml-plugins was removed 2026-09-13, its URL now returns 404.
16
17
  actionlint = "file://./.moon/proto-plugins/actionlint.toml"
17
18
  shellcheck = "file://./.moon/proto-plugins/shellcheck.toml"
18
19
  gitleaks = "file://./.moon/proto-plugins/gitleaks.toml"
20
+ hadolint = "file://./.moon/proto-plugins/hadolint.toml"
@@ -11,6 +11,15 @@ on:
11
11
  type: choice
12
12
  options: [info, debug]
13
13
  default: info
14
+ # Сам файл токен не берёт (Renovate работает под RENOVATE_TOKEN, это PAT), но renovate.yml@v1 просит contents: read,
15
+ # а права вызывающего — потолок вызываемого: с {} workflow недействителен целиком.
16
+ permissions:
17
+ contents: read
18
+ # Группа уникальна на прогон: очередь держит джоб renovate вызываемого (renovate-<репозиторий>, без отмены).
19
+ # Та же группа у вызывающего и вызываемого дала бы тупик.
20
+ concurrency:
21
+ group: ${{ github.workflow }}-${{ github.run_id }}
22
+ cancel-in-progress: false
14
23
  jobs:
15
24
  renovate:
16
25
  uses: alxwlw/stack/.github/workflows/renovate.yml@v1
@@ -3,6 +3,16 @@ on:
3
3
  pull_request:
4
4
  push:
5
5
  branches: [main]
6
+ # Токен берёт check.yml: actions/checkout и git fetch шага history читают репозиторий — contents: read. Права
7
+ # вызывающего — потолок для вызываемого, поэтому право записано здесь, а не только в check.yml.
8
+ permissions:
9
+ contents: read
10
+ # Группа: PR отменяет свой прежний прогон, push в main не отменяется (группа с run_id уникальна: общая группа
11
+ # отменяла бы и ждущий прогон даже при cancel-in-progress: false). check.yml своего concurrency не имеет —
12
+ # та же группа у вызываемого дала бы тупик.
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
15
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
6
16
  jobs:
7
17
  check:
8
18
  uses: alxwlw/stack/.github/workflows/check.yml@v1
@@ -3,6 +3,16 @@ on:
3
3
  pull_request:
4
4
  push:
5
5
  branches: [main]
6
+ # Токен берёт check.yml: actions/checkout и git fetch шага history читают репозиторий — contents: read. Права
7
+ # вызывающего — потолок для вызываемого, поэтому право записано здесь, а не только в check.yml.
8
+ permissions:
9
+ contents: read
10
+ # Группа: PR отменяет свой прежний прогон, push в main не отменяется (группа с run_id уникальна: общая группа
11
+ # отменяла бы и ждущий прогон даже при cancel-in-progress: false). check.yml своего concurrency не имеет —
12
+ # та же группа у вызываемого дала бы тупик.
13
+ concurrency:
14
+ group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}
15
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
6
16
  jobs:
7
17
  check:
8
18
  uses: alxwlw/stack/.github/workflows/check.yml@v1
@@ -5,6 +5,16 @@ on:
5
5
  version:
6
6
  required: true
7
7
  type: string
8
+ # sync.yml сегодня GITHUB_TOKEN не берёт: клон и PR идут токеном приложения (secrets app-id и app-private-key).
9
+ # contents: read — потолок про запас: если sync.yml@v1 позже начнёт читать репозиторий этим токеном, workflow
10
+ # потребителя всё равно запустится до того, как его sync-PR с новой копией будет открыт.
11
+ permissions:
12
+ contents: read
13
+ # Группа уникальна на прогон: очередь по версии держит джоб sync вызываемого (stack-sync-<версия>, без отмены).
14
+ # Та же группа у вызывающего и вызываемого дала бы тупик.
15
+ concurrency:
16
+ group: ${{ github.workflow }}-${{ github.run_id }}
17
+ cancel-in-progress: false
8
18
  jobs:
9
19
  sync:
10
20
  uses: alxwlw/stack/.github/workflows/sync.yml@v1
@@ -63,6 +63,11 @@
63
63
  "dest": ".moon/proto-plugins/gitleaks.toml",
64
64
  "appliesTo": ["node", "contracts", "infra"]
65
65
  },
66
+ {
67
+ "src": "files/proto-plugins/hadolint.toml",
68
+ "dest": ".moon/proto-plugins/hadolint.toml",
69
+ "appliesTo": ["node", "contracts", "infra"]
70
+ },
66
71
  {
67
72
  "src": "files/oxfmtrc.jsonc",
68
73
  "dest": ".oxfmtrc.jsonc",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alxwlw/stack",
3
- "version": "1.17.0",
3
+ "version": "1.18.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -22,9 +22,10 @@
22
22
  "provenance": true
23
23
  },
24
24
  "dependencies": {
25
- "@alxwlw/repo-rules": "1.17.0",
25
+ "@alxwlw/repo-rules": "1.18.0",
26
26
  "json5": "^2.2.3",
27
27
  "jsonc-parser": "^3.3.1",
28
+ "markdownlint-cli2": "0.24.2",
28
29
  "yaml": "^2.9.1"
29
30
  }
30
31
  }
package/schema.json CHANGED
@@ -14,7 +14,16 @@
14
14
  "description": "Opt-in canon groups. \"renovate\" is deprecated and does nothing: Renovate is the canon's dependency bot for every profile.",
15
15
  "items": {
16
16
  "type": "string",
17
- "enum": ["depcruise", "knip", "libs", "moon-tasks", "peers", "renovate", "repo-rules"]
17
+ "enum": [
18
+ "depcruise",
19
+ "guardrails",
20
+ "knip",
21
+ "libs",
22
+ "moon-tasks",
23
+ "peers",
24
+ "renovate",
25
+ "repo-rules"
26
+ ]
18
27
  }
19
28
  },
20
29
  "exceptions": {
package/src/canon.ts CHANGED
@@ -143,7 +143,7 @@ export function canonDir(): string {
143
143
  const DEPRECATED_GROUPS: readonly string[] = ['renovate'];
144
144
 
145
145
  // Группа правила включает правило `stack check`, файлов и каталогов не даёт.
146
- export const RULE_GROUPS = ['peers', 'repo-rules'] as const;
146
+ export const RULE_GROUPS = ['peers', 'repo-rules', 'guardrails'] as const;
147
147
  export type RuleGroup = (typeof RULE_GROUPS)[number];
148
148
 
149
149
  export interface CanonGroups {
package/src/check.ts CHANGED
@@ -10,6 +10,9 @@ import {
10
10
  import { allowedLine, type Exception, type Held, isHeld, resolve } from './exceptions.ts';
11
11
  import { planFiles } from './files.ts';
12
12
  import type { Drift, Finding } from './findings.ts';
13
+ import { type GuardrailsOutcome, readGuardrails } from './guardrails.ts';
14
+ import type { GuardrailsPort } from './guardrails-port.ts';
15
+ import { checkGuardrails, guardrailsNotes } from './guardrails-rule.ts';
13
16
  import { checkMoonToolchains, checkMoonV1Toolchain } from './moon-toolchains.ts';
14
17
  import { checkMoonDefaultBranch, planMoonDefaultBranch } from './moon-workspace.ts';
15
18
  import { planPackageManager } from './package-manager.ts';
@@ -21,6 +24,7 @@ import { readRepoRules, type RepoRulesOutcome, type RepoRulesPort } from './repo
21
24
  import { checkRepoRules, repoRulesNotes } from './repo-rules-rule.ts';
22
25
  import { checkSeedExtends } from './seed-extends.ts';
23
26
  import { planToolchainPins } from './toolchain-pins-rule.ts';
27
+ import { checkWorkflowHygiene } from './workflow-hygiene.ts';
24
28
 
25
29
  // План дрейфа: всё, что sync умеет закрыть, в порядке применения — файлы, каталоги, release-age,
26
30
  // packageManager, ветка по умолчанию moon, копии пинов тулчейна. Правки одного файла друг от друга не
@@ -38,15 +42,16 @@ export function plan(repo: Repo, canon: Canon, exceptions: readonly Exception[]
38
42
  }
39
43
 
40
44
  // Находки в порядке: план, нечитаемые файлы загрузчика, правила «только отчёт» из deps.ts, засевы и moon,
41
- // правила групп peers и repo-rules, если они включены (в этом порядке); затем протухшие исключения.
45
+ // правила групп peers, repo-rules и guardrails, если они включены (в этом порядке); затем протухшие исключения.
42
46
  // Все они проходят через исключения. peers — исход `pnpm peers check`, repoRules — исход двух вызовов
43
- // repo-rules; оба получает checkRepo.
47
+ // repo-rules, guardrails — исход чтения отслеживаемых файлов, инструментов и скана коммитов PR; все три получает checkRepo.
44
48
  export function check(
45
49
  repo: Repo,
46
50
  canon: Canon,
47
51
  exceptions: Exception[],
48
52
  peers?: PeersOutcome,
49
53
  repoRules?: RepoRulesOutcome,
54
+ guardrails?: GuardrailsOutcome,
50
55
  ): Finding[] {
51
56
  const r = resolve(
52
57
  [
@@ -62,6 +67,9 @@ export function check(
62
67
  ...checkMoonDefaultBranch(repo),
63
68
  ...(canon.rules.includes('peers') ? checkPeers(repo, peers) : []),
64
69
  ...(canon.rules.includes('repo-rules') ? checkRepoRules(repoRules) : []),
70
+ ...(canon.rules.includes('guardrails')
71
+ ? [...checkGuardrails(guardrails), ...checkWorkflowHygiene(repo.files)]
72
+ : []),
65
73
  ],
66
74
  exceptions,
67
75
  );
@@ -80,6 +88,7 @@ export function planRepo(
80
88
  export interface CheckPorts {
81
89
  peers?: PeersReader;
82
90
  repoRules?: RepoRulesPort;
91
+ guardrails?: GuardrailsPort;
83
92
  }
84
93
  /** Итог check: находки (блокируют, если не удержаны) и пометки (выход не меняют). */
85
94
  export interface CheckReport {
@@ -89,6 +98,7 @@ export interface CheckReport {
89
98
 
90
99
  // pnpm запускается, только если группа peers включена и лок есть: без лока правило отвечает само.
91
100
  // repo-rules — только если включена группа: два вызова через порт, пометки идут отдельно от находок.
101
+ // guardrails — тоже только если включена группа: один `git ls-files`, пробы версий, запуски инструментов, `git merge-base` и второй запуск gitleaks по коммитам PR.
92
102
  export function checkRepo(
93
103
  repoRoot: string,
94
104
  canon: Canon,
@@ -108,9 +118,16 @@ export function checkRepo(
108
118
  }
109
119
  repoRules = readRepoRules(repoRoot, ports.repoRules);
110
120
  }
121
+ let guardrails: GuardrailsOutcome | undefined;
122
+ if (canon.rules.includes('guardrails')) {
123
+ if (ports.guardrails === undefined) {
124
+ throw new Error('checkRepo: guardrails group needs a GuardrailsPort');
125
+ }
126
+ guardrails = readGuardrails(repoRoot, repo.files.get('.prototools'), ports.guardrails);
127
+ }
111
128
  return {
112
- findings: check(repo, canon, exceptions, peers, repoRules),
113
- notes: repoRulesNotes(repoRules),
129
+ findings: check(repo, canon, exceptions, peers, repoRules, guardrails),
130
+ notes: [...repoRulesNotes(repoRules), ...guardrailsNotes(guardrails)],
114
131
  };
115
132
  }
116
133
 
package/src/cli.ts CHANGED
@@ -11,6 +11,7 @@ import { type Profile, PROFILES, readStackConfig, StackConfigError } from './con
11
11
  import { allowedLine, isHeld } from './exceptions.ts';
12
12
  import { type Finding, isDrift } from './findings.ts';
13
13
  import { ghGitHub } from './gh.ts';
14
+ import { spawnRunner } from './guardrails-port.ts';
14
15
  import { initConfig } from './init.ts';
15
16
  import { ownVersion } from './own-packages.ts';
16
17
  import type { PeersReader } from './peers.ts';
@@ -163,6 +164,7 @@ try {
163
164
  const { findings, notes } = checkRepo(repoRoot, loadCanon(cfg), cfg.exceptions, {
164
165
  peers: pnpmPeers,
165
166
  repoRules: { read: inProcessRepoRules, env: process.env, base: values.base },
167
+ guardrails: { run: spawnRunner(repoRoot), env: process.env, base: values.base },
166
168
  });
167
169
  for (const n of notes) console.warn(n);
168
170
  const blocking = findings.filter((f) => !isHeld(f));
package/src/exceptions.ts CHANGED
@@ -110,6 +110,11 @@ const ADDRESS: { [C in FindingCode]: ((f: FindingOf<C>) => Address) | 'unsuppres
110
110
  'repo-rules-violation': 'unsuppressible',
111
111
  'stale-repo-rules-baseline': 'unsuppressible',
112
112
  'repo-rules-unavailable': 'unsuppressible',
113
+ // Находки guardrails — вывод инструментов над репозиторием; отказ от гейта — убрать группу из with.
114
+ 'guardrails-violation': 'unsuppressible',
115
+ 'guardrails-unavailable': 'unsuppressible',
116
+ // Гигиена workflow — наличие ключей в файле; отказ от гейта — убрать группу из with.
117
+ 'workflow-hygiene': 'unsuppressible',
113
118
  };
114
119
 
115
120
  export function addressOf(f: Finding): Address | undefined {
package/src/findings.ts CHANGED
@@ -37,7 +37,10 @@ export type Finding = FindingBase &
37
37
  | 'peers-unavailable'
38
38
  | 'repo-rules-violation'
39
39
  | 'stale-repo-rules-baseline'
40
- | 'repo-rules-unavailable';
40
+ | 'repo-rules-unavailable'
41
+ | 'guardrails-violation'
42
+ | 'guardrails-unavailable'
43
+ | 'workflow-hygiene';
41
44
  }
42
45
  );
43
46
  export type FindingCode = Finding['code'];
@@ -0,0 +1,65 @@
1
+ import {
2
+ failureReason,
3
+ type GuardrailRun,
4
+ type GuardrailViolation,
5
+ type Unavailable,
6
+ } from './guardrails-port.ts';
7
+ import { QUIET_LEVELS } from './guardrails-shellcheck.ts';
8
+
9
+ // Флаги до файлов. shellcheck — путь пиненного бинарника или пусто (явно выключен: иначе actionlint
10
+ // берёт тот, что лежит в PATH); pyflakes не пинуется и выключен всегда.
11
+ export function actionlintArgv(shellcheck: string | undefined, files: readonly string[]): string[] {
12
+ return ['-format', '{{json .}}', `-shellcheck=${shellcheck ?? ''}`, '-pyflakes=', ...files];
13
+ }
14
+
15
+ const SHAPE = 'output has an unexpected shape: errors';
16
+
17
+ const SHELLCHECK_MESSAGE =
18
+ /^shellcheck reported issue in this script: SC(\d+):([a-z]+):\d+:\d+: (.*)$/s;
19
+
20
+ // Разбор `-format '{{json .}}'`: код 0 и 1 — вывод, прочее — недоступность. stderr при разобранном
21
+ // выводе не читается. Находка shellcheck внутри actionlint проходит тот же порог, что и shellcheck сам.
22
+ export function parseActionlint(run: GuardrailRun): GuardrailViolation[] | Unavailable {
23
+ if (run.code !== 0 && run.code !== 1) return { unavailable: failureReason(run) };
24
+ if (run.code === 0 && run.out.trim() === '') return [];
25
+ let data: unknown;
26
+ try {
27
+ data = JSON.parse(run.out);
28
+ } catch {
29
+ return { unavailable: 'output is not JSON' };
30
+ }
31
+ if (!Array.isArray(data)) return { unavailable: SHAPE };
32
+ const found: GuardrailViolation[] = [];
33
+ for (const item of data as unknown[]) {
34
+ if (typeof item !== 'object' || item === null) return { unavailable: SHAPE };
35
+ const { message, filepath, line, kind } = item as Record<string, unknown>;
36
+ if (
37
+ typeof message !== 'string' ||
38
+ typeof filepath !== 'string' ||
39
+ typeof line !== 'number' ||
40
+ typeof kind !== 'string'
41
+ ) {
42
+ return { unavailable: SHAPE };
43
+ }
44
+ if (kind !== 'shellcheck') {
45
+ found.push({ tool: 'actionlint', rule: kind, path: filepath, line, message });
46
+ continue;
47
+ }
48
+ const m = SHELLCHECK_MESSAGE.exec(message);
49
+ if (m === null) {
50
+ found.push({ tool: 'actionlint', rule: 'shellcheck', path: filepath, line, message });
51
+ } else if (!QUIET_LEVELS.has(m[2] ?? '')) {
52
+ found.push({
53
+ tool: 'actionlint',
54
+ rule: `SC${m[1] ?? ''}`,
55
+ path: filepath,
56
+ line,
57
+ message: m[3] ?? '',
58
+ });
59
+ }
60
+ }
61
+ if (run.code === 1 && data.length === 0) {
62
+ return { unavailable: 'exited with 1 and reported nothing' };
63
+ }
64
+ return found;
65
+ }
@@ -0,0 +1,129 @@
1
+ // Бинарник инструмента guardrails ровно версии пина `.prototools`: путь из переменной или из
2
+ // `proto bin`, затем всегда проба версии. Только она ловит недоверенный `.prototools` (proto молча
3
+ // игнорирует пины) и устаревшую переменную.
4
+
5
+ import { parsePins } from './canon.ts';
6
+ import {
7
+ failureReason,
8
+ type GuardrailRun,
9
+ type GuardrailsPort,
10
+ type ProtoTool,
11
+ type Unavailable,
12
+ } from './guardrails-port.ts';
13
+
14
+ export interface LocatedTool {
15
+ bin: string;
16
+ version: string;
17
+ }
18
+
19
+ export const VERSION_ARGV: Readonly<Record<ProtoTool, readonly string[]>> = {
20
+ actionlint: ['-version'],
21
+ shellcheck: ['--version'],
22
+ gitleaks: ['version'],
23
+ hadolint: ['--version'],
24
+ uv: ['--version'],
25
+ };
26
+
27
+ export function repoPins(prototools: string | undefined): Record<string, string> | Unavailable {
28
+ if (prototools === undefined) return { unavailable: '.prototools is missing' };
29
+ try {
30
+ return parsePins(prototools);
31
+ } catch (e) {
32
+ const msg = e instanceof Error ? e.message : String(e);
33
+ return { unavailable: `.prototools does not parse: ${msg}` };
34
+ }
35
+ }
36
+
37
+ export function binVar(tool: ProtoTool): string {
38
+ return `${tool.toUpperCase()}_BIN`;
39
+ }
40
+
41
+ // actionlint и gitleaks: первая строка, если это версия (у gitleaks `version`; вывод `--version`
42
+ // другой — `gitleaks version 8.x`, и его проба не принимает); hadolint: первая строка
43
+ // `Haskell Dockerfile Linter <v>`; uv: первая строка `uv <v> (…)`; shellcheck: строка `version: <v>`.
44
+ export function toolVersion(tool: ProtoTool, out: string): string | undefined {
45
+ if (tool === 'hadolint') {
46
+ return /^Haskell Dockerfile Linter (\d+\.\d+\.\d+)$/.exec(out.split('\n')[0] ?? '')?.[1];
47
+ }
48
+ if (tool === 'uv') return /^uv (\d+\.\d+\.\d+)\b/.exec(out.split('\n')[0] ?? '')?.[1];
49
+ if (tool === 'actionlint' || tool === 'gitleaks') {
50
+ const first = out.split('\n')[0]?.trim() ?? '';
51
+ return /^\d+\.\d+\.\d+$/.test(first) ? first : undefined;
52
+ }
53
+ return /^version:\s*(\d+\.\d+\.\d+)\s*$/m.exec(out)?.[1];
54
+ }
55
+
56
+ function isUnavailable(v: Record<string, string> | Unavailable): v is Unavailable {
57
+ return typeof v.unavailable === 'string';
58
+ }
59
+
60
+ function firstLine(text: string): string {
61
+ return text.split('\n')[0]?.trim() ?? '';
62
+ }
63
+
64
+ function ndjsonMessage(line: string): { type?: unknown; message?: unknown } | undefined {
65
+ try {
66
+ const v: unknown = JSON.parse(line);
67
+ return typeof v === 'object' && v !== null ? v : undefined;
68
+ } catch {
69
+ return undefined;
70
+ }
71
+ }
72
+
73
+ // `proto bin` печатает голый путь или NDJSON (в окружении агента): путь — message последней строки,
74
+ // ошибка — message первой строки с type "error".
75
+ export function protoBinPath(run: GuardrailRun): string | Unavailable {
76
+ const lines = run.out.split('\n').filter((l) => l.trim() !== '');
77
+ if (run.code !== 0) {
78
+ for (const l of lines) {
79
+ const m = l.startsWith('{') ? ndjsonMessage(l) : undefined;
80
+ if (m?.type === 'error' && typeof m.message === 'string') {
81
+ const reason = firstLine(m.message);
82
+ if (reason !== '') return { unavailable: reason };
83
+ }
84
+ }
85
+ return { unavailable: failureReason(run) };
86
+ }
87
+ const last = lines.at(-1)?.trim();
88
+ if (last === undefined) return { unavailable: 'printed no path' };
89
+ if (!last.startsWith('{')) return last;
90
+ const m = ndjsonMessage(last);
91
+ if (typeof m?.message === 'string' && m.message.trim() !== '') return m.message.trim();
92
+ return { unavailable: 'printed no path' };
93
+ }
94
+
95
+ export function locateTool(
96
+ tool: ProtoTool,
97
+ pins: Record<string, string> | Unavailable,
98
+ port: GuardrailsPort,
99
+ ): LocatedTool | Unavailable {
100
+ if (isUnavailable(pins)) return pins;
101
+ const pin = pins[tool];
102
+ if (pin === undefined) return { unavailable: `.prototools has no ${tool} pin` };
103
+
104
+ const variable = binVar(tool);
105
+ const fromVar = port.env[variable];
106
+ const viaVar = fromVar !== undefined && fromVar !== '';
107
+ let bin: string;
108
+ if (viaVar) {
109
+ bin = fromVar;
110
+ } else {
111
+ const found = protoBinPath(port.run('proto', ['bin', tool]));
112
+ if (typeof found !== 'string')
113
+ return { unavailable: `proto bin ${tool}: ${found.unavailable}` };
114
+ bin = found;
115
+ }
116
+
117
+ const probe = port.run(bin, [...VERSION_ARGV[tool]]);
118
+ if (probe.code !== 0) {
119
+ const origin = viaVar ? `${variable}=${bin}` : bin;
120
+ return { unavailable: `${origin}: ${failureReason(probe)}` };
121
+ }
122
+ const version = toolVersion(tool, probe.out);
123
+ if (version === undefined) return { unavailable: `${bin} printed no ${tool} version` };
124
+ if (version !== pin) {
125
+ const tail = viaVar ? ` (from ${variable})` : '';
126
+ return { unavailable: `${tool} ${version} at ${bin}, .prototools pins ${pin}${tail}` };
127
+ }
128
+ return { bin, version };
129
+ }
@@ -0,0 +1,42 @@
1
+ import {
2
+ failureReason,
3
+ type GuardrailRun,
4
+ type GuardrailViolation,
5
+ type Unavailable,
6
+ } from './guardrails-port.ts';
7
+
8
+ // База PR для скана коммитов: явный --base, иначе окружение GitHub Actions. Пропуск — не ошибка
9
+ // (код выхода не меняется), недоступная база PR-задачи — ошибка, а не «нет дрейфа».
10
+ export type PrBase = { base: string } | { skipped: string } | Unavailable;
11
+
12
+ export function prBase(base: string | undefined, env: NodeJS.ProcessEnv): PrBase {
13
+ if (base !== undefined && base !== '') return { base };
14
+ if (env.GITHUB_ACTIONS === 'true') {
15
+ const event = env.GITHUB_EVENT_NAME;
16
+ if (event !== 'pull_request' && event !== 'pull_request_target') {
17
+ return { skipped: 'not a pull request' };
18
+ }
19
+ const ref = env.GITHUB_BASE_REF ?? '';
20
+ if (ref === '') return { unavailable: 'GITHUB_BASE_REF is empty in a pull_request job' };
21
+ return { base: `origin/${ref}` };
22
+ }
23
+ return { skipped: 'no --base outside GitHub Actions' };
24
+ }
25
+
26
+ export function mergeBaseArgv(base: string): string[] {
27
+ return ['merge-base', base, 'HEAD'];
28
+ }
29
+
30
+ const COMMIT = /^[0-9a-f]{40}([0-9a-f]{24})?$/;
31
+
32
+ export function mergeBase(run: GuardrailRun, base: string): string | Unavailable {
33
+ if (run.code !== 0) return { unavailable: `git merge-base ${base} HEAD: ${failureReason(run)}` };
34
+ const sha = run.out.trim();
35
+ if (!COMMIT.test(sha)) return { unavailable: `git merge-base ${base} HEAD printed no commit` };
36
+ return sha;
37
+ }
38
+
39
+ export type CommitsPart =
40
+ | { skipped: string }
41
+ | Unavailable
42
+ | { range: string; violations: GuardrailViolation[] };
@@ -0,0 +1,91 @@
1
+ import { closeSync, lstatSync, openSync, readSync } from 'node:fs';
2
+ import { basename, extname, join } from 'node:path';
3
+
4
+ import { failureReason, type GuardrailRun, type Unavailable } from './guardrails-port.ts';
5
+ import { pinSiteKind } from './toolchain-pins.ts';
6
+
7
+ // Отслеживаемые файлы: `git ls-files -z` в корне репозитория, зовётся как run('git', TRACKED_FILES_ARGV).
8
+ export const TRACKED_FILES_ARGV: readonly string[] = ['ls-files', '-z'];
9
+
10
+ const WORKFLOW = /^\.github\/workflows\/[^/]+\.ya?ml$/;
11
+ const SHELLS = new Set(['sh', 'bash', 'dash', 'ksh']);
12
+ const SHEBANG_BYTES = 256;
13
+
14
+ export function trackedFiles(run: GuardrailRun): string[] | Unavailable {
15
+ if (run.code !== 0) return { unavailable: failureReason(run) };
16
+ return run.out.split('\0').filter((p) => p !== '');
17
+ }
18
+
19
+ // Обычные файлы на диске: удалённые из рабочего дерева, симлинки и gitlink выпадают.
20
+ export function regularFiles(root: string, paths: readonly string[]): string[] {
21
+ return paths.filter((p) => {
22
+ try {
23
+ return lstatSync(join(root, p)).isFile();
24
+ } catch {
25
+ return false;
26
+ }
27
+ });
28
+ }
29
+
30
+ export function workflowFiles(paths: readonly string[]): string[] {
31
+ return paths.filter((p) => WORKFLOW.test(p));
32
+ }
33
+
34
+ // Dockerfile любого вида (имя целиком, с суффиксом или с префиксом, как у pinSiteKind) в порядке
35
+ // входа; без SKIP: отслеживаемый Dockerfile в любом каталоге — вход.
36
+ export function dockerfiles(paths: readonly string[]): string[] {
37
+ return paths.filter((p) => pinSiteKind(p) === 'dockerfile');
38
+ }
39
+
40
+ // YAML-файлы по `yaml-files` канона yamllint: basename оканчивается на .yaml или .yml (регистр
41
+ // важен), порядок входа.
42
+ export function yamlFiles(paths: readonly string[]): string[] {
43
+ return paths.filter((p) => /\.ya?ml$/.test(basename(p)));
44
+ }
45
+
46
+ // Markdown-файлы по `globs` канона markdownlint-cli2: basename оканчивается на .md или .mdx (регистр
47
+ // важен), порядок входа.
48
+ export function markdownFiles(paths: readonly string[]): string[] {
49
+ return paths.filter((p) => /\.mdx?$/.test(basename(p)));
50
+ }
51
+
52
+ export function isShellShebang(firstLine: string): boolean {
53
+ if (!firstLine.startsWith('#!')) return false;
54
+ const tokens = firstLine
55
+ .slice(2)
56
+ .split(/\s+/)
57
+ .filter((t) => t !== '');
58
+ const first = tokens[0];
59
+ if (first === undefined) return false;
60
+ let interpreter = basename(first);
61
+ if (interpreter === 'env') {
62
+ const next = tokens.slice(1).find((t) => !t.startsWith('-'));
63
+ if (next === undefined) return false;
64
+ interpreter = basename(next);
65
+ }
66
+ return SHELLS.has(interpreter);
67
+ }
68
+
69
+ function firstLineOf(path: string): string | undefined {
70
+ let fd: number | undefined;
71
+ try {
72
+ fd = openSync(path, 'r');
73
+ const buf = Buffer.alloc(SHEBANG_BYTES);
74
+ const n = readSync(fd, buf, 0, SHEBANG_BYTES, 0);
75
+ return buf.toString('latin1', 0, n).split('\n')[0];
76
+ } catch {
77
+ return undefined;
78
+ } finally {
79
+ if (fd !== undefined) closeSync(fd);
80
+ }
81
+ }
82
+
83
+ export function shellScripts(root: string, paths: readonly string[]): string[] {
84
+ return paths.filter((p) => {
85
+ const ext = extname(p);
86
+ if (ext === '.sh' || ext === '.bash') return true;
87
+ if (ext !== '') return false;
88
+ const line = firstLineOf(join(root, p));
89
+ return line !== undefined && isShellShebang(line);
90
+ });
91
+ }