@app-vitals/agent-admin 1.85.0 → 1.86.1

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/Dockerfile CHANGED
@@ -2,7 +2,7 @@
2
2
  #
3
3
  # Build from the repository root: docker build -f admin/Dockerfile .
4
4
 
5
- FROM oven/bun:1.4.4-slim@sha256:1846adf22496bd711036aae8be147e57bdebbaea2e5264e3e0b5af1db187d9a4 AS deps
5
+ FROM oven/bun:1.4.5-slim@sha256:b780593f3e10918cbdaec3d5a08d52224b9198069a65eb47812085c2ec007643 AS deps
6
6
 
7
7
  WORKDIR /app
8
8
 
@@ -23,7 +23,7 @@ RUN if [ -f bun.lock ]; then bun install --frozen-lockfile --production; else bu
23
23
  && rm -rf node_modules/.bun/typescript@* node_modules/.bun/@typescript+* \
24
24
  node_modules/.bun/node_modules/typescript node_modules/.bun/node_modules/@typescript
25
25
 
26
- FROM oven/bun:1.4.4-slim@sha256:1846adf22496bd711036aae8be147e57bdebbaea2e5264e3e0b5af1db187d9a4 AS production
26
+ FROM oven/bun:1.4.5-slim@sha256:b780593f3e10918cbdaec3d5a08d52224b9198069a65eb47812085c2ec007643 AS production
27
27
 
28
28
  # Upgrade apt/libapt-pkg7.0 past the base image's 3.0.3 (Trivy HIGH CVE-2026-109518, fixed in 3.0.4).
29
29
  RUN apt-get update \
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@app-vitals/agent-admin",
3
- "version": "1.85.0",
3
+ "version": "1.86.1",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/app-vitals/agent.git",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@anthropic-ai/sdk": "0.137.0",
47
- "@app-vitals/agent-lib": "1.85.0",
47
+ "@app-vitals/agent-lib": "1.86.1",
48
48
  "@hono/zod-openapi": "^1.0.0",
49
49
  "@prisma/adapter-pg": "^7.10.0",
50
50
  "@prisma/client": "^7.10.0",
@@ -72,20 +72,43 @@ const hasSyncDetail = (v: InstallationSyncView): boolean =>
72
72
  v.leaseHolder !== undefined ||
73
73
  v.lastTickAt !== undefined;
74
74
 
75
- const utc = (iso: string): string =>
76
- `${escapeHtml(iso.slice(0, 16).replace("T", " "))} UTC`;
75
+ /**
76
+ * Display text for a UTC ISO instant: "Nov 23, 5:02 PM PST" in the given IANA
77
+ * timezone, or "2026-11-23 17:02 UTC" when none is set. Unparseable input is
78
+ * returned as-is. Not HTML-escaped.
79
+ */
80
+ export function formatSyncTime(iso: string, timezone?: string): string {
81
+ const d = new Date(iso);
82
+ if (!timezone || Number.isNaN(d.getTime())) {
83
+ return `${iso.slice(0, 16).replace("T", " ")} UTC`;
84
+ }
85
+ return new Intl.DateTimeFormat("en-US", {
86
+ timeZone: timezone,
87
+ month: "short",
88
+ day: "numeric",
89
+ hour: "numeric",
90
+ minute: "2-digit",
91
+ timeZoneName: "short",
92
+ }).format(d);
93
+ }
94
+
95
+ const fmt = (iso: string, timezone?: string): string =>
96
+ escapeHtml(formatSyncTime(iso, timezone));
77
97
 
78
98
  /**
79
99
  * One-line sync status: synced-at, "N of M repos", last error and the rate-limit
80
100
  * reset. Empty when the view has no sync detail (older API).
81
101
  */
82
- export function renderInstallationSyncStatus(v: InstallationSyncView): string {
102
+ export function renderInstallationSyncStatus(
103
+ v: InstallationSyncView,
104
+ timezone?: string,
105
+ ): string {
83
106
  if (!hasSyncDetail(v)) return "";
84
107
  const complete = installationSnapshotComplete(v);
85
108
  const parts: string[] = [];
86
109
  parts.push(
87
110
  v.syncedAt
88
- ? `Synced ${escapeHtml(v.syncedAt.slice(0, 16).replace("T", " "))} UTC`
111
+ ? `Synced ${fmt(v.syncedAt, timezone)}`
89
112
  : complete
90
113
  ? "Synced"
91
114
  : "Sync in progress",
@@ -99,18 +122,17 @@ export function renderInstallationSyncStatus(v: InstallationSyncView): string {
99
122
  }
100
123
  if (v.lastError) parts.push(`Last error: ${escapeHtml(v.lastError)}`);
101
124
  if (v.rateLimitResetAt) {
102
- parts.push(
103
- `GitHub rate limit resets ${escapeHtml(v.rateLimitResetAt.slice(0, 16).replace("T", " "))} UTC`,
104
- );
125
+ parts.push(`GitHub rate limit resets ${fmt(v.rateLimitResetAt, timezone)}`);
105
126
  }
106
127
  if (v.attempts) {
107
128
  parts.push(
108
129
  `${v.attempts} failed ${v.attempts === 1 ? "attempt" : "attempts"}`,
109
130
  );
110
131
  }
111
- if (v.nextAttemptAt) parts.push(`Next attempt ${utc(v.nextAttemptAt)}`);
132
+ if (v.nextAttemptAt)
133
+ parts.push(`Next attempt ${fmt(v.nextAttemptAt, timezone)}`);
112
134
  if (v.leaseHolder) parts.push(`Refreshing (${escapeHtml(v.leaseHolder)})`);
113
- if (v.lastTickAt) parts.push(`Last tick ${utc(v.lastTickAt)}`);
135
+ if (v.lastTickAt) parts.push(`Last tick ${fmt(v.lastTickAt, timezone)}`);
114
136
  const cls = v.lastError || v.rateLimitResetAt ? "alert alert-warning" : "";
115
137
  return `<div class="${cls}" data-installation-sync="${complete ? "complete" : "incomplete"}" style="color:#6b7280;font-size:12px;margin:8px 0">${parts.join(" &middot; ")}</div>`;
116
138
  }
@@ -290,9 +312,9 @@ export function renderGithubSyncCard(
290
312
  /** The card body: read-only repos per org with the user-can-push hint (only when known). */
291
313
  export function renderInstallationReposBody(
292
314
  view: InstallationReposView,
293
- opts: { appIdMismatch?: boolean } = {},
315
+ opts: { appIdMismatch?: boolean; timezone?: string } = {},
294
316
  ): string {
295
- const sync = renderInstallationSyncStatus(view);
317
+ const sync = renderInstallationSyncStatus(view, opts.timezone);
296
318
  if (view.orgs.length === 0 || view.orgs.every((o) => o.repos.length === 0)) {
297
319
  if (opts.appIdMismatch) {
298
320
  return `${sync}<div class="alert alert-warning" data-reason="app-id-mismatch">${escapeHtml(APP_ID_MISMATCH_MESSAGE)}</div>`;
@@ -334,7 +356,7 @@ export function renderInstallationReposBody(
334
356
  return `<tr><td class="mono">${escapeHtml(r.fullName)}</td><td>${hint}${meta}</td></tr>`;
335
357
  })
336
358
  .join("");
337
- return `<div class="github-installation-org" data-org="${escapeHtml(o.org)}" style="margin-bottom:16px"><div style="font-weight:600;margin-bottom:6px">${escapeHtml(o.org)}</div>${renderInstallationSyncStatus(o)}<table class="detail-table"><thead><tr><th>Repo</th><th>Bound user</th></tr></thead><tbody>${rows}</tbody></table></div>`;
359
+ return `<div class="github-installation-org" data-org="${escapeHtml(o.org)}" style="margin-bottom:16px"><div style="font-weight:600;margin-bottom:6px">${escapeHtml(o.org)}</div>${renderInstallationSyncStatus(o, opts.timezone)}<table class="detail-table"><thead><tr><th>Repo</th><th>Bound user</th></tr></thead><tbody>${rows}</tbody></table></div>`;
338
360
  })
339
361
  .join("")
340
362
  );
@@ -422,7 +444,7 @@ const plural = (n: number, one: string, many: string) =>
422
444
  `${n} ${n === 1 ? one : many}`;
423
445
 
424
446
  /** One readable sentence-list describing why an org's cached access was skipped. */
425
- function skipDetailText(d: SkipDetail): string {
447
+ function skipDetailText(d: SkipDetail, timezone?: string): string {
426
448
  const out: string[] = [];
427
449
  const crawls = d.crawls ?? [];
428
450
  const failed = crawls.filter((c) => c.lastError);
@@ -431,7 +453,7 @@ function skipDetailText(d: SkipDetail): string {
431
453
  } else if (failed.length > 0) {
432
454
  for (const c of failed) {
433
455
  out.push(
434
- `Lookup crawl failed: ${c.lastError}${c.rateLimitResetAt ? `; next attempt ${c.rateLimitResetAt}` : ""}`,
456
+ `Lookup crawl failed: ${c.lastError}${c.rateLimitResetAt ? `; next attempt ${formatSyncTime(c.rateLimitResetAt, timezone)}` : ""}`,
435
457
  );
436
458
  }
437
459
  } else if (crawls.some((c) => c.completedAt === null)) {
@@ -453,7 +475,8 @@ function skipDetailText(d: SkipDetail): string {
453
475
  );
454
476
  }
455
477
  if (d.rowErrors?.length) out.push(`Row errors: ${d.rowErrors.join("; ")}`);
456
- if (d.oldestCheckedAt) out.push(`Oldest check ${d.oldestCheckedAt}`);
478
+ if (d.oldestCheckedAt)
479
+ out.push(`Oldest check ${formatSyncTime(d.oldestCheckedAt, timezone)}`);
457
480
  return out
458
481
  .map((x) => `${x}.`)
459
482
  .join(" ")
@@ -471,12 +494,13 @@ const withoutSkipWarnings = (
471
494
 
472
495
  const skippedOrgsHtml = (
473
496
  skipped: readonly { org: string; reason: string; detail?: SkipDetail }[],
497
+ timezone?: string,
474
498
  ) =>
475
499
  skipped.length === 0
476
500
  ? ""
477
501
  : `<div class="alert alert-warning" data-skipped-orgs="1"><div style="font-weight:600">Skipped orgs (nothing added or removed there)</div>${skipped
478
502
  .map((s) => {
479
- const text = s.detail ? skipDetailText(s.detail) : "";
503
+ const text = s.detail ? skipDetailText(s.detail, timezone) : "";
480
504
  return `<div><span class="mono">${escapeHtml(s.org)}</span>: ${escapeHtml(s.reason)}${text ? `<div class="muted" data-skip-detail="1" style="font-size:0.9em">${escapeHtml(text)}</div>` : ""}</div>`;
481
505
  })
482
506
  .join("")}</div>`;
@@ -490,6 +514,7 @@ const skippedOrgsHtml = (
490
514
  export function renderSyncConfirm(
491
515
  agentId: string,
492
516
  preview: GithubSyncPreviewView,
517
+ timezone?: string,
493
518
  ): string {
494
519
  if (preview.status === "skipped") {
495
520
  return `<div class="alert alert-warning" data-sync="skipped">Sync was skipped: ${escapeHtml(preview.reason ?? "unknown reason")}</div>`;
@@ -498,7 +523,7 @@ export function renderSyncConfirm(
498
523
  const appRemoves = preview.appRemoves ?? [];
499
524
  const agentRemoves = preview.agentRemoves ?? [];
500
525
  const skippedList = preview.skippedOrgs ?? [];
501
- const skipped = skippedOrgsHtml(skippedList);
526
+ const skipped = skippedOrgsHtml(skippedList, timezone);
502
527
  const warnings = warningsHtml(
503
528
  withoutSkipWarnings(preview.warnings, skippedList),
504
529
  );
@@ -528,20 +553,21 @@ export function renderSyncConfirm(
528
553
  export function renderSyncResult(
529
554
  result: GithubSyncApplyView,
530
555
  blocked: readonly OpenWorkView[],
556
+ timezone?: string,
531
557
  ): string {
532
558
  if (result.status === "skipped") {
533
559
  return `<div class="alert alert-warning" data-sync="skipped">Sync was skipped: ${escapeHtml(result.reason ?? "unknown reason")}</div>`;
534
560
  }
535
561
  if (result.status === "noop") {
536
562
  const skippedList = result.skippedOrgs ?? [];
537
- return `<div class="alert alert-success" data-sync="noop">Nothing was changed.</div>${skippedOrgsHtml(skippedList)}${warningsHtml(withoutSkipWarnings(result.warnings, skippedList))}`;
563
+ return `<div class="alert alert-success" data-sync="noop">Nothing was changed.</div>${skippedOrgsHtml(skippedList, timezone)}${warningsHtml(withoutSkipWarnings(result.warnings, skippedList))}`;
538
564
  }
539
565
  const notApplied = result.notApplied ?? [];
540
566
  return `<div class="alert alert-success" data-sync="applied">Sync applied. Reload the page to refresh the lists.</div>${repoList("app-adds", "Added to the agent App installation", result.appAdds ?? [])}${repoList("app-removes", "Removed from the agent App installation", result.appRemoves ?? [])}${repoList("agent-removes", "Removed from the agent's repos", result.agentRemoves ?? [])}${
541
567
  notApplied.length === 0
542
568
  ? ""
543
569
  : `<div class="alert alert-warning" data-not-applied="1"><div style="font-weight:600">Left alone</div>${notApplied.map((n) => `<div><span class="mono">${escapeHtml(n.repo)}</span>: ${escapeHtml(n.reason)}</div>`).join("")}</div>`
544
- }${skippedOrgsHtml(result.skippedOrgs ?? [])}${renderOpenWorkByRepo(
570
+ }${skippedOrgsHtml(result.skippedOrgs ?? [], timezone)}${renderOpenWorkByRepo(
545
571
  blocked,
546
572
  "Open tasks and PRs that were blocked",
547
573
  "No open tasks or PRs were blocked.",
@@ -7,6 +7,7 @@ import { describe, expect, it } from "bun:test";
7
7
  import {
8
8
  APP_ID_MISMATCH_MESSAGE,
9
9
  actuallyBlockedWork,
10
+ formatSyncTime,
10
11
  NO_USERNAME_REASON,
11
12
  renderGithubSyncCard,
12
13
  renderInstallationReposBody,
@@ -376,7 +377,7 @@ describe("skipped-org detail", () => {
376
377
  ],
377
378
  });
378
379
  expect(line(html)).toBe(
379
- "Lookup crawl failed: rate limited; next attempt 2026-01-01T01:00:00.000Z.",
380
+ "Lookup crawl failed: rate limited; next attempt 2026-01-01 01:00 UTC.",
380
381
  );
381
382
  });
382
383
 
@@ -404,7 +405,7 @@ describe("skipped-org detail", () => {
404
405
  expect(t).toContain("2 repos errored.");
405
406
  expect(t).toContain("1 repo gave up (max 4 attempts).");
406
407
  expect(t).toContain("Row errors: boom; bang.");
407
- expect(t).toContain("Oldest check 2025-12-01T00:00:00.000Z.");
408
+ expect(t).toContain("Oldest check 2025-12-01 00:00 UTC.");
408
409
  });
409
410
 
410
411
  it("escapes lastError, rowErrors and org", () => {
@@ -482,3 +483,90 @@ describe("renderInstallationSyncStatus debug detail", () => {
482
483
  expect(renderInstallationSyncStatus({})).toBe("");
483
484
  });
484
485
  });
486
+
487
+ describe("installation sync timestamps in the admin timezone", () => {
488
+ const PT = "America/Los_Angeles";
489
+
490
+ it("formats Pacific time with the zone abbreviation (PST)", () => {
491
+ expect(formatSyncTime("2026-11-24T01:02:00.000Z", PT)).toBe(
492
+ "Nov 23, 5:02 PM PST",
493
+ );
494
+ });
495
+
496
+ it("uses PDT on the summer side of the DST boundary", () => {
497
+ expect(formatSyncTime("2026-03-08T09:59:00.000Z", PT)).toBe(
498
+ "Mar 8, 1:59 AM PST",
499
+ );
500
+ expect(formatSyncTime("2026-03-08T10:00:00.000Z", PT)).toBe(
501
+ "Mar 8, 3:00 AM PDT",
502
+ );
503
+ expect(formatSyncTime("2026-11-01T08:59:00.000Z", PT)).toBe(
504
+ "Nov 1, 1:59 AM PDT",
505
+ );
506
+ expect(formatSyncTime("2026-11-01T09:00:00.000Z", PT)).toBe(
507
+ "Nov 1, 1:00 AM PST",
508
+ );
509
+ });
510
+
511
+ it("falls back to labelled UTC when no timezone is set", () => {
512
+ expect(formatSyncTime("2026-11-24T01:02:00.000Z")).toBe(
513
+ "2026-11-24 01:02 UTC",
514
+ );
515
+ });
516
+
517
+ it("renders the sync status line in the timezone", () => {
518
+ const html = renderInstallationSyncStatus(
519
+ {
520
+ complete: false,
521
+ syncedAt: "2026-11-24T01:02:00.000Z",
522
+ rateLimitResetAt: "2026-11-24T02:00:00.000Z",
523
+ nextAttemptAt: "2026-11-24T02:30:00.000Z",
524
+ lastTickAt: "2026-11-24T01:00:00.000Z",
525
+ },
526
+ PT,
527
+ );
528
+ expect(html).toContain("Synced Nov 23, 5:02 PM PST");
529
+ expect(html).toContain("GitHub rate limit resets Nov 23, 6:00 PM PST");
530
+ expect(html).toContain("Next attempt Nov 23, 6:30 PM PST");
531
+ expect(html).toContain("Last tick Nov 23, 5:00 PM PST");
532
+ expect(html).not.toContain("UTC");
533
+ });
534
+
535
+ it("keeps UTC in the sync status line when unset", () => {
536
+ expect(
537
+ renderInstallationSyncStatus({
538
+ complete: true,
539
+ syncedAt: "2026-11-24T01:02:00.000Z",
540
+ }),
541
+ ).toContain("Synced 2026-11-24 01:02 UTC");
542
+ });
543
+
544
+ it("renders skipped-org detail times in the timezone", () => {
545
+ const html = renderSyncConfirm(
546
+ "a1",
547
+ {
548
+ status: "previewed",
549
+ appAdds: ["acme/new"],
550
+ skippedOrgs: [
551
+ {
552
+ org: "zed",
553
+ reason: "access listing is incomplete",
554
+ detail: {
555
+ crawls: [
556
+ {
557
+ completedAt: null,
558
+ lastError: "rate limited",
559
+ rateLimitResetAt: "2026-11-24T01:02:00.000Z",
560
+ },
561
+ ],
562
+ oldestCheckedAt: "2026-07-01T19:00:00.000Z",
563
+ },
564
+ },
565
+ ],
566
+ } as never,
567
+ PT,
568
+ );
569
+ expect(html).toContain("next attempt Nov 23, 5:02 PM PST");
570
+ expect(html).toContain("Oldest check Jul 1, 12:00 PM PDT");
571
+ });
572
+ });
@@ -485,7 +485,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
485
485
  );
486
486
  expect(html).toContain('data-installation-sync="complete"');
487
487
  expect(html).toContain("2 of 2 repos");
488
- expect(html).toContain("2026-11-20");
488
+ expect(html).toContain("Synced Nov 20, 2:00 AM PST");
489
489
  expect(html).toContain('id="repos-uncovered-warning"');
490
490
  // The page reads the cached view only: no GitHub-backed route.
491
491
  expect(
@@ -514,7 +514,7 @@ describe("admin UI — GitHub sync card (IRM-3.2)", () => {
514
514
  );
515
515
  expect(html).toContain("GitHub said &lt;no&gt;");
516
516
  expect(html).toContain("rate limit resets");
517
- expect(html).toContain("2026-11-20");
517
+ expect(html).toContain("resets Nov 20, 3:00 AM PST");
518
518
  expect(html).not.toContain("repos-uncovered-warning");
519
519
  });
520
520
 
@@ -1749,7 +1749,7 @@ export function renderAgentDetailPage(
1749
1749
  <button type="submit" class="btn btn-primary">Add</button>
1750
1750
  </div>
1751
1751
  </form>
1752
- ${opts?.installationSync ? renderInstallationSyncStatus(opts.installationSync) : ""}
1752
+ ${opts?.installationSync ? renderInstallationSyncStatus(opts.installationSync, timezone) : ""}
1753
1753
  <div class="data-table-wrapper">
1754
1754
  <table class="data-table">
1755
1755
  <thead>
package/src/admin-ui.ts CHANGED
@@ -2270,7 +2270,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2270
2270
  }
2271
2271
  }
2272
2272
  }
2273
- return html(renderInstallationReposBody(view, { appIdMismatch }));
2273
+ return html(renderInstallationReposBody(view, { appIdMismatch, timezone }));
2274
2274
  });
2275
2275
 
2276
2276
  // IRM-3.2: the single Sync confirm (over the IRM-3.1 preview) and its apply.
@@ -2288,6 +2288,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2288
2288
  renderSyncConfirm(
2289
2289
  c.req.param("id") ?? "",
2290
2290
  (await res.json()) as GithubSyncPreviewView,
2291
+ timezone,
2291
2292
  ),
2292
2293
  );
2293
2294
  });
@@ -2357,6 +2358,7 @@ export function createAdminUIApp(deps: AdminUIDeps): Hono<AdminUIEnv> {
2357
2358
  warnings,
2358
2359
  )
2359
2360
  : [],
2361
+ timezone,
2360
2362
  ),
2361
2363
  );
2362
2364
  },
@@ -32,6 +32,19 @@ import {
32
32
  */
33
33
  export const DEPLOYMENT_WIDE_ACCOUNT_KEY = "deployment";
34
34
 
35
+ /**
36
+ * The SnapshotKey.accountId values a lookup reads for an agent: its own
37
+ * account (when it has one) plus DEPLOYMENT_WIDE_ACCOUNT_KEY, where the
38
+ * crawler files deployment-wide App snapshots. A null/empty account reads only
39
+ * the deployment key. Note: a real account literally named "deployment" would
40
+ * collide with this fallback key; that is known and deliberately not fixed.
41
+ */
42
+ export function lookupAccountKeys(accountId?: string | null): string[] {
43
+ return accountId
44
+ ? [accountId, DEPLOYMENT_WIDE_ACCOUNT_KEY]
45
+ : [DEPLOYMENT_WIDE_ACCOUNT_KEY];
46
+ }
47
+
35
48
  /** The slice of the installer client the crawl needs. */
36
49
  export type AgentInstallationClient = Pick<
37
50
  InstallationRepoClient,
@@ -11,6 +11,7 @@ import {
11
11
  agentInstallationPageSource,
12
12
  crawlAgentInstallation,
13
13
  DEPLOYMENT_WIDE_ACCOUNT_KEY,
14
+ lookupAccountKeys,
14
15
  type AgentInstallationClient,
15
16
  } from "./github-agent-installation-crawler.ts";
16
17
  import type {
@@ -355,3 +356,23 @@ describe("crawlAgentInstallation", () => {
355
356
  expect(store.snap?.attempts).toBe(1);
356
357
  });
357
358
  });
359
+
360
+ describe("lookupAccountKeys", () => {
361
+ it("a deployment-wide agent (no account) reads only the deployment key", () => {
362
+ expect(lookupAccountKeys(null)).toEqual([DEPLOYMENT_WIDE_ACCOUNT_KEY]);
363
+ expect(lookupAccountKeys(undefined)).toEqual([DEPLOYMENT_WIDE_ACCOUNT_KEY]);
364
+ expect(lookupAccountKeys("")).toEqual([DEPLOYMENT_WIDE_ACCOUNT_KEY]);
365
+ });
366
+
367
+ it("an account agent reads its own account and the deployment key", () => {
368
+ expect(lookupAccountKeys("acct")).toEqual([
369
+ "acct",
370
+ DEPLOYMENT_WIDE_ACCOUNT_KEY,
371
+ ]);
372
+ });
373
+
374
+ it("never includes the empty-string key", () => {
375
+ expect(lookupAccountKeys(null)).not.toContain("");
376
+ expect(lookupAccountKeys("acct")).not.toContain("");
377
+ });
378
+ });
@@ -36,6 +36,7 @@ import {
36
36
  UnprocessableEntityError,
37
37
  } from "./errors.ts";
38
38
  import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
39
+ import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
39
40
  import { fetchAuthenticatedApp, fetchPublicApp } from "./github-app-api.ts";
40
41
  import {
41
42
  GITHUB_ENTERPRISE_APP_ROLES,
@@ -563,10 +564,8 @@ export function createGithubLookupService(
563
564
  if (!lookupKey || (installer?.enterpriseSlug && !installerKey)) {
564
565
  return { configured: false, repos: [] };
565
566
  }
566
- // The crawler files a deployment-wide App's snapshots under accountId "".
567
- const accountIds = accountId ? [accountId, ""] : [""];
568
567
  const snapshots = await deps.cache.listLookupSnapshots(
569
- accountIds,
568
+ lookupAccountKeys(accountId),
570
569
  lookup.appId,
571
570
  );
572
571
  return summarizeLookupSnapshots(
@@ -13,7 +13,7 @@ import type { GithubAccessPreviewFn } from "./github-access-preview.ts";
13
13
  import type { Clock } from "./clock.ts";
14
14
  import type { GitHubEnterpriseAppService } from "./github-enterprise-apps.ts";
15
15
  import { GithubEnterpriseClient } from "./github-enterprise-client.ts";
16
- import { DEPLOYMENT_WIDE_ACCOUNT_KEY } from "./github-agent-installation-crawler.ts";
16
+ import { lookupAccountKeys } from "./github-agent-installation-crawler.ts";
17
17
  import { GithubLookupClient } from "./github-lookup-client.ts";
18
18
  import { GitHubRepoCacheService } from "./github-repo-cache.ts";
19
19
  import type { CrawlStore } from "./github-repo-crawler.ts";
@@ -159,15 +159,8 @@ export function createGithubSync(
159
159
  lookupRepos: async (accountId) => {
160
160
  const lookup = await lookupClient(accountId);
161
161
  if (!lookup) return [];
162
- // The crawler files a deployment-wide App's snapshots under
163
- // DEPLOYMENT_WIDE_ACCOUNT_KEY, so a null-account agent reads that key and
164
- // an account agent reads its own account plus that key.
165
- // Note: a real account literally named "deployment" would collide with
166
- // this fallback key; that is known and deliberately not fixed here.
167
162
  const snapshots = await cache.listLookupOrgSnapshots(
168
- accountId
169
- ? [accountId, DEPLOYMENT_WIDE_ACCOUNT_KEY]
170
- : [DEPLOYMENT_WIDE_ACCOUNT_KEY],
163
+ lookupAccountKeys(accountId),
171
164
  lookup.appId,
172
165
  );
173
166
  return snapshots.map((s) => ({
@@ -83,4 +83,20 @@ describeOrSkip("githubLookup.listRepositories (cache, integration)", () => {
83
83
  expect(done.repos).toHaveLength(2);
84
84
  expect(done.fetchedAt).toEqual(NOW);
85
85
  });
86
+
87
+ it("null-account lookup reads a deployment-wide snapshot filed under 'deployment'", async () => {
88
+ const snap = await cache.upsertSnapshot(
89
+ { ...key("acme"), accountId: "deployment" },
90
+ { crawlPage: 1, crawlStartedAt: NOW, totalCount: 1 },
91
+ );
92
+ await cache.upsertRepos(snap.id, [{ githubId: 3, fullName: "acme/c" }]);
93
+ await cache.upsertSnapshot(
94
+ { ...key("acme"), accountId: "deployment" },
95
+ { completedAt: NOW },
96
+ );
97
+ const r = await svc().listRepositories(null);
98
+ expect(r.configured).toBe(true);
99
+ expect(r.syncState).toBe("ready");
100
+ expect(r.repos).toEqual([{ fullName: "acme/c", archived: false }]);
101
+ });
86
102
  });
@@ -198,8 +198,69 @@ describe("createGithubLookupService", () => {
198
198
  const { svc, calls } = build({ lookup: lookupRow }, [snap()]);
199
199
  const r = await svc.listRepositories("acct");
200
200
  expect(r.syncState).toBe("ready");
201
- expect(calls[0]).toEqual([["acct", ""], "555"]);
202
- await svc.listRepositories();
203
- expect(calls[1]).toEqual([[""], "555"]);
201
+ expect(calls[0]).toEqual([["acct", "deployment"], "555"]);
202
+ });
203
+
204
+ describe("against a cache seeded under the real keys", () => {
205
+ /** Fake cache that only returns snapshots filed under a requested accountId. */
206
+ function seededCache(seed: Record<string, LookupSnapshotView[]>) {
207
+ const calls: string[][] = [];
208
+ return {
209
+ calls,
210
+ cache: {
211
+ listLookupSnapshots: async (accountIds: string[]) => {
212
+ calls.push(accountIds);
213
+ return accountIds.flatMap((id) => seed[id] ?? []);
214
+ },
215
+ },
216
+ };
217
+ }
218
+ const deploymentApps = {
219
+ get: async (role: string) => (role === "lookup" ? lookupRow : null),
220
+ getPrivateKey: async (role: string) => (role === "lookup" ? "pem" : null),
221
+ } as unknown as GitHubEnterpriseAppService;
222
+
223
+ it("deployment-wide lookup App (null account) reads the 'deployment' key: ready", async () => {
224
+ const { cache, calls } = seededCache({
225
+ deployment: [snap({ completedAt: ago(5 * MIN) })],
226
+ });
227
+ const svc = createGithubLookupService({
228
+ appService: deploymentApps,
229
+ cache,
230
+ now: () => NOW,
231
+ });
232
+ const r = await svc.listRepositories(null);
233
+ expect(calls).toEqual([["deployment"]]);
234
+ expect(r.configured).toBe(true);
235
+ expect(r.syncState).toBe("ready");
236
+ expect(r.repos.map((x) => x.fullName)).toEqual(["acme/a", "acme/b"]);
237
+ });
238
+
239
+ it("account-scoped lookup also serves the deployment-wide snapshots", async () => {
240
+ const { cache, calls } = seededCache({
241
+ deployment: [snap({ completedAt: ago(5 * MIN) })],
242
+ });
243
+ const svc = createGithubLookupService({
244
+ appService: deploymentApps,
245
+ cache,
246
+ now: () => NOW,
247
+ });
248
+ const r = await svc.listRepositories("acct");
249
+ expect(calls).toEqual([["acct", "deployment"]]);
250
+ expect(r.syncState).toBe("ready");
251
+ expect(r.repos).toHaveLength(2);
252
+ });
253
+
254
+ it("never queries the empty-string key", async () => {
255
+ const { cache, calls } = seededCache({});
256
+ const svc = createGithubLookupService({
257
+ appService: deploymentApps,
258
+ cache,
259
+ now: () => NOW,
260
+ });
261
+ await svc.listRepositories();
262
+ await svc.listRepositories("acct");
263
+ expect(calls.flat()).not.toContain("");
264
+ });
204
265
  });
205
266
  });