Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
ai-proactive-monitor.test.ts13.3 KB · 413 lines
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/**
 * Tests for the AI Proactive Monitor (`src/lib/ai-proactive-monitor.ts`).
 *
 * Uses the dependency-injection seams on `aiProactiveMonitorTick` so we
 * never touch the DB or the Anthropic API. The Claude call is mocked
 * with canned findings; the issue-create + dedupe + audit side-effects
 * are observed via spy fakes.
 *
 * Covers:
 *   - No-op when AI is unavailable.
 *   - Info-severity findings are filtered out before issue creation.
 *   - Warning + critical findings open issues with the proactive label.
 *   - Dedupe (sha256 of title) skips repeat findings within 24h.
 *   - Audit row is recorded for every considered finding.
 *   - Per-finding errors are isolated (one bad finding doesn't wedge the rest).
 *   - Hard cap on findings per tick (runaway protection).
 *   - Body renderer embeds the dedupe marker so the lookup query can match.
 */

import { describe, it, expect } from "bun:test";
import {
  aiProactiveMonitorTick,
  dedupeKeyForTitle,
  renderFindingBody,
  PROACTIVE_LABEL_NAME,
  PROACTIVE_LOOKBACK_HOURS,
  PROACTIVE_DEDUPE_MARKER_PREFIX,
  __test as monitorInternals,
  type ProactiveFinding,
  type ProactiveTelemetry,
} from "../lib/ai-proactive-monitor";

const EMPTY_TELEMETRY: ProactiveTelemetry = {
  auditLog: [],
  platformDeploys: [],
  workflowRuns: [],
};

const REPO = { repositoryId: "repo-self", ownerId: "owner-1" };

function finding(
  partial: Partial<ProactiveFinding> = {}
): ProactiveFinding {
  return {
    title: "Default finding",
    severity: "warning",
    body_markdown: "Something looks off.",
    target_url: null,
    ...partial,
  };
}

describe("ai-proactive-monitor — module surface", () => {
  it("exports the expected public functions + constants", () => {
    expect(typeof aiProactiveMonitorTick).toBe("function");
    expect(typeof dedupeKeyForTitle).toBe("function");
    expect(typeof renderFindingBody).toBe("function");
    expect(PROACTIVE_LABEL_NAME).toBe("ai:proactive-finding");
    expect(PROACTIVE_LOOKBACK_HOURS).toBe(24);
  });
});

describe("dedupeKeyForTitle", () => {
  it("produces a deterministic 32-char hex digest", () => {
    const k1 = dedupeKeyForTitle("memory growth on workflow-runner");
    const k2 = dedupeKeyForTitle("memory growth on workflow-runner");
    expect(k1).toBe(k2);
    expect(k1).toMatch(/^[0-9a-f]{32}$/);
  });

  it("is case-insensitive and trimmed", () => {
    expect(dedupeKeyForTitle("  Memory Growth  ")).toBe(
      dedupeKeyForTitle("memory growth")
    );
  });

  it("differs for different titles", () => {
    expect(dedupeKeyForTitle("a")).not.toBe(dedupeKeyForTitle("b"));
  });
});

describe("renderFindingBody", () => {
  it("embeds the dedupe marker so the LIKE lookup matches", () => {
    const f = finding({ title: "deploy times creeping up" });
    const key = dedupeKeyForTitle(f.title);
    const body = renderFindingBody(f, key);
    expect(body).toContain(`${PROACTIVE_DEDUPE_MARKER_PREFIX}${key}`);
    expect(body).toContain("warning");
    expect(body).toContain("Something looks off.");
  });

  it("uses the critical badge for critical findings", () => {
    const f = finding({ severity: "critical" });
    const body = renderFindingBody(f, "k");
    expect(body).toContain("critical");
  });

  it("includes the target URL when provided", () => {
    const f = finding({ target_url: "https://gluecron.com/admin/deploys" });
    const body = renderFindingBody(f, "k");
    expect(body).toContain("https://gluecron.com/admin/deploys");
  });
});

describe("aiProactiveMonitorTick — no-op paths", () => {
  it("returns zero summary when AI is unavailable", async () => {
    let askCalled = false;
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => false,
      askClaude: async () => {
        askCalled = true;
        return [];
      },
    });
    expect(askCalled).toBe(false);
    expect(summary).toEqual({
      considered: 0,
      opened: 0,
      skippedDedupe: 0,
      skippedSeverity: 0,
      errors: 0,
    });
  });

  it("returns early when the self-host repo cannot be resolved", async () => {
    let askCalled = false;
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => null,
      askClaude: async () => {
        askCalled = true;
        return [];
      },
    });
    expect(askCalled).toBe(false);
    expect(summary.opened).toBe(0);
  });

  it("returns a clean summary when Claude finds nothing", async () => {
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [],
      isDuplicate: async () => false,
      createFindingIssue: async () => 1,
      recordAudit: async () => {},
    });
    expect(summary).toEqual({
      considered: 0,
      opened: 0,
      skippedDedupe: 0,
      skippedSeverity: 0,
      errors: 0,
    });
  });
});

describe("aiProactiveMonitorTick — issue creation", () => {
  it("opens an issue per warning/critical finding and skips info-severity", async () => {
    const created: Array<{ title: string; body: string }> = [];
    const audited: Array<{ title: string; issueNumber: number | null }> = [];

    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [
        finding({ title: "Memory growth on workflow-runner", severity: "critical" }),
        finding({ title: "Deploy times creeping up", severity: "warning" }),
        finding({ title: "Just FYI: nothing wrong", severity: "info" }),
      ],
      isDuplicate: async () => false,
      createFindingIssue: async (args) => {
        created.push({ title: args.title, body: args.body });
        return created.length; // 1, 2, ...
      },
      recordAudit: async (f, _repo, n) => {
        audited.push({ title: f.title, issueNumber: n });
      },
    });

    expect(summary.considered).toBe(3);
    expect(summary.opened).toBe(2);
    expect(summary.skippedSeverity).toBe(1);
    expect(summary.skippedDedupe).toBe(0);
    expect(summary.errors).toBe(0);
    expect(created.map((c) => c.title)).toEqual([
      "Memory growth on workflow-runner",
      "Deploy times creeping up",
    ]);
    // Each created body must carry the dedupe marker so future ticks dedupe.
    for (const c of created) {
      const key = dedupeKeyForTitle(c.title);
      expect(c.body).toContain(`${PROACTIVE_DEDUPE_MARKER_PREFIX}${key}`);
    }
    // Audit fires for the 2 non-info findings (the info one is skipped before audit).
    expect(audited.map((a) => a.title)).toEqual([
      "Memory growth on workflow-runner",
      "Deploy times creeping up",
    ]);
  });

  it("truncates over-long titles to 200 chars when inserting", async () => {
    const longTitle = "x".repeat(500);
    let receivedTitle = "";
    await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [finding({ title: longTitle, severity: "warning" })],
      isDuplicate: async () => false,
      createFindingIssue: async (args) => {
        receivedTitle = args.title;
        return 1;
      },
      recordAudit: async () => {},
    });
    expect(receivedTitle.length).toBe(200);
  });
});

describe("aiProactiveMonitorTick — dedupe", () => {
  it("does not double-fire on the same title", async () => {
    const created: string[] = [];
    let dedupeChecks = 0;

    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [
        finding({ title: "Memory growth on workflow-runner", severity: "warning" }),
      ],
      isDuplicate: async (_repoId, _key, _hours) => {
        dedupeChecks += 1;
        return true; // pretend we already filed it
      },
      createFindingIssue: async (args) => {
        created.push(args.title);
        return 1;
      },
      recordAudit: async () => {},
    });

    expect(dedupeChecks).toBe(1);
    expect(created).toEqual([]);
    expect(summary.skippedDedupe).toBe(1);
    expect(summary.opened).toBe(0);
  });

  it("uses the lookback window from the constant", async () => {
    let observedHours = -1;
    await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [finding({ severity: "warning" })],
      isDuplicate: async (_r, _k, hours) => {
        observedHours = hours;
        return true;
      },
      createFindingIssue: async () => 1,
      recordAudit: async () => {},
    });
    expect(observedHours).toBe(PROACTIVE_LOOKBACK_HOURS);
  });

  it("passes the sha256 dedupe key to the duplicate check", async () => {
    let observedKey = "";
    await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [
        finding({ title: "Suspicious admin pattern", severity: "critical" }),
      ],
      isDuplicate: async (_r, key) => {
        observedKey = key;
        return true;
      },
      createFindingIssue: async () => 1,
      recordAudit: async () => {},
    });
    expect(observedKey).toBe(dedupeKeyForTitle("Suspicious admin pattern"));
  });
});

describe("aiProactiveMonitorTick — robustness", () => {
  it("isolates per-finding failures — one bad issue insert does not stop the rest", async () => {
    let attempts = 0;
    const created: string[] = [];

    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => [
        finding({ title: "first", severity: "warning" }),
        finding({ title: "second", severity: "critical" }),
      ],
      isDuplicate: async () => false,
      createFindingIssue: async (args) => {
        attempts += 1;
        if (args.title === "first") {
          throw new Error("DB blew up");
        }
        created.push(args.title);
        return attempts;
      },
      recordAudit: async () => {},
    });

    expect(attempts).toBe(2);
    expect(created).toEqual(["second"]);
    expect(summary.opened).toBe(1);
    expect(summary.errors).toBe(1);
  });

  it("returns errors=1 when askClaude throws (does not propagate)", async () => {
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => {
        throw new Error("anthropic 500");
      },
    });
    expect(summary.errors).toBe(1);
    expect(summary.opened).toBe(0);
  });

  it("returns errors=1 when loadTelemetry throws (does not propagate)", async () => {
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => {
        throw new Error("DB down");
      },
      askClaude: async () => [],
    });
    expect(summary.errors).toBe(1);
  });

  it("caps the number of findings opened per tick", async () => {
    const created: string[] = [];
    const tooMany: ProactiveFinding[] = [];
    for (let i = 0; i < 10; i++) {
      tooMany.push(finding({ title: `finding-${i}`, severity: "warning" }));
    }
    const summary = await aiProactiveMonitorTick({
      aiAvailable: () => true,
      resolveSelfHostRepo: async () => REPO,
      loadTelemetry: async () => EMPTY_TELEMETRY,
      askClaude: async () => tooMany,
      isDuplicate: async () => false,
      createFindingIssue: async (args) => {
        created.push(args.title);
        return created.length;
      },
      recordAudit: async () => {},
      maxFindings: 3,
    });
    expect(created.length).toBe(3);
    expect(summary.opened).toBe(3);
    expect(summary.considered).toBe(3);
    // The 7 we didn't even look at are counted in the skipped overflow.
    expect(summary.skippedSeverity).toBe(7);
  });
});

describe("ai-proactive-monitor — prompt summary helper", () => {
  it("renders an empty telemetry block without throwing", () => {
    const out = monitorInternals.summariseTelemetryForPrompt(EMPTY_TELEMETRY);
    expect(out).toContain("Audit log");
    expect(out).toContain("Platform deploys");
    expect(out).toContain("Workflow runs");
  });

  it("groups audit rows by action and counts them", () => {
    const out = monitorInternals.summariseTelemetryForPrompt({
      ...EMPTY_TELEMETRY,
      auditLog: [
        {
          action: "repo.create",
          targetType: null,
          targetId: null,
          userId: null,
          repositoryId: null,
          createdAt: new Date(),
        },
        {
          action: "repo.create",
          targetType: null,
          targetId: null,
          userId: null,
          repositoryId: null,
          createdAt: new Date(),
        },
        {
          action: "auto_merge.merged",
          targetType: null,
          targetId: null,
          userId: null,
          repositoryId: null,
          createdAt: new Date(),
        },
      ],
    });
    expect(out).toContain("repo.create: 2");
    expect(out).toContain("auto_merge.merged: 1");
  });
});