-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstatus.ts
More file actions
243 lines (205 loc) · 7.98 KB
/
Copy pathstatus.ts
File metadata and controls
243 lines (205 loc) · 7.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import {Flags} from '@oclif/core'
import {APICommand} from '../../index.js'
import {JsonObj} from '../../result.js'
import nameArg from '../../util/name-arg.js'
interface ConfigRule {
criteria?: Array<{operator: string}>
value?: Record<string, unknown>
}
interface ConfigEnvironment {
id: string
rules?: ConfigRule[]
}
interface StoredFlag {
default?: {rules?: ConfigRule[]}
environments?: ConfigEnvironment[]
key: string
readyForCleanup?: boolean
type: string
valueType: string
}
interface ConfigSparklineRow {
counts: number[]
days: string[]
environment: string
}
interface ConfigSparklinesResponse {
daysOfHistory: number
rows: ConfigSparklineRow[]
}
interface EnvSummary {
environment: string
evals_2d: number
evals_7d: number
evals_24h: number
evals_30d: number
last_eval: string | null
total: number
}
function startOfDayUtcMs(date: Date): number {
return Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate())
}
function formatRuleValue(value: Record<string, unknown> | undefined): string {
if (!value) return '(no value)'
// Old format: {type: 'bool', value: true}
if (typeof value.type === 'string' && value.value !== undefined) {
return String(value.value)
}
// New format: {bool: true} / {string: "..."} / etc.
for (const k of ['bool', 'string', 'int', 'double']) {
if (value[k] !== undefined) return String(value[k])
}
if (value.stringList !== undefined) {
return Array.isArray(value.stringList) ? value.stringList.join(',') : JSON.stringify(value.stringList)
}
if (value.json !== undefined) return JSON.stringify(value.json)
return JSON.stringify(value)
}
function summarizeRules(rules: ConfigRule[] | undefined): string {
if (!rules || rules.length === 0) return '[inherit default]'
const fallback = rules.find((r) => r.criteria && r.criteria.length === 1 && r.criteria[0].operator === 'ALWAYS_TRUE')
const overrides = rules.filter((r) => r !== fallback)
const fallbackStr = fallback ? formatRuleValue(fallback.value) : formatRuleValue(rules[0].value)
if (overrides.length === 0) return fallbackStr
return `${fallbackStr} (+${overrides.length} override rule${overrides.length === 1 ? '' : 's'})`
}
export default class CleanupStatus extends APICommand {
static args = {...nameArg}
static description = `Drill into one ready-for-cleanup flag — show telemetry across all environments and the current rule shape.
Use this after \`qfg cleanup list\` to inspect a specific flag before handing
removal off to the qfg-flag-cleanup Claude skill. The eval counts come from
analytics.configSparklines (the same backing data the per-flag sparklines on
the flag detail page use), summed into 24h/2d/7d/30d windows so you can decide
whether it's safe to retire.
Pass --json for the structured object including the full rule shape per
environment — the cleanup skill consumes this directly.`
static examples = [
'<%= config.bin %> <%= command.id %> my.flag.key',
'<%= config.bin %> <%= command.id %> my.flag.key --json',
]
static flags = {
json: Flags.boolean({default: false, description: 'Return structured object for agent consumption'}),
}
public async run(): Promise<JsonObj | void> {
const {args, flags} = await this.parse(CleanupStatus)
const key = args.name
if (!key) return this.err('Key is required: `qfg cleanup status <key>`')
const flagReq = await this.apiClient.post('/api/v1/metadata/getByKey', {workspaceId: this.workspaceId, key})
if (!flagReq.ok) {
const errorMsg = flagReq.error?.error || `Failed to fetch flag: ${flagReq.status}`
if (flagReq.status === 404) return this.err(`Flag ${key} not found`)
return this.err(errorMsg, {serverError: flagReq.error})
}
const flag = flagReq.json as unknown as StoredFlag
const sparkReq = await this.apiClient.post('/api/v1/analytics/configSparklines', {
workspaceId: this.workspaceId,
configKey: key,
})
if (!sparkReq.ok) {
return this.err(sparkReq.error?.error || `Failed to fetch sparklines: ${sparkReq.status}`)
}
const sparkResp = sparkReq.json as unknown as ConfigSparklinesResponse
const todayMs = startOfDayUtcMs(new Date())
const envSummaries: EnvSummary[] = []
let totalEvals24h = 0
let totalEvals2d = 0
let totalEvals7d = 0
let totalEvals30d = 0
let overallLast: number | null = null
for (const row of sparkResp.rows ?? []) {
let envTotal = 0
let envEvals24h = 0
let envEvals2d = 0
let envEvals7d = 0
let envEvals30d = 0
let envLastDayAgo: number | null = null
for (const [i, day] of row.days.entries()) {
const count = row.counts[i] ?? 0
if (count <= 0) continue
const dayMs = Date.parse(`${day}T00:00:00Z`)
if (Number.isNaN(dayMs)) continue
const daysAgo = Math.round((todayMs - dayMs) / 86_400_000)
envTotal += count
if (daysAgo === 0) envEvals24h += count
if (daysAgo <= 1) envEvals2d += count
if (daysAgo <= 6) envEvals7d += count
if (daysAgo <= 29) envEvals30d += count
if (envLastDayAgo === null || daysAgo < envLastDayAgo) envLastDayAgo = daysAgo
}
const last_eval =
envLastDayAgo === null ? null : new Date(todayMs - envLastDayAgo * 86_400_000).toISOString().slice(0, 10)
envSummaries.push({
environment: row.environment,
total: envTotal,
evals_24h: envEvals24h,
evals_2d: envEvals2d,
evals_7d: envEvals7d,
evals_30d: envEvals30d,
last_eval,
})
totalEvals24h += envEvals24h
totalEvals2d += envEvals2d
totalEvals7d += envEvals7d
totalEvals30d += envEvals30d
if (envLastDayAgo !== null && (overallLast === null || envLastDayAgo < overallLast)) {
overallLast = envLastDayAgo
}
}
// Drop env summaries with zero evals so the human view stays terse; the
// --json output below includes the same array.
const nonEmptyEnvs = envSummaries.filter((e) => e.total > 0)
const overallLastEval =
overallLast === null ? null : new Date(todayMs - overallLast * 86_400_000).toISOString().slice(0, 10)
const defaultRulesSummary = summarizeRules(flag.default?.rules)
const envRules: Array<{environment: string; rules: string}> = (flag.environments ?? []).map((env) => ({
environment: env.id,
rules: summarizeRules(env.rules),
}))
const payload = {
key: flag.key,
type: flag.valueType,
readyForCleanup: flag.readyForCleanup === true,
defaultRule: defaultRulesSummary,
environmentRules: envRules,
evals: {
evals_24h: totalEvals24h,
evals_2d: totalEvals2d,
evals_7d: totalEvals7d,
evals_30d: totalEvals30d,
last_eval: overallLastEval,
},
environments: nonEmptyEnvs,
}
if (flags.json) {
this.log(this.toSuccessJson(payload))
return payload as unknown as JsonObj
}
this.log(`${flag.key} (${flag.valueType})`)
this.log(` readyForCleanup: ${flag.readyForCleanup === true ? 'yes' : 'no'}`)
this.log(` default rule: ${defaultRulesSummary}`)
if (envRules.length > 0) {
this.log(' per-environment rules:')
for (const er of envRules) this.log(` - env ${er.environment}: ${er.rules}`)
}
this.log('')
this.log('Evaluations:')
this.log(` evals_24h: ${totalEvals24h}`)
this.log(` evals_2d: ${totalEvals2d}`)
this.log(` evals_7d: ${totalEvals7d}`)
this.log(` evals_30d: ${totalEvals30d}`)
this.log(` last_eval: ${overallLastEval ?? '-'}`)
if (nonEmptyEnvs.length > 0) {
this.log('')
this.log('Per-environment:')
for (const env of nonEmptyEnvs) {
this.log(
` ${env.environment}: total=${env.total} 24h=${env.evals_24h} 2d=${env.evals_2d} 7d=${env.evals_7d} 30d=${env.evals_30d} last=${env.last_eval ?? '-'}`,
)
}
} else {
this.log('')
this.log('No evaluations in the retained window — this flag looks quiet.')
}
return payload as unknown as JsonObj
}
}