@appeeky/spec 0.6.0 → 0.7.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.
package/dist/alerts.js ADDED
@@ -0,0 +1,469 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { existsSync } from "node:fs";
4
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { join } from "node:path";
6
+ import { readCategoryHistory, CHART_SIZE } from "./category.js";
7
+ import { competitorSlug, readChanges } from "./competitors.js";
8
+ import { SPEC_DIR } from "./files.js";
9
+ import { readReleases } from "./history.js";
10
+ import { collectLoops } from "./loops.js";
11
+ import { readReviews } from "./reviews.js";
12
+ import { ALERT_KINDS } from "./schema.js";
13
+ import { seoDir } from "./seo.js";
14
+ import { normalize } from "./text.js";
15
+ import { visibilityChangesFile } from "./visibility.js";
16
+ const DAY = 86_400_000;
17
+ const iso = (ms) => new Date(ms).toISOString().slice(0, 10);
18
+ const daysBefore = (now, n) => iso(now.getTime() - n * DAY);
19
+ const hash = (s) => createHash("sha1").update(s).digest("hex").slice(0, 10);
20
+ const where = (store) => (store === "app-store" ? "App Store" : "Google Play");
21
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
22
+ // ── Target ranks ────────────────────────────────────────────────────────────
23
+ /** Ranks newer than this are still news; older ones wait for the next check. */
24
+ export const RANK_FRESH_DAYS = 10;
25
+ /** Not ranked counts as just past the 200 results the stores return (same as verify). */
26
+ const UNRANKED = 201;
27
+ const asRank = (r) => (r === null || r === undefined ? UNRANKED : r);
28
+ const showRank = (r) => (r === null || r === undefined ? "not ranked" : `#${r}`);
29
+ /**
30
+ * Target ranks over time. Spec records them in the release files: the ranks right before
31
+ * each push (the baseline) and on its day-7 and day-14 checks. The last two observations of
32
+ * each target, on different days, show whether it fell.
33
+ */
34
+ export function rankDrops(project, releases, cfg, now) {
35
+ const targets = new Map();
36
+ for (const [country, list] of Object.entries(project.spec.targets))
37
+ targets.set(country, new Set(list.map((k) => normalize(k).trim())));
38
+ const series = new Map();
39
+ const add = (store, at, snapshot, release) => {
40
+ for (const [country, ranks] of Object.entries(snapshot))
41
+ for (const [keyword, rank] of Object.entries(ranks)) {
42
+ if (!targets.get(country)?.has(normalize(keyword).trim()))
43
+ continue;
44
+ const k = `${store}|${country}|${keyword}`;
45
+ series.set(k, [...(series.get(k) ?? []), { at, rank: rank ?? null, release }]);
46
+ }
47
+ };
48
+ for (const r of releases) {
49
+ if (r.baseline)
50
+ add(r.store, r.baseline.at, r.baseline.ranks, r.id);
51
+ for (const c of r.checks ?? [])
52
+ add(r.store, c.at, c.ranks, r.id);
53
+ }
54
+ const out = [];
55
+ for (const [k, list] of series) {
56
+ const sorted = [...list].sort((a, b) => a.at.localeCompare(b.at));
57
+ const last = sorted.at(-1);
58
+ if (now.getTime() - Date.parse(last.at) > RANK_FRESH_DAYS * DAY)
59
+ continue;
60
+ const prev = sorted.filter((o) => o.at.slice(0, 10) < last.at.slice(0, 10)).at(-1);
61
+ if (!prev || prev.rank === null)
62
+ continue;
63
+ const fell = asRank(last.rank) - prev.rank;
64
+ if (fell < cfg.places)
65
+ continue;
66
+ const [store, country, keyword] = k.split("|");
67
+ const critical = fell >= 2 * cfg.places || (prev.rank <= 10 && (last.rank === null || last.rank > 20));
68
+ out.push({
69
+ key: `rank-drop:${store}:${country}:${keyword}`,
70
+ kind: "rank-drop",
71
+ severity: critical ? "critical" : "warn",
72
+ title: `"${keyword}" fell ${last.rank === null ? "out of the results" : `${fell} places`} in ${country.toUpperCase()} on the ${where(store)}`,
73
+ numbers: `${showRank(prev.rank)} → ${showRank(last.rank)}`,
74
+ window: `${prev.at.slice(0, 10)} → ${last.at.slice(0, 10)}`,
75
+ source: `${SPEC_DIR}/releases/${last.release}.yaml`,
76
+ next: "Run `coverage` to see the target is still in the listing and read appeeky/competitors/changes.md for who climbed (skill appeeky-spec-review).",
77
+ });
78
+ }
79
+ return out;
80
+ }
81
+ // ── Releases ────────────────────────────────────────────────────────────────
82
+ /** A release whose latest check (day 7 or day 14) came out lost. */
83
+ export function lostReleases(releases, cfg, now) {
84
+ const out = [];
85
+ for (const r of releases) {
86
+ const last = r.checks?.at(-1);
87
+ if (!last || last.verdict !== "lost")
88
+ continue;
89
+ if (now.getTime() - Date.parse(last.at) > cfg.days * DAY)
90
+ continue;
91
+ const lost = last.regressions.slice(0, 3).map((m) => `"${m.keyword}" ${m.country.toUpperCase()} ${showRank(m.before)} → ${showRank(m.after)}`);
92
+ const counts = `${last.regressions.length} top-20 ${last.regressions.length === 1 ? "target" : "targets"} lost, ${last.improved.length} up, ${last.dropped.length} down`;
93
+ out.push({
94
+ key: `release-lost:${r.id}:day${last.day}`,
95
+ kind: "release-lost",
96
+ severity: "critical",
97
+ title: `Release ${r.id} lost on day ${last.day}${r.note ? ` (${r.note})` : ""}`,
98
+ numbers: last.decidedBy ? `decided by ${last.decidedBy.join(", ")}; ${counts}` : [counts, ...lost].join("; "),
99
+ window: `${r.pushedAt.slice(0, 10)} → ${last.at.slice(0, 10)}`,
100
+ source: `${SPEC_DIR}/releases/${r.id}.yaml`,
101
+ next: `A person decides: \`revert ${r.id}\`, then \`push\` (skill appeeky-spec-review).`,
102
+ });
103
+ }
104
+ return out;
105
+ }
106
+ // ── Category chart ──────────────────────────────────────────────────────────
107
+ /** The category rank on its latest recorded day against the average of the days before. */
108
+ export function categoryDrops(history, cfg, now) {
109
+ const out = [];
110
+ const groups = new Map();
111
+ for (const r of history)
112
+ groups.set(`${r.store}|${r.country}|${r.chart}`, [...(groups.get(`${r.store}|${r.country}|${r.chart}`) ?? []), r]);
113
+ const pos = (r) => r ?? CHART_SIZE + 1;
114
+ for (const [k, rows] of groups) {
115
+ const sorted = [...rows].sort((a, b) => a.date.localeCompare(b.date));
116
+ const last = sorted.at(-1);
117
+ if (last.date < daysBefore(now, 3))
118
+ continue;
119
+ const from = iso(Date.parse(last.date) - cfg.days * DAY);
120
+ const before = sorted.filter((r) => r.date >= from && r.date < last.date);
121
+ if (before.length < 2 || before.every((r) => r.rank === null))
122
+ continue;
123
+ const avg = before.reduce((n, r) => n + pos(r.rank), 0) / before.length;
124
+ const fell = Math.round(pos(last.rank) - avg);
125
+ if (fell < cfg.places)
126
+ continue;
127
+ const [store, country, chart] = k.split("|");
128
+ const critical = fell >= 2 * cfg.places || last.rank === null;
129
+ out.push({
130
+ key: `category-drop:${store}:${country}:${chart}`,
131
+ kind: "category-drop",
132
+ severity: critical ? "critical" : "warn",
133
+ title: `Category rank fell ${fell} places in ${country.toUpperCase()} (${where(store)} ${chart})`,
134
+ numbers: `${last.rank === null ? "out of the top 100" : `#${last.rank}`} on ${last.date}, average #${Math.round(avg)} over the ${plural(before.length, "day")} before`,
135
+ window: `${before[0].date} → ${last.date}`,
136
+ source: `${SPEC_DIR}/category.csv`,
137
+ next: "Look for the cause in appeeky/reviews/summary.md, appeeky/competitors/changes.md and `log` (skill appeeky-spec-visibility).",
138
+ });
139
+ }
140
+ return out;
141
+ }
142
+ // ── Reviews ─────────────────────────────────────────────────────────────────
143
+ /** More 1–2 star reviews in the last days than in the days before. */
144
+ export function lowRatingWaves(reviews, cfg, now) {
145
+ const out = [];
146
+ const t = now.getTime();
147
+ for (const store of ["app-store", "google-play"]) {
148
+ const low = reviews.filter((r) => r.store === store && r.rating <= 2);
149
+ const age = (r) => t - Date.parse(r.date);
150
+ const recent = low.filter((r) => age(r) >= 0 && age(r) < cfg.days * DAY);
151
+ const before = low.filter((r) => age(r) >= cfg.days * DAY && age(r) < 2 * cfg.days * DAY);
152
+ if (recent.length < cfg.min || recent.length < cfg.ratio * before.length)
153
+ continue;
154
+ const critical = recent.length >= 2 * cfg.min && recent.length >= 2 * cfg.ratio * before.length;
155
+ const versions = new Map();
156
+ for (const r of recent)
157
+ if (r.version)
158
+ versions.set(r.version, (versions.get(r.version) ?? 0) + 1);
159
+ const top = [...versions.entries()].sort((a, b) => b[1] - a[1])[0];
160
+ const unanswered = recent.filter((r) => !r.reply).length;
161
+ out.push({
162
+ key: `low-ratings:${store}`,
163
+ kind: "low-ratings",
164
+ severity: critical ? "critical" : "warn",
165
+ title: `A wave of 1–2 star reviews on ${where(store)}`,
166
+ numbers: `${recent.length} in the last ${plural(cfg.days, "day")}, ${before.length} in the ${plural(cfg.days, "day")} before; ${unanswered} unanswered${top && top[1] > 1 ? `; ${top[1]} on version ${top[0]}` : ""}`,
167
+ window: `${daysBefore(now, 2 * cfg.days)} → ${iso(t)}`,
168
+ source: `${SPEC_DIR}/reviews/${store}/`,
169
+ next: `Read them with \`reviews list --store ${store} --rating 1-2 --unanswered\` and draft answers with \`reviews reply\` (skill appeeky-spec-reviews).`,
170
+ });
171
+ }
172
+ return out;
173
+ }
174
+ // ── Competitors ─────────────────────────────────────────────────────────────
175
+ /** Competitor changes on your targets: a climb into the top 10, or a target put in its title. */
176
+ export function competitorMoves(changes, spec, cfg, now) {
177
+ const targets = [...new Set(Object.values(spec.targets).flat().map((k) => normalize(k).trim()))];
178
+ const out = [];
179
+ const since = daysBefore(now, cfg.days);
180
+ for (const ch of changes) {
181
+ if (ch.date < since)
182
+ continue;
183
+ const climb = ch.change.match(/now #(\d+) for "(.+?)"/);
184
+ const title = ch.change.match(/title "(.*)" → "(.*)"/);
185
+ let severity = null;
186
+ if (climb && targets.includes(normalize(climb[2]).trim()))
187
+ severity = Number(climb[1]) <= 3 ? "critical" : "warn";
188
+ else if (title) {
189
+ const [before, after] = [normalize(title[1]), normalize(title[2])];
190
+ if (targets.some((t) => after.includes(t) && !before.includes(t)))
191
+ severity = "warn";
192
+ }
193
+ if (!severity)
194
+ continue;
195
+ out.push({
196
+ key: `competitor-change:${ch.date}:${hash(`${ch.name}|${ch.change}`)}`,
197
+ kind: "competitor-change",
198
+ severity,
199
+ title: `${ch.name} moved on your targets`,
200
+ numbers: ch.change,
201
+ window: ch.date,
202
+ source: `${SPEC_DIR}/competitors/changes.md`,
203
+ next: `Read ${SPEC_DIR}/competitors/${competitorSlug({ name: ch.name })}.yaml: its listing and the searches it ranks for (skill appeeky-spec-competitors).`,
204
+ });
205
+ }
206
+ return out;
207
+ }
208
+ // ── AI visibility ───────────────────────────────────────────────────────────
209
+ /** Lines of appeeky/visibility/changes.md where the assistants stopped naming or citing the app. */
210
+ export async function readVisibilityChanges(root) {
211
+ const file = visibilityChangesFile(root);
212
+ if (!existsSync(file))
213
+ return [];
214
+ const out = [];
215
+ for (const line of (await readFile(file, "utf8")).split("\n")) {
216
+ const m = line.match(/^- (\d{4}-\d{2}-\d{2}) · ([A-Z]{2}) · (.+)$/);
217
+ if (m)
218
+ out.push({ date: m[1], country: m[2].toLowerCase(), change: m[3] });
219
+ }
220
+ return out;
221
+ }
222
+ export function visibilityDrops(changes, cfg, now) {
223
+ const since = daysBefore(now, cfg.days);
224
+ const out = [];
225
+ for (const ch of changes) {
226
+ if (ch.date < since)
227
+ continue;
228
+ const down = /, down$/.test(ch.change);
229
+ const uncited = ch.change === "the assistants stopped citing your own site";
230
+ if (!down && !uncited)
231
+ continue;
232
+ const label = ch.change.match(/^"(.+?)":/)?.[1];
233
+ out.push({
234
+ key: `visibility-drop:${ch.date}:${ch.country}:${hash(ch.change)}`,
235
+ kind: "visibility-drop",
236
+ severity: /→ missing/.test(ch.change) ? "critical" : "warn",
237
+ title: uncited ? `AI assistants stopped citing your site in ${ch.country.toUpperCase()}` : `AI assistants name the app less for "${label ?? "an intent"}" in ${ch.country.toUpperCase()}`,
238
+ numbers: ch.change.replace(/, down$/, ""),
239
+ window: ch.date,
240
+ source: `${SPEC_DIR}/visibility/changes.md`,
241
+ next: `Read ${SPEC_DIR}/visibility/${ch.country}.yaml: who the assistants name instead and which pages they cite (skill appeeky-spec-visibility).`,
242
+ });
243
+ }
244
+ return out;
245
+ }
246
+ // ── Search Console ──────────────────────────────────────────────────────────
247
+ /** Search Console data lags a few days; older than this, the file is not being refreshed. */
248
+ const SEARCH_FRESH_DAYS = 7;
249
+ export async function readSearchDaily(root) {
250
+ const file = join(seoDir(root), "daily.csv");
251
+ if (!existsSync(file))
252
+ return [];
253
+ return (await readFile(file, "utf8"))
254
+ .split("\n")
255
+ .slice(1)
256
+ .filter(Boolean)
257
+ .map((l) => {
258
+ const [date, clicks] = l.split(",");
259
+ return { date: date, clicks: Number(clicks) };
260
+ })
261
+ .filter((r) => Number.isFinite(r.clicks));
262
+ }
263
+ export function searchDrops(rows, cfg, now) {
264
+ const sorted = [...rows].sort((a, b) => a.date.localeCompare(b.date));
265
+ const last = sorted.at(-1);
266
+ if (!last || last.date < daysBefore(now, SEARCH_FRESH_DAYS))
267
+ return [];
268
+ const end = Date.parse(last.date);
269
+ const cut = iso(end - cfg.days * DAY);
270
+ const start = iso(end - 2 * cfg.days * DAY);
271
+ const recent = sorted.filter((r) => r.date > cut);
272
+ const before = sorted.filter((r) => r.date > start && r.date <= cut);
273
+ // Half a window or less on either side is too little to compare.
274
+ if (recent.length * 2 <= cfg.days || before.length * 2 <= cfg.days)
275
+ return [];
276
+ const sum = (xs) => xs.reduce((n, r) => n + r.clicks, 0);
277
+ // Compare per day, so a missing day does not look like a drop.
278
+ const a = sum(recent) / recent.length;
279
+ const b = sum(before) / before.length;
280
+ if (sum(before) < cfg.min || b === 0)
281
+ return [];
282
+ const drop = 1 - a / b;
283
+ if (drop < cfg.drop)
284
+ return [];
285
+ return [
286
+ {
287
+ key: "search-drop",
288
+ kind: "search-drop",
289
+ severity: drop >= Math.min(1, 2 * cfg.drop) ? "critical" : "warn",
290
+ title: `Google search clicks fell ${Math.round(drop * 100)}%`,
291
+ numbers: `${sum(recent)} clicks in ${plural(recent.length, "day")} to ${last.date} (${a.toFixed(1)}/day), ${sum(before)} in the ${plural(before.length, "day")} before (${b.toFixed(1)}/day)`,
292
+ window: `${before[0].date} → ${last.date}`,
293
+ source: `${SPEC_DIR}/seo/daily.csv`,
294
+ next: "Read appeeky/seo/summary.md for the queries and pages that fell, and run `seo check` (skill appeeky-spec-seo).",
295
+ },
296
+ ];
297
+ }
298
+ // ── Late checks ─────────────────────────────────────────────────────────────
299
+ export function lateChecks(loops, cfg, now) {
300
+ const out = [];
301
+ for (const l of loops) {
302
+ if (l.state === "closed" || !l.nextCheck)
303
+ continue;
304
+ const late = Math.floor((now.getTime() - Date.parse(l.nextCheck)) / DAY);
305
+ if (late < cfg.days)
306
+ continue;
307
+ out.push({
308
+ key: `late-check:${l.id}:${l.nextCheck}`,
309
+ kind: "late-check",
310
+ severity: late >= 7 ? "critical" : "warn",
311
+ title: `The ${l.kind} check for ${l.id} is ${plural(late, "day")} late`,
312
+ numbers: `due ${l.nextCheck}, no result yet (${l.what})`,
313
+ window: `${l.nextCheck} → ${iso(now.getTime())}`,
314
+ source: `${SPEC_DIR}/loops.md`,
315
+ next: l.kind === "release"
316
+ ? "Run `verify`. A check this late usually means the daily run stopped or lost a key: run `doctor` (skill appeeky-spec-automation)."
317
+ : `Run \`verify\`, or record the result with \`experiment close ${l.id} --value <n>\` (skill appeeky-spec-experiments).`,
318
+ });
319
+ }
320
+ return out;
321
+ }
322
+ // ── All of them ─────────────────────────────────────────────────────────────
323
+ const SEVERITY_ORDER = { critical: 0, warn: 1 };
324
+ /** Every alert the repo's files show today, critical first. Kinds under `alerts.off` are left out. */
325
+ export async function collectAlerts(project, now = new Date()) {
326
+ const cfg = project.spec.alerts;
327
+ const on = (k) => !cfg.off.includes(k);
328
+ const root = project.root;
329
+ const releases = on("rank-drop") || on("release-lost") ? await readReleases(root) : [];
330
+ const out = [
331
+ ...(on("rank-drop") ? rankDrops(project, releases, cfg["rank-drop"], now) : []),
332
+ ...(on("release-lost") ? lostReleases(releases, cfg["release-lost"], now) : []),
333
+ ...(on("category-drop") ? categoryDrops(await readCategoryHistory(root), cfg["category-drop"], now) : []),
334
+ ...(on("low-ratings") ? lowRatingWaves(await readReviews(root), cfg["low-ratings"], now) : []),
335
+ ...(on("competitor-change") ? competitorMoves(await readChanges(root), project.spec, cfg["competitor-change"], now) : []),
336
+ ...(on("visibility-drop") ? visibilityDrops(await readVisibilityChanges(root), cfg["visibility-drop"], now) : []),
337
+ ...(on("search-drop") ? searchDrops(await readSearchDaily(root), cfg["search-drop"], now) : []),
338
+ ...(on("late-check") ? lateChecks(await collectLoops(root, now), cfg["late-check"], now) : []),
339
+ ];
340
+ return out.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || ALERT_KINDS.indexOf(a.kind) - ALERT_KINDS.indexOf(b.kind));
341
+ }
342
+ export const alertStateFile = (root) => join(root, SPEC_DIR, "alerts.json");
343
+ export async function readAlertState(root) {
344
+ try {
345
+ const raw = JSON.parse(await readFile(alertStateFile(root), "utf8"));
346
+ return { open: raw.open ?? {} };
347
+ }
348
+ catch {
349
+ return { open: {} };
350
+ }
351
+ }
352
+ /** Mark each alert new when it was not recorded yet, or was recorded as a warning and is now critical. */
353
+ export function markNew(alerts, state) {
354
+ return alerts.map((a) => {
355
+ const seen = state.open[a.key];
356
+ return { ...a, new: !seen || (seen.severity === "warn" && a.severity === "critical") };
357
+ });
358
+ }
359
+ /** The state after this run: the open alerts, each with the day it was first seen. Cleared ones are dropped. */
360
+ export function nextAlertState(alerts, state, now = new Date()) {
361
+ const open = {};
362
+ for (const a of [...alerts].sort((x, y) => x.key.localeCompare(y.key)))
363
+ open[a.key] = { kind: a.kind, severity: a.severity, since: state.open[a.key]?.since ?? iso(now.getTime()) };
364
+ return { open };
365
+ }
366
+ /** Write appeeky/alerts.json; only when something changed, so a quiet day makes no commit. */
367
+ export async function writeAlertState(root, state) {
368
+ const file = alertStateFile(root);
369
+ const body = `${JSON.stringify({ about: "Written by `appeeky-spec alerts --record`: the alerts already reported, so the daily run reports each one once.", ...state }, null, 2)}\n`;
370
+ const old = existsSync(file) ? await readFile(file, "utf8") : "";
371
+ if (old === body)
372
+ return false;
373
+ await mkdir(join(root, SPEC_DIR), { recursive: true });
374
+ await writeFile(file, body);
375
+ return true;
376
+ }
377
+ // ── Output ──────────────────────────────────────────────────────────────────
378
+ export const ALERT_LABEL = "appeeky-spec-alert";
379
+ export const ISSUE_TITLE = "Appeeky Spec alerts";
380
+ const count = (alerts) => {
381
+ const critical = alerts.filter((a) => a.severity === "critical").length;
382
+ return `${plural(alerts.length, "alert")}${critical ? ` (${critical} critical)` : ""}`;
383
+ };
384
+ /** Markdown for the issue body (or a comment with the new ones). Empty when there is nothing. */
385
+ export function alertsMarkdown(alerts, appName, now = new Date(), heading = "Needs attention") {
386
+ if (alerts.length === 0)
387
+ return "";
388
+ const lines = [`## ${heading}: ${appName}`, "", `${count(alerts)} on ${iso(now.getTime())}, from the files the daily run wrote.`, ""];
389
+ for (const a of alerts) {
390
+ lines.push(`- **${a.severity === "critical" ? "Critical" : "Warning"}${a.new ? ", new" : ""}: ${a.title}**`);
391
+ lines.push(` ${a.numbers} · ${a.window} · \`${a.source}\``);
392
+ lines.push(` Next: ${a.next}`);
393
+ }
394
+ lines.push("", "Written by `appeeky-spec alerts`. This issue is updated by the daily run and closed when nothing is left; set thresholds or turn kinds off under `alerts:` in appeeky.spec.yaml.");
395
+ return lines.join("\n") + "\n";
396
+ }
397
+ /** Plain text with Slack-style bold, for a webhook. */
398
+ export function alertsText(alerts, appName, link) {
399
+ const lines = [`*Appeeky Spec · ${appName}*: ${count(alerts)}`];
400
+ for (const a of alerts)
401
+ lines.push(`• ${a.severity === "critical" ? "*CRITICAL*" : "warning"}: ${a.title}. ${a.numbers} (${a.window}, ${a.source}). Next: ${a.next.replace(/`/g, "")}`);
402
+ if (link)
403
+ lines.push(link);
404
+ return lines.join("\n");
405
+ }
406
+ /** Post `{ text }` to a Slack-compatible incoming webhook. */
407
+ export async function postWebhook(url, text, fetcher = fetch) {
408
+ const res = await fetcher(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }) });
409
+ if (!res.ok)
410
+ throw new Error(`The alert webhook answered ${res.status}. Check ALERT_WEBHOOK_URL.`);
411
+ }
412
+ // ── The GitHub issue ────────────────────────────────────────────────────────
413
+ /** owner/repo from GITHUB_REPOSITORY, or from the origin remote when it is on github.com. */
414
+ export function githubRepo(root, env = process.env) {
415
+ if (env.GITHUB_REPOSITORY)
416
+ return env.GITHUB_REPOSITORY;
417
+ const r = spawnSync("git", ["remote", "get-url", "origin"], { cwd: root, encoding: "utf8" });
418
+ return parseGithubRepo(r.status === 0 ? r.stdout.trim() : "");
419
+ }
420
+ export function parseGithubRepo(url) {
421
+ const m = url.match(/github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/);
422
+ return m ? `${m[1]}/${m[2]}` : null;
423
+ }
424
+ /**
425
+ * One open issue labelled appeeky-spec-alert: created when alerts appear, its body replaced
426
+ * on each run (with a comment listing the new ones, so watchers are notified), closed when
427
+ * nothing is left.
428
+ */
429
+ export async function syncIssue(opts, body, newBody, fetcher = fetch) {
430
+ const base = `${(opts.api ?? "https://api.github.com").replace(/\/$/, "")}/repos/${opts.repo}`;
431
+ const call = async (method, path, data) => {
432
+ const res = await fetcher(`${base}${path}`, {
433
+ method,
434
+ headers: { Authorization: `Bearer ${opts.token}`, Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "appeeky-spec", ...(data ? { "Content-Type": "application/json" } : {}) },
435
+ ...(data ? { body: JSON.stringify(data) } : {}),
436
+ });
437
+ if (!res.ok) {
438
+ const hint = res.status === 403 || res.status === 404 ? ` The token needs Issues: Read and write on ${opts.repo}.` : "";
439
+ throw Object.assign(new Error(`GitHub answered ${res.status} for ${method} ${path}.${hint}`), { status: res.status });
440
+ }
441
+ return (res.status === 204 ? undefined : await res.json());
442
+ };
443
+ const open = (await call("GET", `/issues?state=open&labels=${ALERT_LABEL}&per_page=20`)).filter((i) => !i.pull_request);
444
+ const issue = open[0];
445
+ if (!body.trim()) {
446
+ if (!issue)
447
+ return { action: "none" };
448
+ await call("POST", `/issues/${issue.number}/comments`, { body: "Nothing needs attention any more. Closed by `appeeky-spec alerts`; it opens again when something does." });
449
+ await call("PATCH", `/issues/${issue.number}`, { state: "closed", state_reason: "completed" });
450
+ return { action: "closed", number: issue.number, url: issue.html_url };
451
+ }
452
+ if (issue) {
453
+ await call("PATCH", `/issues/${issue.number}`, { title: ISSUE_TITLE, body });
454
+ if (newBody.trim())
455
+ await call("POST", `/issues/${issue.number}/comments`, { body: newBody });
456
+ return { action: "updated", number: issue.number, url: issue.html_url };
457
+ }
458
+ try {
459
+ await call("POST", "/labels", { name: ALERT_LABEL, color: "d93f0b", description: "Appeeky Spec: something needs attention" });
460
+ }
461
+ catch (e) {
462
+ // 422: the label is there already.
463
+ if (e.status !== 422)
464
+ throw e;
465
+ }
466
+ const made = await call("POST", "/issues", { title: ISSUE_TITLE, body, labels: [ALERT_LABEL] });
467
+ return { action: "created", number: made.number, url: made.html_url };
468
+ }
469
+ //# sourceMappingURL=alerts.js.map
package/dist/cli.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { existsSync } from "node:fs";
3
3
  import { mkdir, readFile, writeFile } from "node:fs/promises";
4
- import { join, resolve } from "node:path";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { createInterface } from "node:readline/promises";
6
6
  import * as p from "@clack/prompts";
7
7
  import { Command, Option } from "commander";
8
8
  import { adsSnapshot, CHANNEL_LABELS, saveAdsSnapshot } from "./ads.js";
9
9
  import { COFOUNDER_COMMAND, installAgents, parseTargets, TARGET_DIRS } from "./agents.js";
10
10
  import { attributionClient, attributionClients, attributionMetricSource, createExperimentLink, hasClients, IOS_LINK_NOTE, iosOnlyLink, isClient, linkStore, linkValueReader } from "./attribution.js";
11
+ import { alertsMarkdown, alertsText, collectAlerts, githubRepo, markNew, nextAlertState, postWebhook, readAlertState, syncIssue, writeAlertState } from "./alerts.js";
11
12
  import { pullCompetitors, similarApps } from "./competitors.js";
12
13
  import { commentPlatform, deleteComment, draftIssues, fetchSocial, hideComment, likeComment, listComments, readAccounts, readDrafts, replyToComment, resolveAccounts, saveSocial, sendDraft } from "./social.js";
13
14
  import { fetchUgc, findPersona, generateBrief, quoteBrief, readBriefs, readPersonas, saveUgc } from "./ugc.js";
@@ -686,6 +687,74 @@ export function buildProgram() {
686
687
  console.log(c.dim(`\n${closed} closed. --all to see them.`));
687
688
  console.log(free.length ? `\n${c.green("Free to change:")} ${free.map(storeLabel).join(", ")}` : c.dim("\nEvery store has a release being measured: wait before the next change."));
688
689
  console.log(c.dim("Written to appeeky/loops.md."));
690
+ const open = await collectAlerts(project).catch(() => []);
691
+ if (open.length) {
692
+ const critical = open.filter((a) => a.severity === "critical").length;
693
+ console.log((critical ? c.red : c.yellow)(`${open.length} alert${open.length === 1 ? "" : "s"}${critical ? ` (${critical} critical)` : ""}: run \`appeeky-spec alerts\`.`));
694
+ }
695
+ });
696
+ program
697
+ .command("alerts")
698
+ .description("What needs attention, from the files the daily run wrote: target ranks, lost releases, the category chart, low ratings, competitors, AI visibility, Search Console clicks and late checks")
699
+ .option("--markdown", "Markdown, for an issue body (empty when nothing is open)", false)
700
+ .option("-o, --output <file>", "Write the output to a file instead (Markdown unless --json)")
701
+ .option("--new", "Only alerts not reported yet (see --record)", false)
702
+ .option("--record", "Remember the open alerts in appeeky/alerts.json, so the next run reports only new ones", false)
703
+ .option("--webhook [url]", "Post the new alerts as Slack-compatible JSON {text} (default: ALERT_WEBHOOK_URL)")
704
+ .option("--issue", "Open, update or close one GitHub issue labelled appeeky-spec-alert (GITHUB_TOKEN with Issues: write)", false)
705
+ .action(async (opts) => {
706
+ const project = await load();
707
+ const now = new Date();
708
+ const state = await readAlertState(project.root);
709
+ const alerts = markNew(await collectAlerts(project, now), state);
710
+ const fresh = alerts.filter((a) => a.new);
711
+ const shown = opts.new ? fresh : alerts;
712
+ const name = project.spec.app.name;
713
+ const md = alertsMarkdown(shown, name, now, opts.new ? "New" : "Needs attention");
714
+ // Delivery notes go to stderr, so --json and --markdown stay clean on stdout.
715
+ const note = (s) => (g().json || opts.markdown || opts.output ? console.error(s) : console.log(s));
716
+ if (opts.output)
717
+ await mkdir(dirname(resolve(opts.output)), { recursive: true });
718
+ if (opts.output)
719
+ await writeFile(opts.output, g().json ? `${JSON.stringify({ alerts: shown }, null, 2)}\n` : md);
720
+ else if (g().json)
721
+ printJson({ alerts: shown, open: alerts.length, new: fresh.length });
722
+ else if (opts.markdown)
723
+ process.stdout.write(md);
724
+ else
725
+ printAlerts(shown, opts.new);
726
+ let link;
727
+ if (opts.issue) {
728
+ const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
729
+ const repo = githubRepo(project.root);
730
+ if (!token || !repo)
731
+ note(c.yellow(`! No GitHub issue: ${!token ? "set GITHUB_TOKEN" : "the origin remote is not on github.com (set GITHUB_REPOSITORY=owner/repo)"}.`));
732
+ else {
733
+ try {
734
+ const r = await syncIssue({ repo, token, api: process.env.GITHUB_API_URL }, alertsMarkdown(alerts, name, now), alertsMarkdown(fresh, name, now, "New"));
735
+ link = r.url;
736
+ if (r.action !== "none")
737
+ note(`${c.green("✓")} Issue #${r.number} ${r.action}: ${r.url}`);
738
+ }
739
+ catch (e) {
740
+ // The issue always shows every open alert, so the next run catches up.
741
+ note(c.yellow(`! ${e.message}`));
742
+ process.exitCode = 1;
743
+ }
744
+ }
745
+ }
746
+ if (opts.webhook) {
747
+ const url = typeof opts.webhook === "string" ? opts.webhook : process.env.ALERT_WEBHOOK_URL;
748
+ if (!url)
749
+ throw new Error("Set ALERT_WEBHOOK_URL or pass --webhook <url>.");
750
+ // A failed post stops before --record, so the same alerts are posted on the next run.
751
+ if (fresh.length) {
752
+ await postWebhook(url, alertsText(fresh, name, link));
753
+ note(`${c.green("✓")} Posted ${fresh.length} new alert${fresh.length === 1 ? "" : "s"} to the webhook.`);
754
+ }
755
+ }
756
+ if (opts.record && (await writeAlertState(project.root, nextAlertState(alerts, state, now))))
757
+ note(c.dim("Recorded in appeeky/alerts.json."));
689
758
  });
690
759
  program
691
760
  .command("log")
@@ -2154,6 +2223,20 @@ export async function run(argv = process.argv) {
2154
2223
  process.exitCode = 1;
2155
2224
  }
2156
2225
  }
2226
+ function printAlerts(alerts, onlyNew) {
2227
+ if (alerts.length === 0) {
2228
+ console.log(c.green(onlyNew ? "Nothing new needs attention." : "Nothing needs attention."));
2229
+ return;
2230
+ }
2231
+ for (const a of alerts) {
2232
+ const tone = a.severity === "critical" ? c.red : c.yellow;
2233
+ console.log(`${tone(a.severity.padEnd(9))}${c.dim(a.kind.padEnd(18))}${c.bold(a.title)}${a.new ? c.cyan(" new") : ""}`);
2234
+ console.log(`${" ".repeat(27)}${a.numbers} ${c.dim(`${a.window} · ${a.source}`)}`);
2235
+ console.log(`${" ".repeat(27)}${c.dim("next")} ${a.next}`);
2236
+ }
2237
+ const fresh = alerts.filter((a) => a.new).length;
2238
+ console.log(c.dim(`\n${alerts.length} open${fresh ? `, ${fresh} new` : ""}. Thresholds and kinds to turn off: alerts: in appeeky.spec.yaml.`));
2239
+ }
2157
2240
  const STATE_TONE = { late: c.red, due: c.yellow, measuring: c.dim, closed: c.dim };
2158
2241
  function printLoop(l) {
2159
2242
  const state = STATE_TONE[l.state](l.state.padEnd(9));
@@ -50,7 +50,7 @@ export declare const experimentSchema: z.ZodObject<{
50
50
  /** Links, file paths, ad ids: whatever ran. */
51
51
  assets: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
52
52
  }, "strict", z.ZodTypeAny, {
53
- type: "ads" | "ugc" | "screenshots" | "pricing" | "other";
53
+ type: "ads" | "screenshots" | "ugc" | "pricing" | "other";
54
54
  status: "won" | "lost" | "running" | "inconclusive";
55
55
  id: string;
56
56
  hypothesis: string;
@@ -71,10 +71,10 @@ export declare const experimentSchema: z.ZodObject<{
71
71
  note?: string | undefined;
72
72
  } | undefined;
73
73
  persona?: string | undefined;
74
- target?: number | undefined;
75
74
  baseline?: number | undefined;
75
+ target?: number | undefined;
76
76
  }, {
77
- type: "ads" | "ugc" | "screenshots" | "pricing" | "other";
77
+ type: "ads" | "screenshots" | "ugc" | "pricing" | "other";
78
78
  id: string;
79
79
  hypothesis: string;
80
80
  metric: string;
@@ -93,8 +93,8 @@ export declare const experimentSchema: z.ZodObject<{
93
93
  note?: string | undefined;
94
94
  } | undefined;
95
95
  persona?: string | undefined;
96
- target?: number | undefined;
97
96
  baseline?: number | undefined;
97
+ target?: number | undefined;
98
98
  checkAfterDays?: number | undefined;
99
99
  assets?: string[] | undefined;
100
100
  }>;
package/dist/files.js CHANGED
@@ -98,9 +98,18 @@ export function stringifySpec(spec) {
98
98
  if (v === undefined || (Array.isArray(v) ? v.length === 0 : Object.keys(v).length === 0))
99
99
  delete clean[k];
100
100
  }
101
+ // Alert thresholds: only the ones that differ from the defaults are written.
102
+ if (clean.alerts && typeof clean.alerts === "object") {
103
+ const defaults = specFileSchema.shape.alerts.parse(undefined);
104
+ const own = Object.fromEntries(Object.entries(clean.alerts).filter(([k, v]) => v !== undefined && JSON.stringify(v) !== JSON.stringify(defaults[k])));
105
+ if (Object.keys(own).length)
106
+ clean.alerts = own;
107
+ else
108
+ delete clean.alerts;
109
+ }
101
110
  const doc = new YAML.Document(clean);
102
111
  doc.commentBefore =
103
- " Appeeky Spec: your app's store presence as a spec.\n Docs: https://github.com/appeeky/appeeky-spec";
112
+ " Appeeky Spec: your app's store presence as a spec.\n Docs: https://docs.appeeky.com/docs/spec";
104
113
  return doc.toString({ lineWidth: 0 });
105
114
  }
106
115
  export async function writeSpec(root, spec) {
package/dist/reviews.d.ts CHANGED
@@ -102,15 +102,15 @@ export declare const replySchema: z.ZodObject<{
102
102
  store: "app-store" | "google-play";
103
103
  id: string;
104
104
  text: string;
105
- sentAt?: string | undefined;
106
105
  review?: string | undefined;
106
+ sentAt?: string | undefined;
107
107
  }, {
108
108
  store: "app-store" | "google-play";
109
109
  id: string;
110
110
  text: string;
111
111
  status?: "draft" | "sent" | undefined;
112
- sentAt?: string | undefined;
113
112
  review?: string | undefined;
113
+ sentAt?: string | undefined;
114
114
  }>;
115
115
  export type Reply = z.infer<typeof replySchema>;
116
116
  export declare const repliesDir: (root: string) => string;