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
demo-activity-seed.ts11.3 KB · 404 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
/**
 * Block L3 — extra seeded content + audit rows so the live `/demo` page
 * has something to render the first time a visitor lands.
 *
 * This module is STRICTLY ADDITIVE to `src/lib/demo-seed.ts` (which is
 * locked under §4.5). The locked seed creates the `demo` user + 3 sample
 * repos + a handful of issues and one closed PR; this helper layers on:
 *
 *   - 2 additional issues per repo (one labelled `ai:build`).
 *   - One open PR + one merged PR on `todo-api`.
 *   - One AI-review comment on the open PR (with `AI_REVIEW_MARKER`).
 *   - One `auto_merge.merged` audit row for the merged PR.
 *
 * All operations are idempotent — a marker comment, label-name, or
 * audit-action equality check is consulted before each insert. Re-running
 * is a no-op. Never throws.
 *
 * Wired from `src/index.ts` immediately after `ensureDemoContent()`.
 */

import { and, eq, sql } from "drizzle-orm";
import { db } from "../db";
import {
  auditLog,
  issueLabels,
  issues,
  labels,
  prComments,
  pullRequests,
  repositories,
  users,
} from "../db/schema";
import { DEMO_USERNAME } from "./demo-seed";
import { AI_REVIEW_MARKER } from "./ai-review";

const AI_BUILD_LABEL = "ai:build";
const DEMO_ACTIVITY_MARKER = "<!-- gluecron:demo-activity:v1 -->";

export interface DemoActivitySeedResult {
  added: {
    issues: number;
    labels: number;
    issueLabels: number;
    prs: number;
    prComments: number;
    auditRows: number;
  };
  errors: string[];
}

interface DemoRepo {
  id: string;
  name: string;
  ownerId: string;
}

async function loadDemoRepos(): Promise<DemoRepo[]> {
  try {
    const [demo] = await db
      .select({ id: users.id })
      .from(users)
      .where(eq(users.username, DEMO_USERNAME))
      .limit(1);
    if (!demo) return [];
    const rows = await db
      .select({
        id: repositories.id,
        name: repositories.name,
        ownerId: repositories.ownerId,
      })
      .from(repositories)
      .where(eq(repositories.ownerId, demo.id));
    return rows;
  } catch {
    return [];
  }
}

async function ensureLabel(
  repoId: string,
  name: string,
  color: string
): Promise<string | null> {
  try {
    const [existing] = await db
      .select({ id: labels.id })
      .from(labels)
      .where(and(eq(labels.repositoryId, repoId), eq(labels.name, name)))
      .limit(1);
    if (existing) return existing.id;
    const [inserted] = await db
      .insert(labels)
      .values({
        repositoryId: repoId,
        name,
        color,
      })
      .returning({ id: labels.id });
    return inserted?.id ?? null;
  } catch {
    return null;
  }
}

async function findIssueByTitle(
  repoId: string,
  title: string
): Promise<{ id: string } | null> {
  try {
    const [row] = await db
      .select({ id: issues.id })
      .from(issues)
      .where(and(eq(issues.repositoryId, repoId), eq(issues.title, title)))
      .limit(1);
    return row ?? null;
  } catch {
    return null;
  }
}

async function ensureIssueLabel(
  issueId: string,
  labelId: string
): Promise<boolean> {
  try {
    const [existing] = await db
      .select({ id: issueLabels.id })
      .from(issueLabels)
      .where(
        and(
          eq(issueLabels.issueId, issueId),
          eq(issueLabels.labelId, labelId)
        )
      )
      .limit(1);
    if (existing) return false;
    await db.insert(issueLabels).values({ issueId, labelId });
    return true;
  } catch {
    return false;
  }
}

async function findPrByTitle(
  repoId: string,
  title: string
): Promise<{ id: string; number: number; state: string; mergedAt: Date | null } | null> {
  try {
    const [row] = await db
      .select({
        id: pullRequests.id,
        number: pullRequests.number,
        state: pullRequests.state,
        mergedAt: pullRequests.mergedAt,
      })
      .from(pullRequests)
      .where(
        and(
          eq(pullRequests.repositoryId, repoId),
          eq(pullRequests.title, title)
        )
      )
      .limit(1);
    return row ?? null;
  } catch {
    return null;
  }
}

/**
 * Idempotently seed extra demo content + activity for the live `/demo` page.
 * Never throws. Re-runnable.
 */
export async function ensureDemoActivity(): Promise<DemoActivitySeedResult> {
  const result: DemoActivitySeedResult = {
    added: {
      issues: 0,
      labels: 0,
      issueLabels: 0,
      prs: 0,
      prComments: 0,
      auditRows: 0,
    },
    errors: [],
  };

  const repos = await loadDemoRepos();
  if (repos.length === 0) return result;

  // Find the demo user id for `authorId` on issues/PRs/comments.
  const demoUserId = repos[0].ownerId;

  for (const repo of repos) {
    // ── Issue 1: an `ai:build`-labelled issue per repo.
    const aiIssueTitle = `[AI] Add /metrics endpoint to ${repo.name}`;
    const aiIssueBody =
      `Expose a Prometheus-style \`/metrics\` endpoint with request counts ` +
      `and p95 latency. Auto-build candidate; the gluecron autopilot should ` +
      `pick this up and open a draft PR.`;
    try {
      let existing = await findIssueByTitle(repo.id, aiIssueTitle);
      if (!existing) {
        const [inserted] = await db
          .insert(issues)
          .values({
            repositoryId: repo.id,
            authorId: demoUserId,
            title: aiIssueTitle,
            body: aiIssueBody,
            state: "open",
          })
          .returning({ id: issues.id });
        if (inserted) {
          existing = { id: inserted.id };
          result.added.issues += 1;
        }
      }
      if (existing) {
        const labelId = await ensureLabel(repo.id, AI_BUILD_LABEL, "#8c6dff");
        if (labelId) {
          // Track label count only on first insert per repo.
          // ensureLabel doesn't expose "newly inserted" so this is an
          // approximation; the counter is for observability only.
          if (await ensureIssueLabel(existing.id, labelId)) {
            result.added.issueLabels += 1;
          }
        }
      }
    } catch (err: any) {
      result.errors.push(
        `ai:build issue(${repo.name}): ${String(err?.message || err)}`
      );
    }

    // ── Issue 2: a plain triage issue (one extra per repo so each repo has
    // 3+ issues total once the locked seed's single issue is counted).
    const triageTitle = `[triage] Investigate flaky tests in ${repo.name}`;
    try {
      const existing = await findIssueByTitle(repo.id, triageTitle);
      if (!existing) {
        await db.insert(issues).values({
          repositoryId: repo.id,
          authorId: demoUserId,
          title: triageTitle,
          body:
            "Several CI runs have shown intermittent failures. Likely a " +
            "timing-sensitive assertion. Worth a 15-minute investigation.",
          state: "open",
        });
        result.added.issues += 1;
      }
    } catch (err: any) {
      result.errors.push(
        `triage issue(${repo.name}): ${String(err?.message || err)}`
      );
    }
  }

  // ── PR seeding + AI review + audit row are scoped to todo-api.
  const todoApi = repos.find((r) => r.name === "todo-api");
  if (todoApi) {
    // Open PR (carries an AI review comment).
    const openPrTitle = "feat: add /metrics endpoint";
    try {
      let openPr = await findPrByTitle(todoApi.id, openPrTitle);
      if (!openPr) {
        const [inserted] = await db
          .insert(pullRequests)
          .values({
            repositoryId: todoApi.id,
            authorId: demoUserId,
            title: openPrTitle,
            body:
              "Adds a Prometheus-style `/metrics` endpoint. " +
              DEMO_ACTIVITY_MARKER,
            state: "open",
            baseBranch: "main",
            headBranch: "demo/metrics-endpoint",
          })
          .returning({
            id: pullRequests.id,
            number: pullRequests.number,
            state: pullRequests.state,
            mergedAt: pullRequests.mergedAt,
          });
        if (inserted) {
          openPr = inserted;
          result.added.prs += 1;
        }
      }

      if (openPr) {
        // Add an AI review comment with the canonical marker so the page's
        // "AI reviews posted today" tile has content. Idempotent — we
        // refuse to add a second AI review on this PR.
        const [existingReview] = await db
          .select({ id: prComments.id })
          .from(prComments)
          .where(
            and(
              eq(prComments.pullRequestId, openPr.id),
              eq(prComments.isAiReview, true)
            )
          )
          .limit(1);
        if (!existingReview) {
          await db.insert(prComments).values({
            pullRequestId: openPr.id,
            authorId: demoUserId,
            isAiReview: true,
            body:
              `${AI_REVIEW_MARKER}\n## AI Code Review\n\n` +
              "**Verdict: looks good.** The new `/metrics` handler is small, " +
              "side-effect-free, and adds a Prometheus-format counter for " +
              "request totals. No blocking findings.",
          });
          result.added.prComments += 1;
        }
      }
    } catch (err: any) {
      result.errors.push(
        `open PR(todo-api): ${String(err?.message || err)}`
      );
    }

    // Merged PR + matching audit row.
    const mergedPrTitle = "chore: bump hono to ^4.6.0";
    try {
      let mergedPr = await findPrByTitle(todoApi.id, mergedPrTitle);
      if (!mergedPr) {
        const now = new Date();
        const [inserted] = await db
          .insert(pullRequests)
          .values({
            repositoryId: todoApi.id,
            authorId: demoUserId,
            title: mergedPrTitle,
            body:
              "Routine dep bump — Hono 4.6.0 ships small bugfixes. " +
              DEMO_ACTIVITY_MARKER,
            state: "merged",
            baseBranch: "main",
            headBranch: "demo/hono-4-6",
            mergedAt: now,
            mergedBy: demoUserId,
            closedAt: now,
          })
          .returning({
            id: pullRequests.id,
            number: pullRequests.number,
            state: pullRequests.state,
            mergedAt: pullRequests.mergedAt,
          });
        if (inserted) {
          mergedPr = inserted;
          result.added.prs += 1;
        }
      }

      if (mergedPr) {
        // Check for an existing auto_merge.merged audit row on this PR.
        const [existingAudit] = await db
          .select({ id: auditLog.id })
          .from(auditLog)
          .where(
            and(
              eq(auditLog.action, "auto_merge.merged"),
              eq(auditLog.repositoryId, todoApi.id),
              eq(auditLog.targetId, mergedPr.id)
            )
          )
          .limit(1);
        if (!existingAudit) {
          await db.insert(auditLog).values({
            repositoryId: todoApi.id,
            action: "auto_merge.merged",
            targetType: "pull_request",
            targetId: mergedPr.id,
            metadata: JSON.stringify({
              prNumber: mergedPr.number,
              baseBranch: "main",
              headBranch: "demo/hono-4-6",
              source: "demo-activity-seed",
            }),
          });
          result.added.auditRows += 1;
        }
      }
    } catch (err: any) {
      result.errors.push(
        `merged PR(todo-api): ${String(err?.message || err)}`
      );
    }
  }

  return result;
}

/** Test-only re-exports. */
export const __test = {
  AI_BUILD_LABEL,
  DEMO_ACTIVITY_MARKER,
  loadDemoRepos,
};