opencode-windows-scheduler 1.2.3 → 1.4.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +61 -2
  2. package/README.md +21 -4
  3. package/ROADMAP-STRATEGY.md +61 -159
  4. package/ROADMAP.md +60 -98
  5. package/dist/core/audit.d.ts +68 -0
  6. package/dist/core/audit.d.ts.map +1 -0
  7. package/dist/core/audit.js +206 -0
  8. package/dist/core/native-notify.d.ts +36 -0
  9. package/dist/core/native-notify.d.ts.map +1 -0
  10. package/dist/core/native-notify.js +110 -0
  11. package/dist/core/record-history.js +4 -4
  12. package/dist/core/secrets.d.ts +57 -0
  13. package/dist/core/secrets.d.ts.map +1 -0
  14. package/dist/core/secrets.js +331 -0
  15. package/dist/core/structured-log.d.ts.map +1 -1
  16. package/dist/core/structured-log.js +9 -0
  17. package/dist/core/telegram.d.ts +45 -0
  18. package/dist/core/telegram.d.ts.map +1 -0
  19. package/dist/core/telegram.js +160 -0
  20. package/dist/db/schema.d.ts +1 -1
  21. package/dist/db/schema.d.ts.map +1 -1
  22. package/dist/db/schema.js +15 -0
  23. package/dist/index.d.ts +30 -4
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +349 -22
  26. package/dist/notifications.d.ts +26 -6
  27. package/dist/notifications.d.ts.map +1 -1
  28. package/dist/notifications.js +191 -34
  29. package/dist/rpc.d.ts +400 -0
  30. package/dist/rpc.d.ts.map +1 -1
  31. package/dist/rpc.js +146 -0
  32. package/dist/server.d.ts.map +1 -1
  33. package/dist/server.js +67 -0
  34. package/dist/settings.d.ts +63 -2
  35. package/dist/settings.d.ts.map +1 -1
  36. package/dist/settings.js +126 -2
  37. package/dist/workspaces.d.ts +8 -2
  38. package/dist/workspaces.d.ts.map +1 -1
  39. package/dist/workspaces.js +21 -4
  40. package/docs/ARCHITECTURE.md +16 -6
  41. package/docs/FEATURES.md +57 -12
  42. package/docs/README.ru.md +23 -4
  43. package/gui-experimental.cjs +4 -4
  44. package/package.json +5 -2
  45. package/src/core/audit.ts +291 -0
  46. package/src/core/native-notify.ts +154 -0
  47. package/src/core/record-history.ts +6 -4
  48. package/src/core/secrets.ts +385 -0
  49. package/src/core/structured-log.ts +9 -0
  50. package/src/core/telegram.ts +219 -0
  51. package/src/db/schema.ts +15 -0
  52. package/src/gui.tsx +543 -6
  53. package/src/index.ts +459 -22
  54. package/src/notifications.ts +232 -40
  55. package/src/rpc.ts +157 -0
  56. package/src/server.ts +67 -0
  57. package/src/settings.ts +213 -4
  58. package/src/workspaces.ts +22 -4
package/src/server.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { appendStructuredLog, readStructuredLogs } from "./core/structured-log.js";
22
22
  import { PROMETHEUS_CONTENT_TYPE, renderPrometheusMetrics } from "./core/prometheus.js";
23
23
  import { buildOtlpExport } from "./core/otel.js";
24
+ import { readAuditLog, recordAudit } from "./core/audit.js";
24
25
 
25
26
  /**
26
27
  * Локальный веб-дашборд (Спринт 5).
@@ -621,6 +622,7 @@ async function handleRequest(
621
622
  pathname === "/api/history/export" ||
622
623
  pathname === "/api/export-db" ||
623
624
  pathname === "/api/workspaces" ||
625
+ pathname === "/api/audit" ||
624
626
  pathname === "/api/health" ||
625
627
  pathname === "/api/logs" ||
626
628
  pathname === "/metrics" ||
@@ -935,6 +937,27 @@ async function handleRequest(
935
937
  return;
936
938
  }
937
939
 
940
+ // Журнал аудита (Спринт 26): GET /api/audit?action=…&actor=…&limit=…
941
+ if (req.method === "GET" && pathname === "/api/audit") {
942
+ try {
943
+ const limitRaw = Number(url.searchParams.get("limit"));
944
+ const result = readAuditLog({
945
+ action: url.searchParams.get("action") ?? undefined,
946
+ target: url.searchParams.get("target") ?? undefined,
947
+ actor: url.searchParams.get("actor") ?? undefined,
948
+ since: url.searchParams.get("since") ?? undefined,
949
+ until: url.searchParams.get("until") ?? undefined,
950
+ limit: Number.isFinite(limitRaw) ? limitRaw : undefined,
951
+ });
952
+ sendJson(res, 200, { success: true, ...result });
953
+ } catch (err: any) {
954
+ sendJson(res, 500, {
955
+ error: err instanceof Error ? err.message : String(err),
956
+ });
957
+ }
958
+ return;
959
+ }
960
+
938
961
  // Входящий webhook-триггер (Спринт 22): POST /api/hooks/:task?token=…
939
962
  const hookMatch = req.method === "POST" && pathname.match(/^\/api\/hooks\/(.+)$/);
940
963
  if (hookMatch) {
@@ -1022,6 +1045,15 @@ async function handleRequest(
1022
1045
  ? `Задача "${task.name}" уже выполняется.`
1023
1046
  : `Задача "${task.name}" запущена по webhook.`;
1024
1047
  logHook(202, "accepted", undefined, bodyResult.body.length);
1048
+ recordAudit({
1049
+ action: "task.run",
1050
+ targetType: "task",
1051
+ target: task.name,
1052
+ actor: "http",
1053
+ source: "POST /api/hooks/:name",
1054
+ remote,
1055
+ details: { trigger: "hook" },
1056
+ });
1025
1057
  sendJson(res, 202, {
1026
1058
  success: true,
1027
1059
  task: task.name,
@@ -1046,6 +1078,15 @@ async function handleRequest(
1046
1078
  }
1047
1079
  try {
1048
1080
  const result = await deps.runTask(name);
1081
+ recordAudit({
1082
+ action: "task.run",
1083
+ targetType: "task",
1084
+ target: name,
1085
+ actor: "http",
1086
+ source: "POST /api/run/:name",
1087
+ remote: req.socket.remoteAddress ?? null,
1088
+ details: { alreadyRunning: Boolean(result?.alreadyRunning) },
1089
+ });
1049
1090
  sendJson(res, 200, {
1050
1091
  success: true,
1051
1092
  message: result?.alreadyRunning
@@ -1076,6 +1117,15 @@ async function handleRequest(
1076
1117
  }
1077
1118
  try {
1078
1119
  const result = await deps.cancelMatrix(name);
1120
+ recordAudit({
1121
+ action: "matrix.cancel",
1122
+ targetType: "matrix",
1123
+ target: name,
1124
+ actor: "http",
1125
+ source: "POST /api/cancel-matrix/:name",
1126
+ remote: req.socket.remoteAddress ?? null,
1127
+ details: { cancelled: result.cancelled },
1128
+ });
1079
1129
  sendJson(res, 200, {
1080
1130
  success: true,
1081
1131
  message: result.message,
@@ -1098,6 +1148,15 @@ async function handleRequest(
1098
1148
  }
1099
1149
  try {
1100
1150
  const removed = await deps.cleanupMatrixOrphans();
1151
+ recordAudit({
1152
+ action: "matrix.cleanup",
1153
+ targetType: "matrix",
1154
+ target: "orphans",
1155
+ actor: "http",
1156
+ source: "POST /api/matrix-cleanup",
1157
+ remote: req.socket.remoteAddress ?? null,
1158
+ details: { removed: removed.length },
1159
+ });
1101
1160
  sendJson(res, 200, {
1102
1161
  success: true,
1103
1162
  removed,
@@ -1125,6 +1184,14 @@ async function handleRequest(
1125
1184
  }
1126
1185
  try {
1127
1186
  await deps.deleteTask(name);
1187
+ recordAudit({
1188
+ action: "task.delete",
1189
+ targetType: "task",
1190
+ target: name,
1191
+ actor: "http",
1192
+ source: "POST /api/delete/:name",
1193
+ remote: req.socket.remoteAddress ?? null,
1194
+ });
1128
1195
  sendJson(res, 200, { success: true, message: `Задача "${name}" удалена.` });
1129
1196
  } catch (err: any) {
1130
1197
  sendJson(res, 500, {
package/src/settings.ts CHANGED
@@ -60,11 +60,52 @@ export interface DigestSettings {
60
60
  lastSentAt: string | null;
61
61
  }
62
62
 
63
+ /** parse_mode для Telegram Bot API. Пустая строка — plain text. */
64
+ export type TelegramParseMode = "" | "HTML" | "Markdown" | "MarkdownV2";
65
+
66
+ /** Telegram-канал уведомлений (Спринт 25). */
67
+ export interface TelegramNotificationSettings {
68
+ /** Включён ли Telegram-канал. */
69
+ enabled: boolean;
70
+ /** Токен бота из @BotFather. Хранится только локально. */
71
+ botToken: string;
72
+ /** ID чата или канала-получателя. */
73
+ chatId: string;
74
+ /** Разметка сообщения; пусто — plain text. */
75
+ parseMode: TelegramParseMode;
76
+ /** Отправлять без звука. */
77
+ disableNotification: boolean;
78
+ /** ID темы в супергруппе (forum topic), null — обычное сообщение. */
79
+ messageThreadId: number | null;
80
+ /** Добавлять ссылку на локальный дашборд. */
81
+ includeDashboardLink: boolean;
82
+ /** База API; по умолчанию https://api.telegram.org. */
83
+ apiBase: string;
84
+ }
85
+
86
+ /** Нативные уведомления ОС (Спринт 25). */
87
+ export interface NativeNotificationSettings {
88
+ /** Windows Toast, macOS Notification Center, Linux notify-send. */
89
+ enabled: boolean;
90
+ /** Со звуком (где поддерживается). */
91
+ sound: boolean;
92
+ }
93
+
94
+ /** Тихие часы (Спринт 25): success/partial подавляются, ошибки проходят. */
95
+ export interface QuietHoursSettings {
96
+ /** Включён ли режим тихих часов. */
97
+ enabled: boolean;
98
+ /** Начало в HH:MM (локальное время). */
99
+ from: string;
100
+ /** Конец в HH:MM; диапазон может переходить через полночь. */
101
+ to: string;
102
+ }
103
+
63
104
  /**
64
105
  * Уведомления о завершении задач.
65
106
  *
66
- * ntfy.sh намеренно не поддерживается: остаётся только webhook, который
67
- * работает с Discord, Slack и любым generic-эндпоинтом.
107
+ * Каналы: webhook (Discord/Slack/generic), Telegram Bot API и нативные
108
+ * уведомления ОС. Все каналы опциональны и не зависят друг от друга.
68
109
  */
69
110
  export interface NotificationSettings {
70
111
  /** Главный выключатель уведомлений. */
@@ -73,6 +114,14 @@ export interface NotificationSettings {
73
114
  onlyOnError: boolean;
74
115
  /** Webhook-канал. */
75
116
  webhook?: WebhookNotificationSettings;
117
+ /** Telegram-канал. */
118
+ telegram?: TelegramNotificationSettings;
119
+ /** Нативные уведомления ОС. */
120
+ native?: NativeNotificationSettings;
121
+ /** Тихие часы. */
122
+ quietHours?: QuietHoursSettings;
123
+ /** Переопределение ссылки на дашборд; пусто — порт берётся у сервера. */
124
+ dashboardUrl?: string;
76
125
  /** Шаблоны сообщений. */
77
126
  templates?: NotificationTemplates;
78
127
  /** Фильтры по задачам. */
@@ -129,6 +178,16 @@ export interface IntegrationSettings {
129
178
  hooks: HookSettings;
130
179
  }
131
180
 
181
+ /** Настройки журнала аудита (Спринт 26). */
182
+ export interface AuditSettings {
183
+ /** Вести журнал мутаций. */
184
+ enabled: boolean;
185
+ /** Сколько дней хранить записи; 0 — без ограничения по времени. */
186
+ retentionDays: number;
187
+ /** Максимум записей; старые удаляются первыми. */
188
+ maxRecords: number;
189
+ }
190
+
132
191
  /**
133
192
  * Глобальные настройки плагина, которые меняются из GUI.
134
193
  * Хранятся в settings.json рядом с tasks.json / history.json.
@@ -144,6 +203,8 @@ export interface SchedulerSettings {
144
203
  history: HistorySettings;
145
204
  /** Внешние интеграции: входящие webhook-триггеры. */
146
205
  integrations: IntegrationSettings;
206
+ /** Журнал аудита мутаций (Спринт 26). */
207
+ audit: AuditSettings;
147
208
  }
148
209
 
149
210
  export const SETTINGS_FILE = path.join(PLUGIN_DIR, "settings.json");
@@ -164,6 +225,38 @@ export const DEFAULT_HOOK_TIMESTAMP_TOLERANCE_SECONDS = 300;
164
225
  const MAX_HOOK_BODY_BYTES = 5 * 1024 * 1024;
165
226
  const MAX_HOOK_CREDENTIAL_LENGTH = 512;
166
227
 
228
+ /** Аудит (Спринт 26): включён, 90 дней и не больше 10 000 записей. */
229
+ export const DEFAULT_AUDIT_RETENTION_DAYS = 90;
230
+ export const DEFAULT_AUDIT_MAX_RECORDS = 10_000;
231
+
232
+ /** Значения аудита по умолчанию. */
233
+ export function defaultAuditSettings(): AuditSettings {
234
+ return {
235
+ enabled: true,
236
+ retentionDays: DEFAULT_AUDIT_RETENTION_DAYS,
237
+ maxRecords: DEFAULT_AUDIT_MAX_RECORDS,
238
+ };
239
+ }
240
+
241
+ /** Приводит настройки аудита к безопасному виду. */
242
+ function normalizeAuditSettings(
243
+ value: unknown,
244
+ fallback: AuditSettings
245
+ ): AuditSettings {
246
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
247
+ return { ...fallback };
248
+ }
249
+ const raw = value as Partial<AuditSettings>;
250
+ return {
251
+ enabled: typeof raw.enabled === "boolean" ? raw.enabled : fallback.enabled,
252
+ retentionDays: normalizeRetentionLimit(
253
+ raw.retentionDays,
254
+ fallback.retentionDays
255
+ ),
256
+ maxRecords: normalizeRetentionLimit(raw.maxRecords, fallback.maxRecords),
257
+ };
258
+ }
259
+
167
260
  /** Значения интеграций по умолчанию: хуки выключены, подпись обязательна. */
168
261
  export function defaultIntegrations(): IntegrationSettings {
169
262
  return {
@@ -241,10 +334,30 @@ export function defaultNotifications(): NotificationSettings {
241
334
  retryDelayMs: DEFAULT_WEBHOOK_RETRY_DELAY_MS,
242
335
  },
243
336
  templates: {
244
- success: '✅ Задача "{task}" выполнена ({duration})',
245
- error: '❌ Задача "{task}" упала ({duration}){error}',
337
+ success: '✅ Задача "{task}" выполнена ({duration}){cost}',
338
+ error: '❌ Задача "{task}" упала ({duration}){error}{cost}',
246
339
  },
247
340
  filters: { include: [], exclude: [] },
341
+ telegram: {
342
+ enabled: false,
343
+ botToken: "",
344
+ chatId: "",
345
+ parseMode: "HTML",
346
+ disableNotification: false,
347
+ messageThreadId: null,
348
+ includeDashboardLink: true,
349
+ apiBase: "https://api.telegram.org",
350
+ },
351
+ native: {
352
+ enabled: false,
353
+ sound: true,
354
+ },
355
+ quietHours: {
356
+ enabled: false,
357
+ from: "22:00",
358
+ to: "08:00",
359
+ },
360
+ dashboardUrl: "",
248
361
  matrix: {
249
362
  enabled: true,
250
363
  onPartial: true,
@@ -311,6 +424,30 @@ function asRecord(value: unknown): Record<string, unknown> | undefined {
311
424
  : undefined;
312
425
  }
313
426
 
427
+ /** Приводит parse_mode Telegram к допустимому значению. */
428
+ function normalizeTelegramParseMode(
429
+ value: unknown,
430
+ fallback: TelegramParseMode
431
+ ): TelegramParseMode {
432
+ return value === "" || value === "HTML" || value === "Markdown" || value === "MarkdownV2"
433
+ ? value
434
+ : fallback;
435
+ }
436
+
437
+ /** Проверяет http(s)-базу API; иначе возвращает fallback. */
438
+ function normalizeHttpBase(value: unknown, fallback: string): string {
439
+ if (typeof value !== "string") return fallback;
440
+ const trimmed = value.trim().replace(/\/+$/, "");
441
+ if (!trimmed) return fallback;
442
+ try {
443
+ const parsed = new URL(trimmed);
444
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return fallback;
445
+ return trimmed;
446
+ } catch {
447
+ return fallback;
448
+ }
449
+ }
450
+
314
451
  /** Приводит настройки уведомлений к безопасному виду. */
315
452
  function normalizeNotifications(
316
453
  value: unknown,
@@ -321,6 +458,9 @@ function normalizeNotifications(
321
458
  const fallbackFilters = fallback.filters ?? { include: [], exclude: [] };
322
459
  const fallbackMatrix = fallback.matrix ?? defaultNotifications().matrix!;
323
460
  const fallbackDigest = fallback.digest ?? defaultNotifications().digest!;
461
+ const fallbackTelegram = fallback.telegram ?? defaultNotifications().telegram!;
462
+ const fallbackNative = fallback.native ?? defaultNotifications().native!;
463
+ const fallbackQuiet = fallback.quietHours ?? defaultNotifications().quietHours!;
324
464
 
325
465
  const raw = asRecord(value);
326
466
  if (!raw) {
@@ -334,6 +474,10 @@ function normalizeNotifications(
334
474
  },
335
475
  matrix: { ...fallbackMatrix },
336
476
  digest: { ...fallbackDigest },
477
+ telegram: { ...fallbackTelegram },
478
+ native: { ...fallbackNative },
479
+ quietHours: { ...fallbackQuiet },
480
+ dashboardUrl: fallback.dashboardUrl ?? "",
337
481
  };
338
482
  }
339
483
 
@@ -342,6 +486,9 @@ function normalizeNotifications(
342
486
  const rawFilters = asRecord(raw.filters);
343
487
  const rawMatrix = asRecord(raw.matrix);
344
488
  const rawDigest = asRecord(raw.digest);
489
+ const rawTelegram = asRecord(raw.telegram);
490
+ const rawNative = asRecord(raw.native);
491
+ const rawQuiet = asRecord(raw.quietHours);
345
492
 
346
493
  const frequency: DigestFrequency =
347
494
  rawDigest?.frequency === "weekly" || rawDigest?.frequency === "daily"
@@ -399,6 +546,61 @@ function normalizeNotifications(
399
546
  include: normalizeNameList(rawFilters?.include, fallbackFilters.include),
400
547
  exclude: normalizeNameList(rawFilters?.exclude, fallbackFilters.exclude),
401
548
  },
549
+ telegram: {
550
+ enabled:
551
+ typeof rawTelegram?.enabled === "boolean"
552
+ ? rawTelegram.enabled
553
+ : fallbackTelegram.enabled,
554
+ botToken:
555
+ typeof rawTelegram?.botToken === "string"
556
+ ? rawTelegram.botToken.trim().slice(0, 512)
557
+ : fallbackTelegram.botToken,
558
+ chatId:
559
+ typeof rawTelegram?.chatId === "string"
560
+ ? rawTelegram.chatId.trim().slice(0, 128)
561
+ : fallbackTelegram.chatId,
562
+ parseMode: normalizeTelegramParseMode(
563
+ rawTelegram?.parseMode,
564
+ fallbackTelegram.parseMode
565
+ ),
566
+ disableNotification:
567
+ typeof rawTelegram?.disableNotification === "boolean"
568
+ ? rawTelegram.disableNotification
569
+ : fallbackTelegram.disableNotification,
570
+ messageThreadId:
571
+ rawTelegram?.messageThreadId === null
572
+ ? null
573
+ : Number.isFinite(Number(rawTelegram?.messageThreadId))
574
+ ? Math.max(0, Math.floor(Number(rawTelegram?.messageThreadId)))
575
+ : fallbackTelegram.messageThreadId,
576
+ includeDashboardLink:
577
+ typeof rawTelegram?.includeDashboardLink === "boolean"
578
+ ? rawTelegram.includeDashboardLink
579
+ : fallbackTelegram.includeDashboardLink,
580
+ apiBase: normalizeHttpBase(rawTelegram?.apiBase, fallbackTelegram.apiBase),
581
+ },
582
+ native: {
583
+ enabled:
584
+ typeof rawNative?.enabled === "boolean"
585
+ ? rawNative.enabled
586
+ : fallbackNative.enabled,
587
+ sound:
588
+ typeof rawNative?.sound === "boolean"
589
+ ? rawNative.sound
590
+ : fallbackNative.sound,
591
+ },
592
+ quietHours: {
593
+ enabled:
594
+ typeof rawQuiet?.enabled === "boolean"
595
+ ? rawQuiet.enabled
596
+ : fallbackQuiet.enabled,
597
+ from: normalizeDailyTime(rawQuiet?.from, fallbackQuiet.from),
598
+ to: normalizeDailyTime(rawQuiet?.to, fallbackQuiet.to),
599
+ },
600
+ dashboardUrl:
601
+ typeof raw.dashboardUrl === "string"
602
+ ? raw.dashboardUrl.trim().slice(0, 500)
603
+ : (fallback.dashboardUrl ?? ""),
402
604
  matrix: {
403
605
  enabled:
404
606
  typeof rawMatrix?.enabled === "boolean"
@@ -478,6 +680,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
478
680
  const fallbackNotifications = defaultNotifications();
479
681
  const fallbackHistory = defaultHistorySettings();
480
682
  const fallbackIntegrations = defaultIntegrations();
683
+ const fallbackAudit = defaultAuditSettings();
481
684
  try {
482
685
  const raw = await fs.readFile(SETTINGS_FILE, "utf8");
483
686
  const parsed = JSON.parse(raw) as Partial<SchedulerSettings> | null;
@@ -499,6 +702,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
499
702
  parsed?.integrations,
500
703
  fallbackIntegrations
501
704
  ),
705
+ audit: normalizeAuditSettings(parsed?.audit, fallbackAudit),
502
706
  };
503
707
  } catch {
504
708
  return {
@@ -507,6 +711,7 @@ export async function loadSettings(): Promise<SchedulerSettings> {
507
711
  notifications: fallbackNotifications,
508
712
  history: fallbackHistory,
509
713
  integrations: fallbackIntegrations,
714
+ audit: fallbackAudit,
510
715
  };
511
716
  }
512
717
  }
@@ -537,6 +742,10 @@ export async function saveSettings(
537
742
  patch.integrations !== undefined
538
743
  ? normalizeIntegrations(patch.integrations, current.integrations)
539
744
  : current.integrations,
745
+ audit:
746
+ patch.audit !== undefined
747
+ ? normalizeAuditSettings(patch.audit, current.audit)
748
+ : current.audit,
540
749
  };
541
750
 
542
751
  // Удобство: при включении хуков без явных учётных данных генерируем их,
package/src/workspaces.ts CHANGED
@@ -4,6 +4,7 @@ import { basename, join, resolve } from "node:path";
4
4
  import { spawnSync } from "node:child_process";
5
5
  import { getDb } from "./db/index.js";
6
6
  import { clearWorkspaceAssignments } from "./db/tasks-repo.js";
7
+ import { hasSecretRef, resolveSecretRefs } from "./core/secrets.js";
7
8
 
8
9
  /**
9
10
  * Multi-repo workspaces.
@@ -134,14 +135,23 @@ export function readWorkspaceEnvFile(envFile?: string): Record<string, string> {
134
135
 
135
136
  /**
136
137
  * Итоговые env-переменные workspace: сначала .env-файл, затем явные пары
137
- * (пары важнее файла). Никогда не бросает.
138
+ * (пары важнее файла). Ссылки `${secret:NAME}` разворачиваются из
139
+ * зашифрованного хранилища (Спринт 26); отсутствующий секрет даёт пустую
140
+ * строку и предупреждение с именем — без значения. Никогда не бросает.
138
141
  */
139
142
  export function resolveWorkspaceEnv(workspace: Workspace | undefined): Record<string, string> {
140
143
  if (!workspace) return {};
141
- return {
144
+ const merged = {
142
145
  ...readWorkspaceEnvFile(workspace.envFile),
143
146
  ...(workspace.env ?? {}),
144
147
  };
148
+ const resolved = resolveSecretRefs(merged);
149
+ if (resolved.missing.length > 0) {
150
+ console.warn(
151
+ `[workspace] "${workspace.name}": не найдены секреты: ${resolved.missing.join(", ")}`
152
+ );
153
+ }
154
+ return resolved.env;
145
155
  }
146
156
 
147
157
  /** Маскирует значение секрета для логов. */
@@ -151,12 +161,20 @@ export function maskSecretValue(): string {
151
161
 
152
162
  const SECRET_KEY_RE = /(TOKEN|SECRET|PASS|PASSWORD|KEY|CREDENTIAL|AUTH)/i;
153
163
 
154
- /** Копия env для логов: значения «секретных» ключей заменены на ***. */
164
+ /**
165
+ * Копия env для логов: значения «секретных» ключей заменены на ***.
166
+ * Чистые ссылки `${secret:NAME}` сохраняются как есть — это не секрет,
167
+ * а указатель, и он помогает диагностике (Спринт 26).
168
+ */
155
169
  export function maskEnvForLog(env: Record<string, string> | undefined): Record<string, string> {
156
170
  if (!env) return {};
157
171
  const masked: Record<string, string> = {};
158
172
  for (const [key, value] of Object.entries(env)) {
159
- masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
173
+ if (hasSecretRef(value)) {
174
+ masked[key] = String(value);
175
+ } else {
176
+ masked[key] = SECRET_KEY_RE.test(key) ? maskSecretValue() : value;
177
+ }
160
178
  }
161
179
  return masked;
162
180
  }