@app-vitals/agent-admin 1.74.0 → 1.76.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.
@@ -40,4 +40,7 @@ export type * from './models/ChatThreadWatch.ts'
40
40
  export type * from './models/UserNotificationPrefs.ts'
41
41
  export type * from './models/AgentMarketplace.ts'
42
42
  export type * from './models/GitHubReconcileAudit.ts'
43
+ export type * from './models/GitHubRepoSnapshot.ts'
44
+ export type * from './models/GitHubCachedRepo.ts'
45
+ export type * from './models/GitHubRepoAccess.ts'
43
46
  export type * from './commonInputTypes.ts'
@@ -0,0 +1,75 @@
1
+ -- GLC-1.1: GitHub repo/access cache. Additive only: three new tables, nothing existing is touched.
2
+ -- CreateTable
3
+ CREATE TABLE "GitHubRepoSnapshot" (
4
+ "id" TEXT NOT NULL,
5
+ "accountId" TEXT NOT NULL,
6
+ "appKind" TEXT NOT NULL,
7
+ "appRef" TEXT NOT NULL,
8
+ "org" TEXT NOT NULL,
9
+ "crawlPage" INTEGER NOT NULL DEFAULT 0,
10
+ "crawlStartedAt" TIMESTAMP(3),
11
+ "completedAt" TIMESTAMP(3),
12
+ "totalCount" INTEGER,
13
+ "lastError" TEXT,
14
+ "attempts" INTEGER NOT NULL DEFAULT 0,
15
+ "nextAttemptAt" TIMESTAMP(3),
16
+ "rateLimitResetAt" TIMESTAMP(3),
17
+ "leaseHolder" TEXT,
18
+ "leasedUntil" TIMESTAMP(3),
19
+ "lastTickAt" TIMESTAMP(3),
20
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
21
+ "updatedAt" TIMESTAMP(3) NOT NULL,
22
+
23
+ CONSTRAINT "GitHubRepoSnapshot_pkey" PRIMARY KEY ("id")
24
+ );
25
+
26
+ -- CreateTable
27
+ CREATE TABLE "GitHubCachedRepo" (
28
+ "id" TEXT NOT NULL,
29
+ "snapshotId" TEXT NOT NULL,
30
+ "githubId" BIGINT NOT NULL,
31
+ "fullName" TEXT NOT NULL,
32
+ "archived" BOOLEAN NOT NULL DEFAULT false,
33
+ "seenAt" TIMESTAMP(3) NOT NULL,
34
+
35
+ CONSTRAINT "GitHubCachedRepo_pkey" PRIMARY KEY ("id")
36
+ );
37
+
38
+ -- CreateTable
39
+ CREATE TABLE "GitHubRepoAccess" (
40
+ "id" TEXT NOT NULL,
41
+ "accountId" TEXT NOT NULL,
42
+ "org" TEXT NOT NULL,
43
+ "repo" TEXT NOT NULL,
44
+ "username" TEXT NOT NULL,
45
+ "canPush" BOOLEAN NOT NULL DEFAULT false,
46
+ "level" TEXT,
47
+ "checkedAt" TIMESTAMP(3) NOT NULL,
48
+ "status" TEXT NOT NULL,
49
+ "attempts" INTEGER NOT NULL DEFAULT 0,
50
+ "nextAttemptAt" TIMESTAMP(3),
51
+ "lastError" TEXT,
52
+
53
+ CONSTRAINT "GitHubRepoAccess_pkey" PRIMARY KEY ("id")
54
+ );
55
+
56
+ -- CreateIndex
57
+ CREATE INDEX "GitHubRepoSnapshot_accountId_appKind_org_idx" ON "GitHubRepoSnapshot"("accountId", "appKind", "org");
58
+
59
+ -- CreateIndex
60
+ CREATE UNIQUE INDEX "GitHubRepoSnapshot_accountId_appKind_appRef_org_key" ON "GitHubRepoSnapshot"("accountId", "appKind", "appRef", "org");
61
+
62
+ -- CreateIndex
63
+ CREATE INDEX "GitHubCachedRepo_snapshotId_seenAt_idx" ON "GitHubCachedRepo"("snapshotId", "seenAt");
64
+
65
+ -- CreateIndex
66
+ CREATE UNIQUE INDEX "GitHubCachedRepo_snapshotId_githubId_key" ON "GitHubCachedRepo"("snapshotId", "githubId");
67
+
68
+ -- CreateIndex
69
+ CREATE INDEX "GitHubRepoAccess_accountId_org_username_nextAttemptAt_idx" ON "GitHubRepoAccess"("accountId", "org", "username", "nextAttemptAt");
70
+
71
+ -- CreateIndex
72
+ CREATE UNIQUE INDEX "GitHubRepoAccess_accountId_org_repo_username_key" ON "GitHubRepoAccess"("accountId", "org", "repo", "username");
73
+
74
+ -- AddForeignKey
75
+ ALTER TABLE "GitHubCachedRepo" ADD CONSTRAINT "GitHubCachedRepo_snapshotId_fkey" FOREIGN KEY ("snapshotId") REFERENCES "GitHubRepoSnapshot"("id") ON DELETE CASCADE ON UPDATE CASCADE;
@@ -744,3 +744,65 @@ model GitHubReconcileAudit {
744
744
 
745
745
  @@index([agentId, createdAt])
746
746
  }
747
+
748
+ // ─── GitHub repo/access cache (GLC-1.1) ──────────────────────────────────────
749
+ // Per-org crawl snapshot, the repos seen by it, and per-user push access.
750
+ // accountId/appRef are plain columns (no relations): cache rows are disposable.
751
+ // Debug detail (lastError, attempts, timestamps) is stored as plain columns so
752
+ // any existing view can show it.
753
+
754
+ model GitHubRepoSnapshot {
755
+ id String @id @default(cuid())
756
+ accountId String
757
+ appKind String // 'lookup' | 'agent'
758
+ appRef String // app id (lookup) or agent id (agent)
759
+ org String
760
+ crawlPage Int @default(0)
761
+ crawlStartedAt DateTime?
762
+ completedAt DateTime?
763
+ totalCount Int?
764
+ lastError String?
765
+ attempts Int @default(0)
766
+ nextAttemptAt DateTime?
767
+ rateLimitResetAt DateTime?
768
+ leaseHolder String?
769
+ leasedUntil DateTime?
770
+ lastTickAt DateTime?
771
+ createdAt DateTime @default(now())
772
+ updatedAt DateTime @updatedAt
773
+ repos GitHubCachedRepo[]
774
+
775
+ @@unique([accountId, appKind, appRef, org])
776
+ @@index([accountId, appKind, org])
777
+ }
778
+
779
+ model GitHubCachedRepo {
780
+ id String @id @default(cuid())
781
+ snapshotId String
782
+ snapshot GitHubRepoSnapshot @relation(fields: [snapshotId], references: [id], onDelete: Cascade)
783
+ githubId BigInt
784
+ fullName String
785
+ archived Boolean @default(false)
786
+ seenAt DateTime
787
+
788
+ @@unique([snapshotId, githubId])
789
+ @@index([snapshotId, seenAt])
790
+ }
791
+
792
+ model GitHubRepoAccess {
793
+ id String @id @default(cuid())
794
+ accountId String
795
+ org String
796
+ repo String
797
+ username String
798
+ canPush Boolean @default(false)
799
+ level String?
800
+ checkedAt DateTime
801
+ status String // 'ok' | 'error' | 'terminal'
802
+ attempts Int @default(0)
803
+ nextAttemptAt DateTime?
804
+ lastError String?
805
+
806
+ @@unique([accountId, org, repo, username])
807
+ @@index([accountId, org, username, nextAttemptAt])
808
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * admin/scripts/backfill-member-id.ts (ACM-1.2)
3
+ *
4
+ * DATABASE_URL_SHIPWRIGHT_ADMIN=... bun admin/scripts/backfill-member-id.ts [--dry-run] [--overrides overrides.json] [--report report.json]
5
+ *
6
+ * overrides.json: { "alice@old.com": "<AccountMember.id>" }. Overrides win over
7
+ * the automatic email match. --dry-run changes nothing.
8
+ */
9
+
10
+ import { readFileSync, writeFileSync } from "node:fs";
11
+ import { parseFlags } from "@app-vitals/agent-lib/cli-flags";
12
+ import {
13
+ parseOverrides,
14
+ runMemberIdBackfill,
15
+ } from "../src/member-id-backfill.ts";
16
+ import { createAdminPrismaClient } from "../src/prisma-client.ts";
17
+
18
+ const flags = parseFlags(process.argv.slice(2), ["--overrides", "--report"], {
19
+ booleans: ["--dry-run"],
20
+ });
21
+ const url = process.env.DATABASE_URL_SHIPWRIGHT_ADMIN;
22
+ if (!url) {
23
+ console.error("DATABASE_URL_SHIPWRIGHT_ADMIN is required");
24
+ process.exit(2);
25
+ }
26
+
27
+ const prisma = createAdminPrismaClient(url);
28
+ try {
29
+ const overrides = flags["--overrides"]
30
+ ? parseOverrides(readFileSync(flags["--overrides"], "utf8"))
31
+ : undefined;
32
+ const report = await runMemberIdBackfill(prisma, {
33
+ dryRun: flags["--dry-run"],
34
+ overrides,
35
+ });
36
+ const body = JSON.stringify(report, null, 2);
37
+ if (flags["--report"]) writeFileSync(flags["--report"], `${body}\n`);
38
+ console.log(body);
39
+ } finally {
40
+ await prisma.$disconnect();
41
+ }
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Integration tests for GitHubRepoCacheService against a real PostgreSQL DB.
3
+ * Requires DATABASE_URL_ADMIN_TEST to be set; skips otherwise.
4
+ */
5
+
6
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
7
+ import type { PrismaClient } from "../prisma/client/client.ts";
8
+ import { GitHubRepoCacheService } from "./github-repo-cache.ts";
9
+ import { createAdminPrismaClient } from "./prisma-client.ts";
10
+
11
+ const TEST_DB = process.env.DATABASE_URL_ADMIN_TEST;
12
+ const describeOrSkip = TEST_DB ? describe : describe.skip;
13
+
14
+ const key = {
15
+ accountId: "acc",
16
+ appKind: "lookup" as const,
17
+ appRef: "1",
18
+ org: "acme",
19
+ };
20
+ const T0 = new Date("2026-11-20T12:00:00Z");
21
+ const min = (n: number) => new Date(T0.getTime() + n * 60_000);
22
+
23
+ describeOrSkip("GitHubRepoCacheService (integration)", () => {
24
+ let prisma: PrismaClient;
25
+ let now: Date;
26
+ let svc: GitHubRepoCacheService;
27
+
28
+ beforeEach(async () => {
29
+ prisma = createAdminPrismaClient(TEST_DB as string);
30
+ await prisma.gitHubCachedRepo.deleteMany();
31
+ await prisma.gitHubRepoSnapshot.deleteMany();
32
+ await prisma.gitHubRepoAccess.deleteMany();
33
+ now = T0;
34
+ svc = new GitHubRepoCacheService(prisma, { now: () => now });
35
+ });
36
+
37
+ afterEach(async () => {
38
+ await prisma.$disconnect();
39
+ });
40
+
41
+ it("upserts and reads a snapshot, merging progress", async () => {
42
+ expect(await svc.getSnapshot(key)).toBeNull();
43
+ const a = await svc.upsertSnapshot(key, { crawlPage: 1, totalCount: 5 });
44
+ const b = await svc.upsertSnapshot(key, { crawlPage: 2 });
45
+ expect(b.id).toBe(a.id);
46
+ expect(b.crawlPage).toBe(2);
47
+ expect(b.totalCount).toBe(5);
48
+ expect((await svc.getSnapshot(key))?.id).toBe(a.id);
49
+ });
50
+
51
+ it("batch-upserts repos without duplicating", async () => {
52
+ const snap = await svc.upsertSnapshot(key);
53
+ const repos = Array.from({ length: 1200 }, (_, i) => ({
54
+ githubId: 10_000_000_000 + i,
55
+ fullName: `acme/r${i}`,
56
+ }));
57
+ await svc.upsertRepos(snap.id, repos, T0);
58
+ await svc.upsertRepos(
59
+ snap.id,
60
+ [{ githubId: 10_000_000_000, fullName: "acme/renamed", archived: true }],
61
+ min(1),
62
+ );
63
+ expect(await prisma.gitHubCachedRepo.count()).toBe(1200);
64
+ const r = await prisma.gitHubCachedRepo.findFirstOrThrow({
65
+ where: { githubId: 10_000_000_000n },
66
+ });
67
+ expect(r.fullName).toBe("acme/renamed");
68
+ expect(r.archived).toBe(true);
69
+ });
70
+
71
+ it("sweep deletes only rows seen before crawlStartedAt", async () => {
72
+ const snap = await svc.upsertSnapshot(key, { crawlStartedAt: min(10) });
73
+ await svc.upsertRepos(
74
+ snap.id,
75
+ [{ githubId: 1, fullName: "acme/old" }],
76
+ min(5),
77
+ );
78
+ await svc.upsertRepos(
79
+ snap.id,
80
+ [{ githubId: 2, fullName: "acme/new" }],
81
+ min(10),
82
+ );
83
+ await svc.upsertRepos(
84
+ snap.id,
85
+ [{ githubId: 3, fullName: "acme/newer" }],
86
+ min(11),
87
+ );
88
+ expect(await svc.sweepGeneration(snap.id)).toBe(1);
89
+ const left = await prisma.gitHubCachedRepo.findMany({
90
+ orderBy: { githubId: "asc" },
91
+ });
92
+ expect(left.map((r) => r.fullName)).toEqual(["acme/new", "acme/newer"]);
93
+ });
94
+
95
+ it("sweep is a no-op before a crawl has started and spares other snapshots", async () => {
96
+ const a = await svc.upsertSnapshot(key);
97
+ const b = await svc.upsertSnapshot(
98
+ { ...key, org: "other" },
99
+ { crawlStartedAt: min(10) },
100
+ );
101
+ await svc.upsertRepos(a.id, [{ githubId: 1, fullName: "acme/x" }], min(1));
102
+ await svc.upsertRepos(
103
+ b.id,
104
+ [{ githubId: 2, fullName: "other/y" }],
105
+ min(20),
106
+ );
107
+ expect(await svc.sweepGeneration(a.id)).toBe(0);
108
+ expect(await prisma.gitHubCachedRepo.count()).toBe(2);
109
+ });
110
+
111
+ it("lease: first concurrent acquirer wins; others fail until expiry", async () => {
112
+ const snap = await svc.upsertSnapshot(key);
113
+ const results = await Promise.all(
114
+ ["w1", "w2", "w3", "w4"].map((w) => svc.acquireLease(snap.id, w, 60_000)),
115
+ );
116
+ expect(results.filter(Boolean).length).toBe(1);
117
+ const holder = (await svc.getSnapshot(key))?.leaseHolder as string;
118
+ expect(await svc.acquireLease(snap.id, "late", 60_000)).toBe(false);
119
+ now = min(2); // past leasedUntil
120
+ expect(await svc.acquireLease(snap.id, "late", 60_000)).toBe(true);
121
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBe("late");
122
+ expect(holder).not.toBe("late");
123
+ });
124
+
125
+ it("lease: release is idempotent, owner-only, and frees the lease", async () => {
126
+ const snap = await svc.upsertSnapshot(key);
127
+ expect(await svc.acquireLease(snap.id, "w1", 60_000)).toBe(true);
128
+ await svc.releaseLease(snap.id, "intruder");
129
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBe("w1");
130
+ await svc.releaseLease(snap.id, "w1");
131
+ await svc.releaseLease(snap.id, "w1");
132
+ expect((await svc.getSnapshot(key))?.leaseHolder).toBeNull();
133
+ expect(await svc.acquireLease(snap.id, "w2", 60_000)).toBe(true);
134
+ });
135
+
136
+ it("acquire on a missing snapshot returns false", async () => {
137
+ expect(await svc.acquireLease("nope", "w", 1000)).toBe(false);
138
+ });
139
+
140
+ it("access: missing-or-expired query", async () => {
141
+ const base = {
142
+ accountId: "acc",
143
+ org: "acme",
144
+ username: "dan",
145
+ canPush: true,
146
+ };
147
+ await svc.upsertAccess({ ...base, repo: "fresh", status: "ok" });
148
+ await svc.upsertAccess({
149
+ ...base,
150
+ repo: "terminal",
151
+ status: "terminal",
152
+ lastError: "404",
153
+ });
154
+ await svc.upsertAccess({
155
+ ...base,
156
+ repo: "err-later",
157
+ status: "error",
158
+ attempts: 1,
159
+ nextAttemptAt: min(30),
160
+ });
161
+ await svc.upsertAccess({
162
+ ...base,
163
+ repo: "err-due",
164
+ status: "error",
165
+ attempts: 1,
166
+ nextAttemptAt: min(-1),
167
+ });
168
+ await svc.upsertAccess({
169
+ ...base,
170
+ repo: "other-user",
171
+ status: "ok",
172
+ username: "eve",
173
+ });
174
+ const repos = [
175
+ "fresh",
176
+ "terminal",
177
+ "err-later",
178
+ "err-due",
179
+ "other-user",
180
+ "absent",
181
+ ];
182
+ const q = {
183
+ accountId: "acc",
184
+ org: "acme",
185
+ username: "dan",
186
+ repos,
187
+ maxAgeMs: 3_600_000,
188
+ };
189
+ expect(await svc.findMissingOrExpiredAccess(q)).toEqual([
190
+ "err-due",
191
+ "other-user",
192
+ "absent",
193
+ ]);
194
+ now = min(120); // everything ok is now older than 1h; error-later is due too
195
+ expect(await svc.findMissingOrExpiredAccess(q)).toEqual([
196
+ "fresh",
197
+ "err-later",
198
+ "err-due",
199
+ "other-user",
200
+ "absent",
201
+ ]);
202
+ });
203
+
204
+ it("access: upsert updates in place", async () => {
205
+ const base = { accountId: "acc", org: "acme", username: "dan", repo: "r" };
206
+ await svc.upsertAccess({
207
+ ...base,
208
+ canPush: false,
209
+ status: "error",
210
+ attempts: 1,
211
+ });
212
+ await svc.upsertAccess({
213
+ ...base,
214
+ canPush: true,
215
+ level: "write",
216
+ status: "ok",
217
+ });
218
+ const rows = await prisma.gitHubRepoAccess.findMany();
219
+ expect(rows).toHaveLength(1);
220
+ expect(rows[0]).toMatchObject({
221
+ canPush: true,
222
+ level: "write",
223
+ status: "ok",
224
+ attempts: 0,
225
+ });
226
+ });
227
+ });