devcontour-harness 0.1.0-alpha.27 → 0.1.0-alpha.28

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.
@@ -211,7 +211,7 @@ export declare class DocumentView {
211
211
  activeRunId?: string | undefined;
212
212
  resultSha?: string | undefined;
213
213
  failure?: string | undefined;
214
- failureKind?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
214
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
215
215
  failureFingerprint?: string | undefined;
216
216
  approvedAt?: string | undefined;
217
217
  approvedDigest?: string | undefined;
@@ -359,7 +359,7 @@ export declare class DocumentView {
359
359
  activeRunId?: string | undefined;
360
360
  resultSha?: string | undefined;
361
361
  failure?: string | undefined;
362
- failureKind?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
362
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
363
363
  failureFingerprint?: string | undefined;
364
364
  approvedAt?: string | undefined;
365
365
  approvedDigest?: string | undefined;
@@ -618,6 +618,21 @@ export declare class DocumentView {
618
618
  } | undefined;
619
619
  coverage?: string[] | undefined;
620
620
  } | undefined;
621
+ artifactFiles?: {
622
+ dir: string;
623
+ files: {
624
+ path: string;
625
+ sha256: string;
626
+ bytes: number;
627
+ redacted?: true | undefined;
628
+ }[];
629
+ skipped: {
630
+ path: string;
631
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
632
+ detail?: string | undefined;
633
+ }[];
634
+ skippedMore?: number | undefined;
635
+ } | undefined;
621
636
  checks?: string | undefined;
622
637
  alreadySatisfied?: {
623
638
  gates: string[];
@@ -644,7 +659,7 @@ export declare class DocumentView {
644
659
  integrationSha?: string | undefined;
645
660
  error?: string | undefined;
646
661
  blocked?: boolean | undefined;
647
- failureKind?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
662
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
648
663
  failureFingerprint?: string | undefined;
649
664
  requiredGates?: string[] | undefined;
650
665
  consumers?: {
@@ -734,7 +749,7 @@ export declare class DocumentView {
734
749
  kind: "candidate" | "unfinished";
735
750
  applied: boolean;
736
751
  files: string[];
737
- reason?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
752
+ reason?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
738
753
  respecified?: boolean | undefined;
739
754
  } | undefined;
740
755
  callsRecorded?: true | undefined;
@@ -932,6 +947,21 @@ export declare class DocumentView {
932
947
  } | undefined;
933
948
  coverage?: string[] | undefined;
934
949
  } | undefined;
950
+ artifactFiles?: {
951
+ dir: string;
952
+ files: {
953
+ path: string;
954
+ sha256: string;
955
+ bytes: number;
956
+ redacted?: true | undefined;
957
+ }[];
958
+ skipped: {
959
+ path: string;
960
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
961
+ detail?: string | undefined;
962
+ }[];
963
+ skippedMore?: number | undefined;
964
+ } | undefined;
935
965
  checks?: string | undefined;
936
966
  alreadySatisfied?: {
937
967
  gates: string[];
@@ -958,7 +988,7 @@ export declare class DocumentView {
958
988
  integrationSha?: string | undefined;
959
989
  error?: string | undefined;
960
990
  blocked?: boolean | undefined;
961
- failureKind?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
991
+ failureKind?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
962
992
  failureFingerprint?: string | undefined;
963
993
  requiredGates?: string[] | undefined;
964
994
  consumers?: {
@@ -1048,7 +1078,7 @@ export declare class DocumentView {
1048
1078
  kind: "candidate" | "unfinished";
1049
1079
  applied: boolean;
1050
1080
  files: string[];
1051
- reason?: "gate" | "unknown" | "review" | "environment" | "cancelled" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1081
+ reason?: "gate" | "unknown" | "review" | "cancelled" | "environment" | "timeout" | "provider-auth" | "stale-base" | "empty-result" | "unfinished" | "scope-violation" | "review-protocol" | "merge" | "budget" | "needs-lead" | undefined;
1052
1082
  respecified?: boolean | undefined;
1053
1083
  } | undefined;
1054
1084
  callsRecorded?: true | undefined;
@@ -1109,6 +1139,21 @@ export declare class DocumentView {
1109
1139
  path: string;
1110
1140
  digest: string;
1111
1141
  }[];
1142
+ artifactFiles?: {
1143
+ dir: string;
1144
+ files: {
1145
+ path: string;
1146
+ sha256: string;
1147
+ bytes: number;
1148
+ redacted?: true | undefined;
1149
+ }[];
1150
+ skipped: {
1151
+ path: string;
1152
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1153
+ detail?: string | undefined;
1154
+ }[];
1155
+ skippedMore?: number | undefined;
1156
+ } | undefined;
1112
1157
  durationMs?: number | undefined;
1113
1158
  }[];
1114
1159
  token: string;
@@ -1122,7 +1167,7 @@ export declare class DocumentView {
1122
1167
  changed: string[];
1123
1168
  affected: string[];
1124
1169
  gateIds: string[];
1125
- mode: "all" | "affected";
1170
+ mode: "affected" | "all";
1126
1171
  reason: string;
1127
1172
  baseline?: string | undefined;
1128
1173
  } | undefined;
@@ -1149,6 +1194,21 @@ export declare class DocumentView {
1149
1194
  path: string;
1150
1195
  digest: string;
1151
1196
  }[];
1197
+ artifactFiles?: {
1198
+ dir: string;
1199
+ files: {
1200
+ path: string;
1201
+ sha256: string;
1202
+ bytes: number;
1203
+ redacted?: true | undefined;
1204
+ }[];
1205
+ skipped: {
1206
+ path: string;
1207
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1208
+ detail?: string | undefined;
1209
+ }[];
1210
+ skippedMore?: number | undefined;
1211
+ } | undefined;
1152
1212
  durationMs?: number | undefined;
1153
1213
  }[];
1154
1214
  token: string;
@@ -1162,7 +1222,7 @@ export declare class DocumentView {
1162
1222
  changed: string[];
1163
1223
  affected: string[];
1164
1224
  gateIds: string[];
1165
- mode: "all" | "affected";
1225
+ mode: "affected" | "all";
1166
1226
  reason: string;
1167
1227
  baseline?: string | undefined;
1168
1228
  } | undefined;
@@ -1193,6 +1253,21 @@ export declare class DocumentView {
1193
1253
  path: string;
1194
1254
  digest: string;
1195
1255
  }[];
1256
+ artifactFiles?: {
1257
+ dir: string;
1258
+ files: {
1259
+ path: string;
1260
+ sha256: string;
1261
+ bytes: number;
1262
+ redacted?: true | undefined;
1263
+ }[];
1264
+ skipped: {
1265
+ path: string;
1266
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1267
+ detail?: string | undefined;
1268
+ }[];
1269
+ skippedMore?: number | undefined;
1270
+ } | undefined;
1196
1271
  durationMs?: number | undefined;
1197
1272
  }[];
1198
1273
  token: string;
@@ -1201,7 +1276,7 @@ export declare class DocumentView {
1201
1276
  changed: string[];
1202
1277
  affected: string[];
1203
1278
  gateIds: string[];
1204
- mode: "all" | "affected";
1279
+ mode: "affected" | "all";
1205
1280
  reason: string;
1206
1281
  baseline?: string | undefined;
1207
1282
  } | undefined;
@@ -1227,6 +1302,21 @@ export declare class DocumentView {
1227
1302
  path: string;
1228
1303
  digest: string;
1229
1304
  }[];
1305
+ artifactFiles?: {
1306
+ dir: string;
1307
+ files: {
1308
+ path: string;
1309
+ sha256: string;
1310
+ bytes: number;
1311
+ redacted?: true | undefined;
1312
+ }[];
1313
+ skipped: {
1314
+ path: string;
1315
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1316
+ detail?: string | undefined;
1317
+ }[];
1318
+ skippedMore?: number | undefined;
1319
+ } | undefined;
1230
1320
  durationMs?: number | undefined;
1231
1321
  }[];
1232
1322
  token: string;
@@ -1240,7 +1330,7 @@ export declare class DocumentView {
1240
1330
  changed: string[];
1241
1331
  affected: string[];
1242
1332
  gateIds: string[];
1243
- mode: "all" | "affected";
1333
+ mode: "affected" | "all";
1244
1334
  reason: string;
1245
1335
  baseline?: string | undefined;
1246
1336
  } | undefined;
@@ -1267,6 +1357,21 @@ export declare class DocumentView {
1267
1357
  path: string;
1268
1358
  digest: string;
1269
1359
  }[];
1360
+ artifactFiles?: {
1361
+ dir: string;
1362
+ files: {
1363
+ path: string;
1364
+ sha256: string;
1365
+ bytes: number;
1366
+ redacted?: true | undefined;
1367
+ }[];
1368
+ skipped: {
1369
+ path: string;
1370
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1371
+ detail?: string | undefined;
1372
+ }[];
1373
+ skippedMore?: number | undefined;
1374
+ } | undefined;
1270
1375
  durationMs?: number | undefined;
1271
1376
  }[];
1272
1377
  token: string;
@@ -1280,7 +1385,7 @@ export declare class DocumentView {
1280
1385
  changed: string[];
1281
1386
  affected: string[];
1282
1387
  gateIds: string[];
1283
- mode: "all" | "affected";
1388
+ mode: "affected" | "all";
1284
1389
  reason: string;
1285
1390
  baseline?: string | undefined;
1286
1391
  } | undefined;
@@ -1311,6 +1416,21 @@ export declare class DocumentView {
1311
1416
  path: string;
1312
1417
  digest: string;
1313
1418
  }[];
1419
+ artifactFiles?: {
1420
+ dir: string;
1421
+ files: {
1422
+ path: string;
1423
+ sha256: string;
1424
+ bytes: number;
1425
+ redacted?: true | undefined;
1426
+ }[];
1427
+ skipped: {
1428
+ path: string;
1429
+ reason: "missing" | "symlink" | "outside" | "not-regular" | "hardlink" | "secret" | "extension" | "file-limit" | "total-limit" | "count-limit" | "scan-limit" | "copy-failed";
1430
+ detail?: string | undefined;
1431
+ }[];
1432
+ skippedMore?: number | undefined;
1433
+ } | undefined;
1314
1434
  durationMs?: number | undefined;
1315
1435
  }[];
1316
1436
  token: string;
@@ -1319,7 +1439,7 @@ export declare class DocumentView {
1319
1439
  changed: string[];
1320
1440
  affected: string[];
1321
1441
  gateIds: string[];
1322
- mode: "all" | "affected";
1442
+ mode: "affected" | "all";
1323
1443
  reason: string;
1324
1444
  baseline?: string | undefined;
1325
1445
  } | undefined;
@@ -0,0 +1,34 @@
1
+ import { gateArtifactLimits, type GateArtifactFiles } from '../contracts/index.ts';
2
+ import type { Redactor } from '../environment/redaction.ts';
3
+ type Limits = {
4
+ -readonly [K in keyof typeof gateArtifactLimits]: number;
5
+ };
6
+ /**
7
+ * Сохранить artifacts gate в `dest` и описать результат для evidence.
8
+ *
9
+ * Пути — относительно корня дерева `root`; каталог обходится в порядке имён
10
+ * в пределах `scan` записей. Ссылки не разыменовываются ни в объявленном
11
+ * пути, ни в его компонентах, ни внутри каталога: такой путь записывается как
12
+ * `symlink`. Копируются только обычные файлы с одной жёсткой ссылкой и с
13
+ * разрешёнными расширениями в пределах `gateArtifactLimits`; файл,
14
+ * разрешающийся перед чтением вне дерева, не
15
+ * копируется. Всё прочее и всякий отказ чтения или записи записываются в
16
+ * `skipped` с причиной. Функция не бросает: исход gate от сохранения не
17
+ * зависит, а отказ сохранения остаётся в evidence.
18
+ *
19
+ * `dest` принадлежит harness: прежние копии того же gate удаляются, чтобы
20
+ * они не выдали себя за результат этого запуска. Каталог, совпадающий с
21
+ * деревом, содержащий его или лежащий внутри него, отклоняется до удаления.
22
+ */
23
+ export declare function keepGateArtifacts(options: {
24
+ root: string;
25
+ paths: readonly string[];
26
+ dest: string;
27
+ redact: Redactor;
28
+ signal?: AbortSignal;
29
+ /** Только для тестов: меньшие пределы. */
30
+ limits?: Partial<Limits>;
31
+ /** Только для тестов: вызывается перед посещением каждого пути. */
32
+ beforeVisit?: (rel: string) => Promise<void> | void;
33
+ }): Promise<GateArtifactFiles>;
34
+ export {};
@@ -0,0 +1,303 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, mkdir, open, opendir, realpath, rm, writeFile } from 'node:fs/promises';
3
+ import { basename, dirname, extname, join, resolve, sep } from 'node:path';
4
+ import { gateArtifactExtensions, gateArtifactLimits, sha256, } from "../contracts/index.js";
5
+ /** Текстовые расширения: в копии маскируются секреты окружения, как в логе gate. */
6
+ const textExtensions = new Set(['.json', '.txt', '.xml', '.log']);
7
+ const allowed = new Set(gateArtifactExtensions);
8
+ const message = (error) => (error instanceof Error ? error.message : String(error));
9
+ const inside = (path, root) => path.startsWith(root + sep);
10
+ /** Реальный путь, даже если хвоста ещё нет: ближайший существующий предок разрешается. */
11
+ async function realTarget(path) {
12
+ const absolute = resolve(path);
13
+ try {
14
+ return await realpath(absolute);
15
+ }
16
+ catch (error) {
17
+ if (error.code !== 'ENOENT')
18
+ throw error;
19
+ const parent = dirname(absolute);
20
+ if (parent === absolute)
21
+ throw error;
22
+ return join(await realTarget(parent), basename(absolute));
23
+ }
24
+ }
25
+ /**
26
+ * Секрет в байтах не текстового файла. Изображение не переписывается (маска
27
+ * испортила бы его), поэтому такой файл не копируется. Формы секрета — те же,
28
+ * что маскирует redactor (`secrets`); у redactor без них — его же проверка
29
+ * по байтам, прочитанным как UTF-8 и как latin1.
30
+ */
31
+ function binaryHasSecret(bytes, redact) {
32
+ if (redact.secrets)
33
+ return redact.secrets.some((secret) => secret.length > 0 &&
34
+ (bytes.includes(Buffer.from(secret, 'utf8')) ||
35
+ bytes.includes(Buffer.from(secret, 'utf16le'))));
36
+ for (const encoding of ['utf8', 'latin1']) {
37
+ const text = bytes.toString(encoding);
38
+ if (redact(text) !== text)
39
+ return true;
40
+ }
41
+ return false;
42
+ }
43
+ const marker = Buffer.from('[REDACTED]');
44
+ /**
45
+ * Маска секретов в байтах текстового файла; `undefined` — секретов нет. По
46
+ * списку форм redactor замена идёт по байтам: невалидный UTF-8 вокруг секрета
47
+ * остаётся как был. Redactor без списка применяется к тексту UTF-8.
48
+ */
49
+ function maskText(bytes, redact) {
50
+ if (!redact.secrets) {
51
+ const text = bytes.toString('utf8');
52
+ const masked = redact(text);
53
+ return masked === text ? undefined : Buffer.from(masked);
54
+ }
55
+ let out = bytes, changed = false;
56
+ for (const secret of redact.secrets) {
57
+ if (!secret)
58
+ continue;
59
+ const needle = Buffer.from(secret, 'utf8');
60
+ const parts = [];
61
+ let from = 0;
62
+ for (let at = out.indexOf(needle); at >= 0; at = out.indexOf(needle, from)) {
63
+ parts.push(out.subarray(from, at), marker);
64
+ from = at + needle.length;
65
+ }
66
+ if (!parts.length)
67
+ continue;
68
+ parts.push(out.subarray(from));
69
+ out = Buffer.concat(parts);
70
+ changed = true;
71
+ }
72
+ return changed ? out : undefined;
73
+ }
74
+ /** Объявленные пути без повторов и без путей внутри уже объявленного каталога. */
75
+ function declaredRoots(paths) {
76
+ const unique = [...new Set(paths.map((p) => p.replace(/\/+$/, '')))];
77
+ return unique.filter((p) => !unique.some((other) => other !== p && p.startsWith(other + '/')));
78
+ }
79
+ /**
80
+ * Сохранить artifacts gate в `dest` и описать результат для evidence.
81
+ *
82
+ * Пути — относительно корня дерева `root`; каталог обходится в порядке имён
83
+ * в пределах `scan` записей. Ссылки не разыменовываются ни в объявленном
84
+ * пути, ни в его компонентах, ни внутри каталога: такой путь записывается как
85
+ * `symlink`. Копируются только обычные файлы с одной жёсткой ссылкой и с
86
+ * разрешёнными расширениями в пределах `gateArtifactLimits`; файл,
87
+ * разрешающийся перед чтением вне дерева, не
88
+ * копируется. Всё прочее и всякий отказ чтения или записи записываются в
89
+ * `skipped` с причиной. Функция не бросает: исход gate от сохранения не
90
+ * зависит, а отказ сохранения остаётся в evidence.
91
+ *
92
+ * `dest` принадлежит harness: прежние копии того же gate удаляются, чтобы
93
+ * они не выдали себя за результат этого запуска. Каталог, совпадающий с
94
+ * деревом, содержащий его или лежащий внутри него, отклоняется до удаления.
95
+ */
96
+ export async function keepGateArtifacts(options) {
97
+ const { redact, signal } = options;
98
+ const paths = declaredRoots(options.paths);
99
+ const limits = { ...gateArtifactLimits, ...options.limits };
100
+ const files = [];
101
+ const skipped = [];
102
+ let skippedMore = 0, total = 0, scanned = 0, stopped = false;
103
+ const skip = (path, reason, detail) => {
104
+ if (skipped.length >= limits.skipped) {
105
+ skippedMore++;
106
+ return;
107
+ }
108
+ skipped.push({
109
+ path: redact(path).slice(0, 1000) || '.',
110
+ reason,
111
+ ...(detail ? { detail: redact(detail).slice(0, 500) } : {}),
112
+ });
113
+ };
114
+ const done = () => ({ dir: dest, files, skipped, ...(skippedMore ? { skippedMore } : {}) });
115
+ let root, dest = resolve(options.dest);
116
+ // Отменённый запуск не трогает и прежние копии: удалять их уже незачем.
117
+ if (signal?.aborted) {
118
+ for (const path of paths)
119
+ skip(path, 'copy-failed', 'проверка отменена');
120
+ return done();
121
+ }
122
+ try {
123
+ root = await realpath(options.root);
124
+ // Удаляется только свой каталог копий: никогда не дерево, не его предок и
125
+ // не каталог внутри него. Сравниваются реальные пути (/var и /private/var).
126
+ dest = await realTarget(options.dest);
127
+ if (dest === root || inside(root, dest) || inside(dest, root))
128
+ throw new Error('каталог копий artifacts пересекается с деревом проверки');
129
+ await rm(dest, { recursive: true, force: true });
130
+ await mkdir(dest, { recursive: true });
131
+ }
132
+ catch (error) {
133
+ for (const path of paths)
134
+ skip(path, 'copy-failed', message(error));
135
+ return done();
136
+ }
137
+ const read = async (abs) => {
138
+ // Каталог-предок мог быть подменён ссылкой после обхода: копия берётся
139
+ // только из пути, который и сейчас разрешается внутрь дерева. Между этой
140
+ // проверкой и open остаётся окно гонки: без openat его не закрыть по пути.
141
+ // Его может использовать только процесс, переживший gate; потомков gate
142
+ // harness завершает до копирования (см. docs/contracts.md).
143
+ const real = await realpath(abs);
144
+ if (!inside(real, root))
145
+ return 'outside';
146
+ const handle = await open(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
147
+ try {
148
+ const stat = await handle.stat();
149
+ if (!stat.isFile())
150
+ return 'not-regular';
151
+ // Жёсткая ссылка на файл вне дерева неотличима от своего файла по пути.
152
+ if (stat.nlink > 1)
153
+ return 'hardlink';
154
+ if (stat.size > limits.fileBytes)
155
+ return 'file-limit';
156
+ const buffer = Buffer.allocUnsafe(Math.min(stat.size, limits.fileBytes) + 1);
157
+ let size = 0;
158
+ for (;;) {
159
+ const { bytesRead } = await handle.read(buffer, size, buffer.length - size);
160
+ if (!bytesRead)
161
+ break;
162
+ size += bytesRead;
163
+ if (size > limits.fileBytes)
164
+ return 'file-limit';
165
+ // Файл вырос после stat: копия была бы не тем, что описано.
166
+ if (size === buffer.length)
167
+ throw new Error('файл изменился при чтении');
168
+ }
169
+ return Buffer.from(buffer.subarray(0, size));
170
+ }
171
+ finally {
172
+ await handle.close();
173
+ }
174
+ };
175
+ const copy = async (rel, abs) => {
176
+ if (!allowed.has(extname(rel).toLowerCase()))
177
+ return skip(rel, 'extension');
178
+ // Имя копии на диске равно пути в evidence: путь с секретом не сохраняется.
179
+ if (redact(rel) !== rel)
180
+ return skip(rel, 'secret');
181
+ if (files.length >= limits.files)
182
+ return skip(rel, 'count-limit');
183
+ let bytes;
184
+ try {
185
+ const result = await read(abs);
186
+ if (!Buffer.isBuffer(result))
187
+ return skip(rel, result);
188
+ bytes = result;
189
+ }
190
+ catch (error) {
191
+ return skip(rel, 'copy-failed', message(error));
192
+ }
193
+ let redacted = false;
194
+ if (textExtensions.has(extname(rel).toLowerCase())) {
195
+ const masked = maskText(bytes, redact);
196
+ if (masked) {
197
+ bytes = masked;
198
+ redacted = true;
199
+ }
200
+ }
201
+ // Секрет, оставшийся после маски (текст в UTF-16 и других кодировках), и
202
+ // секрет в не текстовом файле: такой файл не копируется.
203
+ if (binaryHasSecret(bytes, redact))
204
+ return skip(rel, 'secret');
205
+ if (bytes.length > limits.fileBytes)
206
+ return skip(rel, 'file-limit');
207
+ if (total + bytes.length > limits.totalBytes)
208
+ return skip(rel, 'total-limit');
209
+ try {
210
+ const target = join(dest, ...rel.split('/'));
211
+ await mkdir(dirname(target), { recursive: true });
212
+ await writeFile(target, bytes, { flag: 'wx' });
213
+ }
214
+ catch (error) {
215
+ return skip(rel, 'copy-failed', message(error));
216
+ }
217
+ total += bytes.length;
218
+ files.push({
219
+ path: rel,
220
+ sha256: sha256(bytes),
221
+ bytes: bytes.length,
222
+ ...(redacted ? { redacted: true } : {}),
223
+ });
224
+ };
225
+ const visit = async (rel, abs) => {
226
+ if (signal?.aborted)
227
+ return skip(rel, 'copy-failed', 'проверка отменена');
228
+ await options.beforeVisit?.(rel);
229
+ let info;
230
+ try {
231
+ info = await lstat(abs);
232
+ }
233
+ catch (error) {
234
+ return skip(rel, 'copy-failed', message(error));
235
+ }
236
+ if (info.isSymbolicLink())
237
+ return skip(rel, 'symlink');
238
+ if (info.isFile())
239
+ return copy(rel, abs);
240
+ if (!info.isDirectory())
241
+ return skip(rel, 'not-regular');
242
+ // Записи читаются только до предела обхода: огромный каталог не
243
+ // перечисляется целиком. Прочитанное посещается в порядке имён.
244
+ const names = [];
245
+ try {
246
+ const handle = await opendir(abs);
247
+ try {
248
+ for await (const entry of handle) {
249
+ if (scanned >= limits.scan) {
250
+ stopped = true;
251
+ skip(rel, 'scan-limit', `обход остановлен после ${limits.scan} записей`);
252
+ break;
253
+ }
254
+ scanned++;
255
+ names.push(entry.name);
256
+ }
257
+ }
258
+ finally {
259
+ // Прерванный for await уже закрыл каталог; повторное закрытие — не ошибка.
260
+ await handle.close().catch(() => undefined);
261
+ }
262
+ }
263
+ catch (error) {
264
+ return skip(rel, 'copy-failed', message(error));
265
+ }
266
+ for (const name of names.sort())
267
+ await visit(`${rel}/${name}`, join(abs, name));
268
+ };
269
+ for (const rel of paths) {
270
+ if (stopped) {
271
+ skip(rel, 'scan-limit', `обход остановлен после ${limits.scan} записей`);
272
+ continue;
273
+ }
274
+ const abs = resolve(root, rel);
275
+ if (!inside(abs, root)) {
276
+ skip(rel, 'outside');
277
+ continue;
278
+ }
279
+ // Компоненты пути проверяются по одному: ссылка на любом уровне могла бы
280
+ // увести копирование за пределы дерева.
281
+ const parts = rel.split('/');
282
+ let blocked, detail;
283
+ for (let i = 1; i <= parts.length && !blocked; i++) {
284
+ try {
285
+ const info = await lstat(join(root, ...parts.slice(0, i)));
286
+ if (info.isSymbolicLink())
287
+ blocked = 'symlink';
288
+ else if (i < parts.length && !info.isDirectory())
289
+ blocked = 'missing';
290
+ }
291
+ catch (error) {
292
+ blocked = error.code === 'ENOENT' ? 'missing' : 'copy-failed';
293
+ detail = blocked === 'copy-failed' ? message(error) : undefined;
294
+ }
295
+ }
296
+ if (blocked) {
297
+ skip(rel, blocked, detail);
298
+ continue;
299
+ }
300
+ await visit(rel, abs);
301
+ }
302
+ return done();
303
+ }
@@ -11,6 +11,7 @@ import { UntrustedCheckoutError } from "../environment/git-trust.js";
11
11
  import { TaskFailure } from "../engine/failure.js";
12
12
  import { redactDeep } from "../environment/redaction.js";
13
13
  import { expectsReference, manifestDigest, propertyCoverage, propertyFailure, propertySeed, readPropertyReport, } from "./property.js";
14
+ import { keepGateArtifacts } from "./gate-artifacts.js";
14
15
  /** Длинное имя testcase заменяется хешем, а не обрезается: обрезка дала бы ложные совпадения. */
15
16
  export const TEST_ID_LIMIT = 1000;
16
17
  export function portableTest(test) {
@@ -716,6 +717,19 @@ export async function runGate(run) {
716
717
  }
717
718
  else if (corpusDir)
718
719
  await rm(corpusDir, { recursive: true, force: true }).catch(() => undefined);
720
+ // Artifacts gate (снимки экрана, отчёты) сохраняются при любом исходе:
721
+ // провал — тот случай, когда они нужнее всего. Пропуски и отказы копирования
722
+ // названы в evidence и на исход gate не влияют.
723
+ const artifactFiles = gate.artifacts?.length
724
+ ? await keepGateArtifacts({
725
+ root,
726
+ paths: gate.artifacts,
727
+ // Точки в ID нет: имя не совпадёт с каталогом другого gate или фазы.
728
+ dest: join(artifactDir, `${gate.id}.artifacts`),
729
+ redact,
730
+ signal,
731
+ })
732
+ : undefined;
719
733
  await mkdir(artifactDir, { recursive: true });
720
734
  const logPath = join(artifactDir, `${gate.id}.log`);
721
735
  log = redact(log);
@@ -735,6 +749,7 @@ export async function runGate(run) {
735
749
  ...(manifest?.truncated ? { testsTruncated: true } : {}),
736
750
  ...(run.consumer ? { consumer: run.consumer } : {}),
737
751
  ...(propertyEvidence ? { property: propertyEvidence } : {}),
752
+ ...(artifactFiles ? { artifactFiles } : {}),
738
753
  ...(run.recheck
739
754
  ? {
740
755
  recheck: {