@alxwlw/stack 1.16.1 → 1.17.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.
@@ -0,0 +1,144 @@
1
+ // Порт группы repo-rules: один вызов `main` из @alxwlw/repo-rules с захваченным выводом, какие вызовы
2
+ // делать и как читать их исход. Правило группы — repo-rules-rule.ts; здесь только значения и разбор.
3
+
4
+ /** Один вызов `main` repo-rules: код выхода и захваченные строки, склеенные через `\n`. */
5
+ export interface RepoRulesRun {
6
+ code: number;
7
+ out: string;
8
+ err: string;
9
+ }
10
+ /** Порт: вызов repo-rules в процессе. Сбой repo-rules — не исключение, а код 2 в ответе. */
11
+ export type RepoRulesReader = (argv: string[], env: NodeJS.ProcessEnv) => RepoRulesRun;
12
+ /** Порт вместе с входами вызова: окружение и значение `--base`. */
13
+ export interface RepoRulesPort {
14
+ read: RepoRulesReader;
15
+ env: NodeJS.ProcessEnv;
16
+ base: string | undefined;
17
+ }
18
+
19
+ export interface RepoRulesViolation {
20
+ rule: string;
21
+ path: string;
22
+ line: number;
23
+ message: string;
24
+ }
25
+ export interface RepoRulesStale {
26
+ rule: string;
27
+ path: string;
28
+ baseline: number;
29
+ actual: number;
30
+ }
31
+ export interface RepoRulesReport {
32
+ violations: RepoRulesViolation[];
33
+ stale: RepoRulesStale[];
34
+ notes: string[];
35
+ }
36
+ export type RepoRulesPart = RepoRulesReport | { unavailable: string };
37
+ export interface RepoRulesOutcome {
38
+ check: RepoRulesPart;
39
+ diff: RepoRulesPart | { skipped: string };
40
+ }
41
+
42
+ export const DIFF_SKIPPED_NO_BASE = 'skipped (no --base outside GitHub Actions)';
43
+
44
+ const ERROR_PREFIX = 'repo-rules: ';
45
+
46
+ // Тот же предикат, что у repo-rules (diff.mjs): без --base diff зовётся только в GitHub Actions.
47
+ export function repoRulesCalls(
48
+ repoRoot: string,
49
+ base: string | undefined,
50
+ env: NodeJS.ProcessEnv,
51
+ ): { check: string[]; diff: string[] | undefined } {
52
+ const check = ['-C', repoRoot, 'check', '--json'];
53
+ const diff = ['-C', repoRoot, 'diff', '--json'];
54
+ if (base !== undefined && base !== '') return { check, diff: [...diff, '--base', base] };
55
+ return { check, diff: env.GITHUB_ACTIONS === 'true' ? diff : undefined };
56
+ }
57
+
58
+ /** Аргументы режима repo-rules «убрать исправленное из baseline»: его зовёт sync-pr. */
59
+ export function repoRulesDropFixedCall(repoRoot: string): string[] {
60
+ return ['-C', repoRoot, 'baseline', '--drop-fixed'];
61
+ }
62
+
63
+ // Причина сбоя: первая непустая строка stderr без префикса repo-rules, при пустом stderr — код выхода.
64
+ function failureReason(run: RepoRulesRun): string {
65
+ const first = run.err.split('\n').find((l) => l.trim() !== '');
66
+ if (first === undefined) return `exited with ${run.code}`;
67
+ return first.startsWith(ERROR_PREFIX) ? first.slice(ERROR_PREFIX.length) : first;
68
+ }
69
+
70
+ /** Что sync-pr печатает по исходу режима: строки repo-rules при коде 0, иначе причина сбоя. */
71
+ export interface RepoRulesDropFixed {
72
+ out: string[];
73
+ err: string[];
74
+ }
75
+
76
+ export function repoRulesDropFixed(run: RepoRulesRun): RepoRulesDropFixed {
77
+ if (run.code === 0) return { out: run.out.split('\n').filter((l) => l.trim() !== ''), err: [] };
78
+ return { out: [], err: [failureReason(run)] };
79
+ }
80
+
81
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
82
+ typeof v === 'object' && v !== null && !Array.isArray(v);
83
+
84
+ function violationOf(v: unknown): RepoRulesViolation | undefined {
85
+ if (!isRecord(v)) return undefined;
86
+ const { rule, path, line, message } = v;
87
+ if (typeof rule !== 'string' || typeof path !== 'string') return undefined;
88
+ if (typeof line !== 'number' || typeof message !== 'string') return undefined;
89
+ return { rule, path, line, message };
90
+ }
91
+
92
+ function staleOf(v: unknown): RepoRulesStale | undefined {
93
+ if (!isRecord(v)) return undefined;
94
+ const { rule, path, baseline, actual } = v;
95
+ if (typeof rule !== 'string' || typeof path !== 'string') return undefined;
96
+ if (typeof baseline !== 'number' || typeof actual !== 'number') return undefined;
97
+ return { rule, path, baseline, actual };
98
+ }
99
+
100
+ // Список целиком или undefined: один негодный элемент делает негодным весь ответ.
101
+ function listOf<T>(v: unknown, one: (x: unknown) => T | undefined): T[] | undefined {
102
+ if (!Array.isArray(v)) return undefined;
103
+ const out: T[] = [];
104
+ for (const x of v) {
105
+ const item = one(x);
106
+ if (item === undefined) return undefined;
107
+ out.push(item);
108
+ }
109
+ return out;
110
+ }
111
+
112
+ const noteOf = (x: unknown): string | undefined => (typeof x === 'string' ? x : undefined);
113
+
114
+ export function repoRulesPart(run: RepoRulesRun): RepoRulesPart {
115
+ if (run.code !== 0 && run.code !== 1) {
116
+ return { unavailable: failureReason(run) };
117
+ }
118
+ let data: unknown;
119
+ try {
120
+ data = JSON.parse(run.out);
121
+ } catch {
122
+ return { unavailable: 'output is not JSON' };
123
+ }
124
+ if (!isRecord(data)) return { unavailable: 'output has an unexpected shape: not an object' };
125
+ const violations = listOf(data.violations, violationOf);
126
+ if (violations === undefined)
127
+ return { unavailable: 'output has an unexpected shape: violations' };
128
+ const stale = listOf(data.stale, staleOf);
129
+ if (stale === undefined) return { unavailable: 'output has an unexpected shape: stale' };
130
+ const notes = listOf(data.notes, noteOf);
131
+ if (notes === undefined) return { unavailable: 'output has an unexpected shape: notes' };
132
+ // Код 1 без нарушений и без устаревших записей — ответ, которому нельзя верить как «чисто».
133
+ if (run.code === 1 && violations.length === 0 && stale.length === 0) {
134
+ return { unavailable: 'exited with 1 and reported nothing' };
135
+ }
136
+ return { violations, stale, notes };
137
+ }
138
+
139
+ export function readRepoRules(repoRoot: string, port: RepoRulesPort): RepoRulesOutcome {
140
+ const calls = repoRulesCalls(repoRoot, port.base, port.env);
141
+ const check = repoRulesPart(port.read(calls.check, port.env));
142
+ if (calls.diff === undefined) return { check, diff: { skipped: DIFF_SKIPPED_NO_BASE } };
143
+ return { check, diff: repoRulesPart(port.read(calls.diff, port.env)) };
144
+ }
package/src/repo.ts CHANGED
@@ -1,15 +1,17 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { readdirSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
 
4
- import { Glob } from 'bun';
5
4
  import JSON5 from 'json5';
6
5
  import { type Document, parseDocument } from 'yaml';
7
6
 
8
7
  import type { Canon } from './canon.ts';
9
8
  import type { Finding } from './findings.ts';
10
9
  import { parsePeersBaseline, type PeerEntry, PEERS_BASELINE } from './peers.ts';
10
+ import { pinSiteKind } from './toolchain-pins.ts';
11
11
 
12
12
  // package.json в этих каталогах не читаются: чужой или собранный файл — не предмет проверки.
13
+ // По тем же причинам не читаются и файлы с копиями пинов тулчейна (Dockerfile, workflow).
14
+ // Обход дерева (walkFiles) в такие каталоги не заходит.
13
15
  export const SKIP = /node_modules|\.worktrees|\.moon\/cache|(^|\/)(dist|build)\//;
14
16
 
15
17
  // Имена и порядок поиска — как у самого Renovate (расширения json, jsonc, json5 для каждого места; первый
@@ -33,6 +35,8 @@ export const RENOVATE_CONFIGS = [
33
35
  export const WORKSPACE_FILE = 'pnpm-workspace.yaml';
34
36
 
35
37
  export const MOON_TOOLCHAINS = '.moon/toolchains.yml';
38
+ /** Имя конфига тулчейна в moon 1: moon 2 читает MOON_TOOLCHAINS, а этот файл — нет. */
39
+ export const MOON_TOOLCHAIN_V1 = '.moon/toolchain.yml';
36
40
 
37
41
  export const MOON_WORKSPACE = '.moon/workspace.yml';
38
42
 
@@ -95,7 +99,8 @@ export type Snapshot = ReadonlyMap<string, Read>;
95
99
  // сбой разбора одной роли — одна находка. Разбираемые роли: package.json (корневой всегда; вложенные —
96
100
  // только при pnpm-workspace.yaml среди путей), pnpm-workspace.yaml и первый из RENOVATE_CONFIGS среди
97
101
  // путей (нечитаемый заслоняет остальные), MOON_TOOLCHAINS, найденный из MOON_WORKSPACES и PEERS_BASELINE.
98
- // Остальные пути (среди них LOCKFILE) — только в paths, находки не дают.
102
+ // Остальные пути (среди них LOCKFILE и MOON_TOOLCHAIN_V1) загрузчик не разбирает и находок по ним не даёт:
103
+ // они лежат в paths, существование MOON_TOOLCHAIN_V1 читает правило checkMoonV1Toolchain.
99
104
  // Порядок unreadable: по rank, равные — в порядке снимка.
100
105
  export function repoFromSnapshot(snapshot: Snapshot): Repo {
101
106
  const files = new Map<string, string>();
@@ -242,9 +247,33 @@ function readFile(root: string, path: string): Read {
242
247
  }
243
248
  }
244
249
 
250
+ // Файлы под dir (путь от корня репозитория, '' — сам корень), отсортированные, пути через `/`.
251
+ // Каталог, который не читается (или которого нет), пропускается молча: Bun.Glob#scanSync бросает на первом
252
+ // же таком каталоге, а stack check и sync не должны падать из-за чужих данных в дереве. Заходит только в
253
+ // настоящий каталог (не симлинк), без точки в имени и не под SKIP; файл — только настоящий файл.
254
+ function walkFiles(root: string, dir: string): string[] {
255
+ let entries;
256
+ try {
257
+ entries = readdirSync(join(root, dir), { withFileTypes: true });
258
+ } catch {
259
+ return [];
260
+ }
261
+ const out: string[] = [];
262
+ for (const entry of entries) {
263
+ const path = dir === '' ? entry.name : `${dir}/${entry.name}`;
264
+ if (entry.isFile()) out.push(path);
265
+ else if (entry.isDirectory() && !entry.name.startsWith('.') && !SKIP.test(`${path}/`)) {
266
+ out.push(...walkFiles(root, path));
267
+ }
268
+ }
269
+ return out.sort();
270
+ }
271
+
245
272
  // Адаптер диска, без классификации: dest и satisfiedBy канон-файлов, конфиги Renovate и dependabot,
246
- // MOON_TOOLCHAINS, MOON_WORKSPACES, PEERS_BASELINE, LOCKFILE, pnpm-workspace.yaml, корневой package.json;
247
- // если pnpm-workspace.yaml есть (текст или сбой чтения) — ещё вложенные package.json без SKIP.
273
+ // MOON_TOOLCHAINS, MOON_TOOLCHAIN_V1, MOON_WORKSPACES, PEERS_BASELINE, LOCKFILE, pnpm-workspace.yaml, корневой package.json;
274
+ // если pnpm-workspace.yaml есть (текст или сбой чтения) — ещё вложенные package.json без SKIP;
275
+ // всегда — Dockerfile и workflow с возможными копиями пинов (pinSiteKind) без SKIP. Дерево обходится один
276
+ // раз (без скрытых каталогов), каталоги .github/workflows и .github/actions — отдельными обходами.
248
277
  export function readSnapshot(root: string, canon: Canon): Snapshot {
249
278
  const candidates = new Set<string>(['package.json', WORKSPACE_FILE]);
250
279
  for (const f of canon.files) {
@@ -255,6 +284,7 @@ export function readSnapshot(root: string, canon: Canon): Snapshot {
255
284
  ...RENOVATE_CONFIGS,
256
285
  ...DEPENDABOT_CONFIGS,
257
286
  MOON_TOOLCHAINS,
287
+ MOON_TOOLCHAIN_V1,
258
288
  ...MOON_WORKSPACES,
259
289
  PEERS_BASELINE,
260
290
  LOCKFILE,
@@ -262,18 +292,30 @@ export function readSnapshot(root: string, canon: Canon): Snapshot {
262
292
  candidates.add(p);
263
293
  const snapshot = new Map<string, Read>();
264
294
  for (const p of candidates) snapshot.set(p, readFile(root, p));
295
+ const tree = walkFiles(root, '');
265
296
  const workspace = snapshot.get(WORKSPACE_FILE) as Read;
266
297
  if (!('missing' in workspace)) {
267
- for (const file of new Glob('**/package.json').scanSync({ cwd: root })) {
268
- if (!SKIP.test(file) && !candidates.has(file)) snapshot.set(file, readFile(root, file));
298
+ for (const file of tree) {
299
+ if (basename(file) === 'package.json' && !SKIP.test(file) && !candidates.has(file)) {
300
+ snapshot.set(file, readFile(root, file));
301
+ }
269
302
  }
270
303
  }
304
+ for (const file of [
305
+ ...tree,
306
+ ...walkFiles(root, '.github/workflows'),
307
+ ...walkFiles(root, '.github/actions'),
308
+ ]) {
309
+ if (SKIP.test(file) || pinSiteKind(file) === undefined || snapshot.has(file)) continue;
310
+ snapshot.set(file, readFile(root, file));
311
+ }
271
312
  return snapshot;
272
313
  }
273
314
 
274
315
  // Verbatim канон-файл сравнивается по содержимому, поэтому нечитаемый (например, каталог) для правила
275
316
  // отсутствует: file-missing, затем sync падает с EISDIR — громко, намеренно. Create-if-absent
276
- // dest/satisfiedBy, конфиги dependabot и LOCKFILE нужны правилам только как существующие пути.
317
+ // dest/satisfiedBy, конфиги dependabot, LOCKFILE и MOON_TOOLCHAIN_V1 нужны правилам только как существующие пути
318
+ // (загрузчик их не разбирает).
277
319
  export function loadRepo(root: string, canon: Canon): Repo {
278
320
  return repoFromSnapshot(readSnapshot(root, canon));
279
321
  }
@@ -0,0 +1,97 @@
1
+ import { parse, type ParseError, printParseErrorCode } from 'jsonc-parser';
2
+
3
+ import type { Canon } from './canon.ts';
4
+ import type { Finding } from './findings.ts';
5
+ import type { Repo } from './repo.ts';
6
+
7
+ /** Канон-файл с правилами gitleaks: его подключает засев gitleaks. */
8
+ export const GITLEAKS_CANON = '.gitleaks.canon.toml';
9
+
10
+ const NOT_PARSED = 'stack cannot tell whether it extends the canon';
11
+
12
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
13
+ typeof v === 'object' && v !== null && !Array.isArray(v);
14
+
15
+ const notParsed = (format: string, reason: string) =>
16
+ `does not parse as ${format} (${reason}) — ${NOT_PARSED}`;
17
+
18
+ // Засев gitleaks: канон подключён, когда extend.path указывает на канон-файл правил. useDefault = true
19
+ // не годится и вместе с path: gitleaks такой конфиг не загружает.
20
+ function readGitleaks(text: string): string | undefined {
21
+ let data: unknown;
22
+ try {
23
+ data = Bun.TOML.parse(text);
24
+ } catch (error) {
25
+ const first = (error instanceof Error ? error.message : String(error)).split('\n')[0] ?? '';
26
+ return notParsed('TOML', first);
27
+ }
28
+ const extend = isRecord(data) ? data['extend'] : undefined;
29
+ if (isRecord(extend) && extend['useDefault'] === true) {
30
+ return `[extend] must set path = "${GITLEAKS_CANON}" in place of useDefault = true — the canon ruleset already extends the default one, and gitleaks refuses a config that sets both`;
31
+ }
32
+ const path = isRecord(extend) ? extend['path'] : undefined;
33
+ if (typeof path === 'string' && path.replace(/^(\.\/)+/, '') === GITLEAKS_CANON) return undefined;
34
+ return `[extend] path must be "${GITLEAKS_CANON}" — without it the canon ruleset does not apply`;
35
+ }
36
+
37
+ // Записи extends верхнего уровня: строка — одна запись, массив — его строки, прочее — ни одной.
38
+ function readExtends(text: string): string[] | string {
39
+ const errors: ParseError[] = [];
40
+ const data: unknown = parse(text.replace(/^\uFEFF/, ''), errors, { allowTrailingComma: true });
41
+ const first = errors[0];
42
+ if (first) {
43
+ return notParsed(
44
+ 'JSON with comments',
45
+ `${printParseErrorCode(first.error)} at offset ${first.offset}`,
46
+ );
47
+ }
48
+ const value = isRecord(data) ? data['extends'] : undefined;
49
+ if (typeof value === 'string') return [value];
50
+ if (Array.isArray(value)) return value.filter((v): v is string => typeof v === 'string');
51
+ return [];
52
+ }
53
+
54
+ function jsonSeed(pattern: RegExp, message: string): (text: string) => string | undefined {
55
+ return (text) => {
56
+ const entries = readExtends(text);
57
+ if (typeof entries === 'string') return entries;
58
+ return entries.some((entry) => pattern.test(entry)) ? undefined : message;
59
+ };
60
+ }
61
+
62
+ /** dest засева → чтение его текста: undefined — канон подключён, строка — текст находки. */
63
+ export const SEED_CHECKS: ReadonlyMap<string, (text: string) => string | undefined> = new Map([
64
+ ['.gitleaks.toml', readGitleaks],
65
+ [
66
+ '.oxlintrc.json',
67
+ jsonSeed(
68
+ /(^|\/)@alxwlw\/oxlint-config\//,
69
+ '"extends" must include a preset of @alxwlw/oxlint-config, such as "./node_modules/@alxwlw/oxlint-config/node.jsonc" — without it the canon lint rules do not apply',
70
+ ),
71
+ ],
72
+ [
73
+ 'tsconfig.options.json',
74
+ jsonSeed(
75
+ /(^|\/)@alxwlw\/tsconfig\//,
76
+ '"extends" must name a preset of @alxwlw/tsconfig, such as "@alxwlw/tsconfig/node.json" — without it the canon compiler options do not apply',
77
+ ),
78
+ ],
79
+ ]);
80
+
81
+ const NOT_READABLE = `is not a readable file — ${NOT_PARSED}`;
82
+
83
+ // Правило только для отчёта: засев на месте, но канон не подключает. Идёт по файлам канона, не по
84
+ // ключам таблицы: файла нет в каноне — проверять нечего. Отсутствие засева сообщает file-missing.
85
+ export function checkSeedExtends(repo: Repo, canon: Canon): Finding[] {
86
+ const findings: Finding[] = [];
87
+ for (const { dest } of canon.files) {
88
+ const read = SEED_CHECKS.get(dest);
89
+ if (!read || !repo.paths.has(dest)) continue;
90
+ const text = repo.files.get(dest);
91
+ const message = text === undefined ? NOT_READABLE : read(text);
92
+ if (message !== undefined) {
93
+ findings.push({ code: 'canon-not-extended', target: dest, file: dest, message });
94
+ }
95
+ }
96
+ return findings;
97
+ }
package/src/sync-pr.ts CHANGED
@@ -2,12 +2,13 @@ import { spawnSync } from 'node:child_process';
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
 
5
- import { loadCanon } from './canon.ts';
5
+ import { type Canon, loadCanon } from './canon.ts';
6
6
  import { syncOutput, syncRepo } from './check.ts';
7
7
  import { readStackConfig, StackConfigError } from './config.ts';
8
8
  import type { PeersReader } from './peers.ts';
9
9
  import { peersBaseline } from './peers-baseline.ts';
10
10
  import { type Registry, type WaitOptions, waitVisible } from './registry.ts';
11
+ import { repoRulesDropFixed, repoRulesDropFixedCall, type RepoRulesReader } from './repo-rules.ts';
11
12
 
12
13
  export interface NewPr {
13
14
  head: string;
@@ -277,27 +278,36 @@ export interface SyncPrPorts {
277
278
  registry: Registry;
278
279
  print: Print;
279
280
  peers: PeersReader;
281
+ repoRules: RepoRulesReader;
280
282
  }
281
283
 
282
284
  // Как ATTEMPTS/INTERVAL шага ожидания в sync.yml.
283
285
  export const SYNC_PR_WAIT: WaitOptions = { attempts: 12, intervalMs: 10_000 };
284
286
 
285
- // Поле version из package.json пакета: он лежит рядом с src/, как canon/ (canonDir()).
286
- export function ownVersion(): string {
287
- const pkg = JSON.parse(readFileSync(join(import.meta.dir, '..', 'package.json'), 'utf8')) as {
288
- version: string;
289
- };
290
- return pkg.version;
291
- }
292
-
293
287
  class StepFailed extends Error {}
294
288
 
295
- // sync в процессе, ожидание реестра, установка, хук stack:post-sync, затем publishChanges.
289
+ // Исправленные записи baseline repo-rules уходят в тот же коммит: правила идут в процессе и читают исходники,
290
+ // поэтому режим нужен и без package.json, и без установки. Рост и новые нарушения он не записывает, а код
291
+ // не меняет итог: что осталось несведённым, покажет stack check в CI sync-PR. Группу проверяет эта функция.
292
+ function dropFixedRepoRules(
293
+ repoRoot: string,
294
+ canon: Canon,
295
+ repoRules: RepoRulesReader,
296
+ print: Print,
297
+ ): void {
298
+ if (!canon.rules.includes('repo-rules')) return;
299
+ const r = repoRulesDropFixed(repoRules(repoRulesDropFixedCall(repoRoot), {}));
300
+ for (const line of r.out) print('out', line);
301
+ for (const line of r.err) print('err', `sync-pr: repo-rules baseline: ${line}`);
302
+ }
303
+
304
+ // sync в процессе, ожидание реестра, установка, dedupe, хук stack:post-sync, baseline peers и repo-rules, затем
305
+ // publishChanges. dedupe стоит до хука и до baseline peers: и хук, и baseline читают lockfile, который пойдёт в коммит.
296
306
  export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0 | 1 | 2> {
297
307
  const { repoRoot, version } = opts;
298
308
  const { run, print } = ports;
299
309
  try {
300
- let canon: ReturnType<typeof loadCanon>;
310
+ let canon: Canon;
301
311
  try {
302
312
  const cfg = readStackConfig(repoRoot);
303
313
  canon = loadCanon(cfg);
@@ -313,7 +323,10 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
313
323
  }
314
324
 
315
325
  const pkgPath = join(repoRoot, 'package.json');
316
- if (!existsSync(pkgPath)) return await publishChanges(opts, ports.github, print);
326
+ if (!existsSync(pkgPath)) {
327
+ dropFixedRepoRules(repoRoot, canon, ports.repoRules, print);
328
+ return await publishChanges(opts, ports.github, print);
329
+ }
317
330
 
318
331
  let hook = false;
319
332
  try {
@@ -328,10 +341,7 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
328
341
  }
329
342
 
330
343
  if (opts.install) {
331
- const wanted = Object.entries(canon.catalogs.dev ?? {})
332
- .filter(([name]) => name.startsWith('@alxwlw/'))
333
- .map(([name, v]) => ({ name, version: v }));
334
- await waitVisible(wanted, ports.registry, opts.wait);
344
+ await waitVisible(canon.ownPackages, ports.registry, opts.wait);
335
345
  }
336
346
 
337
347
  const step = (cmd: string, args: string[], env?: Record<string, string>): void => {
@@ -339,7 +349,10 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
339
349
  if (code !== 0) throw new StepFailed(`\`${cmd} ${args.join(' ')}\` exited with ${code}`);
340
350
  };
341
351
  step('proto', ['install']);
342
- if (opts.install) step('pnpm', ['install', '--no-frozen-lockfile']);
352
+ if (opts.install) {
353
+ step('pnpm', ['install', '--no-frozen-lockfile']);
354
+ step('pnpm', ['dedupe']);
355
+ }
343
356
  if (hook) step('pnpm', ['run', 'stack:post-sync'], { VERSION: version });
344
357
 
345
358
  // Новый лок мог исправить записи baseline группы peers: они уходят в тот же коммит, иначе CI
@@ -349,6 +362,7 @@ export async function syncPr(opts: SyncPrOptions, ports: SyncPrPorts): Promise<0
349
362
  for (const line of peers.out) print('out', line);
350
363
  for (const line of peers.err) print('err', `sync-pr: peers baseline: ${line}`);
351
364
 
365
+ dropFixedRepoRules(repoRoot, canon, ports.repoRules, print);
352
366
  return await publishChanges(opts, ports.github, print);
353
367
  } catch (error) {
354
368
  print('err', `sync-pr: ${message(error)}`);
@@ -0,0 +1,56 @@
1
+ import { type Canon, parsePins } from './canon.ts';
2
+ import type { Exception } from './exceptions.ts';
3
+ import type { Drift } from './findings.ts';
4
+ import type { Repo } from './repo.ts';
5
+ import { pinSiteKind, rewritePinCopies } from './toolchain-pins.ts';
6
+
7
+ // Пины, с которыми сверяются копии. Исключение на .prototools — репозиторий держит свой тулчейн:
8
+ // берутся строки его собственного файла (нет файла или он не разбирается — пинов нет). Иначе — пины
9
+ // канона: это пины файла, который будет у репозитория после sync, один sync двигает и их, и копии.
10
+ function pinsFor(
11
+ repo: Repo,
12
+ canon: Canon,
13
+ exceptions: readonly Exception[],
14
+ ): Record<string, string> {
15
+ if (!exceptions.some((e) => e.file === '.prototools')) return canon.pins;
16
+ const own = repo.files.get('.prototools');
17
+ if (own === undefined) return {};
18
+ try {
19
+ return parsePins(own);
20
+ } catch {
21
+ return {};
22
+ }
23
+ }
24
+
25
+ // Копии пинов тулчейна в Dockerfile и workflow: одна находка на файл, правка — весь файл целиком.
26
+ // Файлы, которыми владеет канон, правило не смотрит — все dest, и verbatim (их текст целиком задаёт
27
+ // planFiles или удерживает исключение), и засеваемые (create-if-absent): второй write в тот же файл затёр
28
+ // бы первый. Среди dest сегодня нет файлов с копиями пинов — это закрепляет тест «в канон-файлах копий пинов нет».
29
+ export function planToolchainPins(
30
+ repo: Repo,
31
+ canon: Canon,
32
+ exceptions: readonly Exception[],
33
+ ): Drift[] {
34
+ const pins = pinsFor(repo, canon, exceptions);
35
+ const owned = new Set(canon.files.map((f) => f.dest));
36
+ const drifts: Drift[] = [];
37
+ for (const path of [...repo.files.keys()].sort()) {
38
+ const kind = pinSiteKind(path);
39
+ if (kind === undefined || owned.has(path)) continue;
40
+ const text = repo.files.get(path) as string;
41
+ const { text: content, changes } = rewritePinCopies(kind, text, pins);
42
+ if (changes.length === 0) continue;
43
+ const moves = new Set(changes.map((c) => `${c.tool} ${c.from} → ${c.to}`));
44
+ drifts.push({
45
+ code: 'toolchain-pin',
46
+ target: path,
47
+ file: path,
48
+ message: `${changes
49
+ .map((c) => `${c.tool} ${c.from} instead of ${c.to} (line ${c.line})`)
50
+ .join(', ')}: pin copies follow .prototools`,
51
+ fix: `${path}: ${[...moves].join(', ')}`,
52
+ change: { kind: 'write', file: path, content },
53
+ });
54
+ }
55
+ return drifts;
56
+ }