@switchbot/openapi-cli 3.1.1 → 3.2.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 (113) hide show
  1. package/README.md +3 -3
  2. package/dist/index.js +56945 -169
  3. package/dist/policy/schema/v0.2.json +1 -1
  4. package/package.json +3 -2
  5. package/dist/api/client.js +0 -235
  6. package/dist/auth.js +0 -20
  7. package/dist/commands/agent-bootstrap.js +0 -182
  8. package/dist/commands/auth.js +0 -354
  9. package/dist/commands/batch.js +0 -413
  10. package/dist/commands/cache.js +0 -126
  11. package/dist/commands/capabilities.js +0 -385
  12. package/dist/commands/catalog.js +0 -359
  13. package/dist/commands/completion.js +0 -385
  14. package/dist/commands/config.js +0 -376
  15. package/dist/commands/daemon.js +0 -410
  16. package/dist/commands/device-meta.js +0 -159
  17. package/dist/commands/devices.js +0 -948
  18. package/dist/commands/doctor.js +0 -1015
  19. package/dist/commands/events.js +0 -563
  20. package/dist/commands/expand.js +0 -130
  21. package/dist/commands/explain.js +0 -139
  22. package/dist/commands/health.js +0 -113
  23. package/dist/commands/history.js +0 -320
  24. package/dist/commands/identity.js +0 -59
  25. package/dist/commands/install.js +0 -246
  26. package/dist/commands/mcp.js +0 -2017
  27. package/dist/commands/plan.js +0 -653
  28. package/dist/commands/policy.js +0 -586
  29. package/dist/commands/quota.js +0 -78
  30. package/dist/commands/rules.js +0 -875
  31. package/dist/commands/scenes.js +0 -264
  32. package/dist/commands/schema.js +0 -177
  33. package/dist/commands/status-sync.js +0 -131
  34. package/dist/commands/uninstall.js +0 -237
  35. package/dist/commands/upgrade-check.js +0 -107
  36. package/dist/commands/watch.js +0 -194
  37. package/dist/commands/webhook.js +0 -182
  38. package/dist/config.js +0 -258
  39. package/dist/credentials/backends/file.js +0 -101
  40. package/dist/credentials/backends/linux.js +0 -129
  41. package/dist/credentials/backends/macos.js +0 -129
  42. package/dist/credentials/backends/windows.js +0 -215
  43. package/dist/credentials/keychain.js +0 -88
  44. package/dist/credentials/prime.js +0 -52
  45. package/dist/devices/cache.js +0 -293
  46. package/dist/devices/catalog.js +0 -767
  47. package/dist/devices/device-meta.js +0 -56
  48. package/dist/devices/history-agg.js +0 -138
  49. package/dist/devices/history-query.js +0 -181
  50. package/dist/devices/param-validator.js +0 -433
  51. package/dist/devices/resources.js +0 -270
  52. package/dist/install/default-steps.js +0 -257
  53. package/dist/install/preflight.js +0 -212
  54. package/dist/install/steps.js +0 -67
  55. package/dist/lib/command-keywords.js +0 -17
  56. package/dist/lib/daemon-state.js +0 -46
  57. package/dist/lib/destructive-mode.js +0 -12
  58. package/dist/lib/devices.js +0 -382
  59. package/dist/lib/idempotency.js +0 -106
  60. package/dist/lib/plan-store.js +0 -68
  61. package/dist/lib/request-context.js +0 -12
  62. package/dist/lib/scenes.js +0 -10
  63. package/dist/logger.js +0 -16
  64. package/dist/mcp/device-history.js +0 -145
  65. package/dist/mcp/events-subscription.js +0 -213
  66. package/dist/mqtt/client.js +0 -180
  67. package/dist/mqtt/credential.js +0 -30
  68. package/dist/policy/add-rule.js +0 -124
  69. package/dist/policy/diff.js +0 -91
  70. package/dist/policy/format.js +0 -57
  71. package/dist/policy/load.js +0 -61
  72. package/dist/policy/migrate.js +0 -67
  73. package/dist/policy/schema.js +0 -18
  74. package/dist/policy/validate.js +0 -262
  75. package/dist/rules/action.js +0 -216
  76. package/dist/rules/audit-query.js +0 -89
  77. package/dist/rules/conflict-analyzer.js +0 -214
  78. package/dist/rules/cron-scheduler.js +0 -186
  79. package/dist/rules/destructive.js +0 -52
  80. package/dist/rules/engine.js +0 -757
  81. package/dist/rules/matcher.js +0 -230
  82. package/dist/rules/pid-file.js +0 -95
  83. package/dist/rules/quiet-hours.js +0 -45
  84. package/dist/rules/suggest.js +0 -95
  85. package/dist/rules/throttle.js +0 -116
  86. package/dist/rules/types.js +0 -34
  87. package/dist/rules/webhook-listener.js +0 -223
  88. package/dist/rules/webhook-token.js +0 -90
  89. package/dist/schema/field-aliases.js +0 -131
  90. package/dist/sinks/dispatcher.js +0 -12
  91. package/dist/sinks/file.js +0 -19
  92. package/dist/sinks/format.js +0 -56
  93. package/dist/sinks/homeassistant.js +0 -44
  94. package/dist/sinks/openclaw.js +0 -33
  95. package/dist/sinks/stdout.js +0 -5
  96. package/dist/sinks/telegram.js +0 -28
  97. package/dist/sinks/types.js +0 -1
  98. package/dist/sinks/webhook.js +0 -22
  99. package/dist/status-sync/manager.js +0 -268
  100. package/dist/utils/arg-parsers.js +0 -66
  101. package/dist/utils/audit.js +0 -121
  102. package/dist/utils/filter.js +0 -189
  103. package/dist/utils/flags.js +0 -186
  104. package/dist/utils/format.js +0 -117
  105. package/dist/utils/health.js +0 -101
  106. package/dist/utils/help-json.js +0 -54
  107. package/dist/utils/name-resolver.js +0 -137
  108. package/dist/utils/output.js +0 -404
  109. package/dist/utils/quota.js +0 -227
  110. package/dist/utils/redact.js +0 -68
  111. package/dist/utils/retry.js +0 -140
  112. package/dist/utils/string.js +0 -22
  113. package/dist/version.js +0 -4
@@ -1,216 +0,0 @@
1
- /**
2
- * Rule action executor — the only place that calls into `executeCommand`
3
- * from the rules pipeline.
4
- *
5
- * Responsibilities:
6
- * 1. Parse the `command` string into a `{ deviceId, verb, parameter }`
7
- * tuple, rejecting shapes the PoC doesn't understand.
8
- * 2. Enforce the destructive-command blocklist as a second line of
9
- * defence (the validator should have caught it at load time — this
10
- * protects against hand-crafted engine inputs).
11
- * 3. Resolve `action.device` (alias or deviceId) into the `<id>`
12
- * slot.
13
- * 4. Branch on `dry_run`: dry-run writes audit with kind
14
- * `rule-fire-dry` and returns without touching the API.
15
- * 5. Live run delegates to `executeCommand`, then re-writes audit
16
- * with the rule-scoped kind + fireId so `rules tail` / `replay`
17
- * can correlate multi-action fires.
18
- */
19
- import { executeCommand } from '../lib/devices.js';
20
- import { writeAudit } from '../utils/audit.js';
21
- import { isDestructiveCommand } from './destructive.js';
22
- const DEVICES_COMMAND_RE = /^devices\s+command\s+(\S+)\s+(\S+)(?:\s+(.*))?$/;
23
- export function parseRuleCommand(cmd) {
24
- const m = DEVICES_COMMAND_RE.exec(cmd.trim());
25
- if (!m)
26
- return null;
27
- const deviceIdSlot = m[1];
28
- const verb = m[2];
29
- const rest = (m[3] ?? '').trim();
30
- return {
31
- deviceIdSlot,
32
- verb,
33
- parameterTokens: rest.length === 0 ? [] : rest.split(/\s+/),
34
- };
35
- }
36
- /** Alias-first resolver — falls back to the raw value (assumed deviceId). */
37
- export function resolveActionDevice(explicit, slot, aliases) {
38
- // Explicit device field on the action wins.
39
- const candidate = explicit ?? (slot && slot !== '<id>' ? slot : null);
40
- if (!candidate)
41
- return null;
42
- if (aliases[candidate])
43
- return aliases[candidate];
44
- return candidate;
45
- }
46
- /**
47
- * Render a parameter for SwitchBot's command API. For the PoC we pass
48
- * the raw token string for single-token args, join with `:` for
49
- * multi-token args (matches the CLI's `devices command` convention),
50
- * and `undefined` when no tokens were supplied (the SDK substitutes
51
- * `'default'`).
52
- */
53
- function renderParameter(tokens) {
54
- if (tokens.length === 0)
55
- return undefined;
56
- if (tokens.length === 1)
57
- return tokens[0];
58
- return tokens.join(':');
59
- }
60
- export async function executeRuleAction(action, ctx) {
61
- const parsed = parseRuleCommand(action.command);
62
- if (!parsed) {
63
- writeAudit({
64
- t: new Date().toISOString(),
65
- kind: 'rule-fire',
66
- deviceId: 'unknown',
67
- command: action.command,
68
- parameter: null,
69
- commandType: 'command',
70
- dryRun: true,
71
- result: 'error',
72
- error: 'unparseable-command',
73
- rule: {
74
- name: ctx.rule.name,
75
- triggerSource: ctx.rule.when.source,
76
- fireId: ctx.fireId,
77
- reason: 'unparseable-command',
78
- },
79
- });
80
- return { ok: false, error: 'unparseable-command', blocked: true };
81
- }
82
- if (isDestructiveCommand(action.command)) {
83
- writeAudit({
84
- t: new Date().toISOString(),
85
- kind: 'rule-fire',
86
- deviceId: resolveActionDevice(action.device, parsed.deviceIdSlot, ctx.aliases) ?? 'unknown',
87
- command: action.command,
88
- parameter: null,
89
- commandType: 'command',
90
- dryRun: true,
91
- result: 'error',
92
- error: `destructive-verb:${parsed.verb}`,
93
- rule: {
94
- name: ctx.rule.name,
95
- triggerSource: ctx.rule.when.source,
96
- fireId: ctx.fireId,
97
- reason: `destructive verb "${parsed.verb}" refused at runtime`,
98
- },
99
- });
100
- return { ok: false, error: `destructive-verb:${parsed.verb}`, blocked: true, verb: parsed.verb };
101
- }
102
- const deviceId = resolveActionDevice(action.device, parsed.deviceIdSlot, ctx.aliases);
103
- if (!deviceId || deviceId === '<id>') {
104
- writeAudit({
105
- t: new Date().toISOString(),
106
- kind: 'rule-fire',
107
- deviceId: 'unknown',
108
- command: action.command,
109
- parameter: null,
110
- commandType: 'command',
111
- dryRun: true,
112
- result: 'error',
113
- error: 'missing-device',
114
- rule: {
115
- name: ctx.rule.name,
116
- triggerSource: ctx.rule.when.source,
117
- fireId: ctx.fireId,
118
- reason: 'action omitted `device` and command used `<id>` placeholder',
119
- },
120
- });
121
- return { ok: false, error: 'missing-device', verb: parsed.verb };
122
- }
123
- const dryRun = ctx.globalDryRun === true || ctx.rule.dry_run === true;
124
- const parameter = renderParameter(parsed.parameterTokens);
125
- if (dryRun) {
126
- writeAudit({
127
- t: new Date().toISOString(),
128
- kind: 'rule-fire-dry',
129
- deviceId,
130
- command: parsed.verb,
131
- parameter: parameter ?? 'default',
132
- commandType: 'command',
133
- dryRun: true,
134
- result: 'ok',
135
- rule: {
136
- name: ctx.rule.name,
137
- triggerSource: ctx.rule.when.source,
138
- matchedDevice: deviceId,
139
- fireId: ctx.fireId,
140
- },
141
- });
142
- return { ok: true, dryRun: true, deviceId, verb: parsed.verb };
143
- }
144
- if (ctx.skipApiCall) {
145
- writeAudit({
146
- t: new Date().toISOString(),
147
- kind: 'rule-fire',
148
- deviceId,
149
- command: parsed.verb,
150
- parameter: parameter ?? 'default',
151
- commandType: 'command',
152
- dryRun: false,
153
- result: 'ok',
154
- rule: {
155
- name: ctx.rule.name,
156
- triggerSource: ctx.rule.when.source,
157
- matchedDevice: deviceId,
158
- fireId: ctx.fireId,
159
- reason: 'api-skipped',
160
- },
161
- });
162
- return { ok: true, deviceId, verb: parsed.verb };
163
- }
164
- try {
165
- await executeCommand(deviceId, parsed.verb, parameter, 'command', ctx.httpClient);
166
- writeAudit({
167
- t: new Date().toISOString(),
168
- kind: 'rule-fire',
169
- deviceId,
170
- command: parsed.verb,
171
- parameter: parameter ?? 'default',
172
- commandType: 'command',
173
- dryRun: false,
174
- result: 'ok',
175
- rule: {
176
- name: ctx.rule.name,
177
- triggerSource: ctx.rule.when.source,
178
- matchedDevice: deviceId,
179
- fireId: ctx.fireId,
180
- },
181
- });
182
- return { ok: true, deviceId, verb: parsed.verb };
183
- }
184
- catch (err) {
185
- const msg = err instanceof Error ? err.message : String(err);
186
- writeAudit({
187
- t: new Date().toISOString(),
188
- kind: 'rule-fire',
189
- deviceId,
190
- command: parsed.verb,
191
- parameter: parameter ?? 'default',
192
- commandType: 'command',
193
- dryRun: false,
194
- result: 'error',
195
- error: msg,
196
- rule: {
197
- name: ctx.rule.name,
198
- triggerSource: ctx.rule.when.source,
199
- matchedDevice: deviceId,
200
- fireId: ctx.fireId,
201
- },
202
- });
203
- return { ok: false, error: msg, deviceId, verb: parsed.verb };
204
- }
205
- }
206
- /**
207
- * Extract the raw deviceId from an action object without alias resolution.
208
- * Prefers `action.device` over the deviceId embedded in the command string.
209
- * Use resolveActionDevice() when alias resolution is needed.
210
- */
211
- export function extractDeviceIdFromAction(action) {
212
- if (action.device)
213
- return action.device;
214
- const m = /\bdevices\s+command\s+(\S+)/.exec(action.command ?? '');
215
- return m ? m[1] : null;
216
- }
@@ -1,89 +0,0 @@
1
- /**
2
- * Shared filters + aggregations over the audit log for
3
- * `switchbot rules tail` and `switchbot rules replay`.
4
- *
5
- * All functions are pure — no I/O, no clock reads — so they can be
6
- * unit-tested with fixture arrays. The CLI entry points handle file
7
- * reading, `--follow` tailing, and human vs JSON rendering.
8
- */
9
- /** The subset of audit kinds the rules engine emits. */
10
- export const RULE_AUDIT_KINDS = [
11
- 'rule-fire',
12
- 'rule-fire-dry',
13
- 'rule-throttled',
14
- 'rule-webhook-rejected',
15
- ];
16
- /** Keep entries that are rule-engine emitted and match the filter. */
17
- export function filterRuleAudits(entries, filter = {}) {
18
- const kinds = new Set(filter.kinds ?? RULE_AUDIT_KINDS);
19
- const out = [];
20
- for (const e of entries) {
21
- if (!kinds.has(e.kind))
22
- continue;
23
- if (filter.sinceMs !== undefined) {
24
- const ms = Date.parse(e.t);
25
- if (!Number.isFinite(ms) || ms < filter.sinceMs)
26
- continue;
27
- }
28
- if (filter.ruleName !== undefined) {
29
- if (e.rule?.name !== filter.ruleName)
30
- continue;
31
- }
32
- out.push(e);
33
- }
34
- return out;
35
- }
36
- /** Aggregate a filtered stream into per-rule counters. */
37
- export function aggregateRuleAudits(entries) {
38
- const byRule = new Map();
39
- let webhookRejectedCount = 0;
40
- for (const e of entries) {
41
- if (e.kind === 'rule-webhook-rejected' && !e.rule) {
42
- webhookRejectedCount++;
43
- continue;
44
- }
45
- const name = e.rule?.name;
46
- if (!name)
47
- continue;
48
- let s = byRule.get(name);
49
- if (!s) {
50
- s = {
51
- rule: name,
52
- fires: 0,
53
- driesFires: 0,
54
- throttled: 0,
55
- errors: 0,
56
- errorRate: 0,
57
- firstAt: null,
58
- lastAt: null,
59
- triggerSource: null,
60
- };
61
- byRule.set(name, s);
62
- }
63
- if (e.kind === 'rule-fire')
64
- s.fires++;
65
- else if (e.kind === 'rule-fire-dry')
66
- s.driesFires++;
67
- else if (e.kind === 'rule-throttled')
68
- s.throttled++;
69
- if (e.result === 'error')
70
- s.errors++;
71
- if (!s.firstAt || e.t < s.firstAt)
72
- s.firstAt = e.t;
73
- if (!s.lastAt || e.t > s.lastAt)
74
- s.lastAt = e.t;
75
- const source = e.rule?.triggerSource;
76
- if (source) {
77
- if (s.triggerSource === null)
78
- s.triggerSource = source;
79
- else if (s.triggerSource !== source)
80
- s.triggerSource = 'mixed';
81
- }
82
- }
83
- for (const s of byRule.values()) {
84
- const denom = s.fires + s.driesFires;
85
- s.errorRate = denom === 0 ? 0 : s.errors / denom;
86
- }
87
- const summaries = [...byRule.values()].sort((a, b) => b.fires + b.driesFires - (a.fires + a.driesFires));
88
- return { total: entries.length, summaries, webhookRejectedCount };
89
- }
@@ -1,214 +0,0 @@
1
- /**
2
- * Static conflict analysis for automation rules.
3
- *
4
- * Detects patterns that are technically valid but likely to cause
5
- * operational problems:
6
- *
7
- * 1. Opposing-action pairs — same device, opposite commands (e.g.
8
- * turnOn / turnOff), triggered by the same source within a short
9
- * window and with no throttle on either rule.
10
- *
11
- * 2. High-frequency MQTT rules without throttle — rules that listen
12
- * on `device.shadow` (catch-all) with no throttle can fire on
13
- * every shadow push (up to once per second) and exhaust the daily
14
- * API quota quickly.
15
- *
16
- * 3. Potentially-destructive action without quiet-hours protection —
17
- * a rule that targets a destructive verb is technically blocked by
18
- * the engine, but we can still flag it early so users don't get a
19
- * surprise at runtime.
20
- *
21
- * Results are designed to be consumed by `rules doctor --json` and
22
- * by CI pipelines. Each finding carries a `severity` so callers can
23
- * decide how to gate on them.
24
- */
25
- import { isTimeBetween, isAllCondition, isAnyCondition, isNotCondition } from './types.js';
26
- import { parseMaxPerMs } from './throttle.js';
27
- import { isDestructiveCommand } from './destructive.js';
28
- import { extractDeviceIdFromAction } from './action.js';
29
- /** Known opposing command pairs (order-independent). */
30
- const OPPOSING_PAIRS = [
31
- ['turnOn', 'turnOff'],
32
- ['lock', 'unlock'],
33
- ['open', 'close'],
34
- ['openDoor', 'closeDoor'],
35
- ['openCurtain', 'closeCurtain'],
36
- ['turnOn', 'standby'],
37
- ['brightnessUp', 'brightnessDown'],
38
- ['volumeUp', 'volumeDown'],
39
- ['fanSpeedUp', 'fanSpeedDown'],
40
- ];
41
- /**
42
- * MQTT events that fire on every device state push and can rapidly exhaust
43
- * the daily API quota when a rule has no throttle.
44
- *
45
- * Conditional events like `motion.detected` are intentionally excluded —
46
- * they fire discretely, not at continuous high frequency. Extend this set
47
- * when new catch-all or near-continuous event types are added to the classifier.
48
- */
49
- export const HIGH_FREQ_EVENTS = ['device.shadow', '*'];
50
- /** Returns true when an MQTT event is known to fire at high frequency. */
51
- export function isHighFreqEvent(event) {
52
- return HIGH_FREQ_EVENTS.includes(event);
53
- }
54
- function commandsAreOpposing(a, b) {
55
- for (const [x, y] of OPPOSING_PAIRS) {
56
- if ((a === x && b === y) || (a === y && b === x))
57
- return true;
58
- }
59
- return false;
60
- }
61
- function extractCommandVerb(command) {
62
- // command strings are like "devices command <id> turnOn" — extract last token
63
- const parts = command.trim().split(/\s+/);
64
- return parts[parts.length - 1] ?? command;
65
- }
66
- function effectiveCooldownMs(rule) {
67
- if (rule.cooldown) {
68
- try {
69
- return parseMaxPerMs(rule.cooldown);
70
- }
71
- catch {
72
- return null;
73
- }
74
- }
75
- if (rule.throttle?.max_per) {
76
- try {
77
- return parseMaxPerMs(rule.throttle.max_per);
78
- }
79
- catch {
80
- return null;
81
- }
82
- }
83
- return null;
84
- }
85
- function hasTimeBetweenGuard(conditions) {
86
- if (!conditions)
87
- return false;
88
- for (const c of conditions) {
89
- if (isTimeBetween(c))
90
- return true;
91
- if (isAllCondition(c) && hasTimeBetweenGuard(c.all))
92
- return true;
93
- if (isAnyCondition(c) && hasTimeBetweenGuard(c.any))
94
- return true;
95
- if (isNotCondition(c) && hasTimeBetweenGuard([c.not]))
96
- return true;
97
- }
98
- return false;
99
- }
100
- export function analyzeConflicts(rules, quietHours) {
101
- const findings = [];
102
- const active = rules.filter((r) => r.enabled !== false);
103
- // 1. Opposing-action pairs on the same device
104
- for (let i = 0; i < active.length; i++) {
105
- for (let j = i + 1; j < active.length; j++) {
106
- const a = active[i];
107
- const b = active[j];
108
- // Only flag when they share the same trigger source (otherwise they
109
- // can't race each other in normal operation).
110
- if (a.when.source !== b.when.source)
111
- continue;
112
- const cooldownA = effectiveCooldownMs(a);
113
- const cooldownB = effectiveCooldownMs(b);
114
- // If both rules have meaningful cooldowns (≥ 5 minutes), the risk is
115
- // low — skip.
116
- const bothThrottled = cooldownA !== null && cooldownA >= 5 * 60_000 &&
117
- cooldownB !== null && cooldownB >= 5 * 60_000;
118
- if (bothThrottled)
119
- continue;
120
- for (const actionA of a.then) {
121
- for (const actionB of b.then) {
122
- const deviceA = extractDeviceIdFromAction(actionA);
123
- const deviceB = extractDeviceIdFromAction(actionB);
124
- // Skip if devices can't be compared.
125
- if (!deviceA || !deviceB || deviceA !== deviceB)
126
- continue;
127
- const verbA = extractCommandVerb(actionA.command);
128
- const verbB = extractCommandVerb(actionB.command);
129
- if (commandsAreOpposing(verbA, verbB)) {
130
- const noThrottle = cooldownA === null || cooldownB === null;
131
- findings.push({
132
- severity: noThrottle ? 'warning' : 'info',
133
- code: 'opposing-actions',
134
- message: `Rules "${a.name}" and "${b.name}" issue opposing commands (${verbA} / ${verbB}) on device "${deviceA}" via the same trigger source.`,
135
- rules: [a.name, b.name],
136
- hint: noThrottle
137
- ? 'Add a "cooldown" or "throttle.max_per" to both rules to prevent rapid state oscillation.'
138
- : undefined,
139
- });
140
- }
141
- }
142
- }
143
- }
144
- }
145
- // 2. High-frequency MQTT catch-all rules without throttle
146
- for (const rule of active) {
147
- if (rule.when.source !== 'mqtt')
148
- continue;
149
- const event = rule.when.event;
150
- const isHighFreq = isHighFreqEvent(event);
151
- if (!isHighFreq)
152
- continue;
153
- const cooldown = effectiveCooldownMs(rule);
154
- if (cooldown === null) {
155
- findings.push({
156
- severity: 'warning',
157
- code: 'high-frequency-no-throttle',
158
- message: `Rule "${rule.name}" listens on "${event}" (high-frequency catch-all) with no throttle/cooldown. This can rapidly exhaust the daily API quota.`,
159
- rules: [rule.name],
160
- hint: 'Add "cooldown: 1m" or "throttle: { max_per: 1m }" to rate-limit this rule.',
161
- });
162
- }
163
- else if (cooldown < 30_000) {
164
- findings.push({
165
- severity: 'info',
166
- code: 'high-frequency-low-throttle',
167
- message: `Rule "${rule.name}" listens on "${event}" with a throttle under 30 s. Consider increasing to at least 1 m to protect API quota.`,
168
- rules: [rule.name],
169
- });
170
- }
171
- }
172
- // 3. Destructive actions in rules (engine blocks these at runtime, but
173
- // surface early with clear guidance).
174
- for (const rule of active) {
175
- for (let i = 0; i < rule.then.length; i++) {
176
- const verb = extractCommandVerb(rule.then[i].command);
177
- if (isDestructiveCommand(verb)) {
178
- findings.push({
179
- severity: 'error',
180
- code: 'destructive-action-in-rule',
181
- message: `Rule "${rule.name}" then[${i}] contains destructive command "${verb}". The engine blocks this at runtime.`,
182
- rules: [rule.name],
183
- hint: 'Remove the destructive command or replace it with a non-destructive alternative.',
184
- });
185
- }
186
- }
187
- }
188
- // 4. Event-driven rules with no time_between guard when quiet_hours is defined.
189
- // Cron rules fire on an explicit schedule so their overlap with quiet hours
190
- // requires schedule analysis — flag those separately when needed.
191
- if (quietHours?.start && quietHours?.end) {
192
- for (const rule of active) {
193
- if (rule.when.source === 'cron')
194
- continue;
195
- if (!hasTimeBetweenGuard(rule.conditions)) {
196
- findings.push({
197
- severity: 'warning',
198
- code: 'no-quiet-hours-guard',
199
- message: `Rule "${rule.name}" (${rule.when.source} trigger) has no time_between condition and may fire during quiet hours (${quietHours.start}–${quietHours.end}).`,
200
- rules: [rule.name],
201
- hint: `Add a conditions entry "{ time_between: ['${quietHours.end}', '${quietHours.start}'] }" to block this rule during quiet hours.`,
202
- });
203
- }
204
- }
205
- }
206
- const counts = { error: 0, warning: 0, info: 0 };
207
- for (const f of findings)
208
- counts[f.severity]++;
209
- return {
210
- findings,
211
- counts,
212
- clean: counts.error === 0,
213
- };
214
- }