lastlight-core 0.23.8 → 0.24.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.
Files changed (34) hide show
  1. package/deploy/.env.production.example +3 -1
  2. package/deploy/native/lastlight.env.example +3 -1
  3. package/dist/admin/routes.js +24 -1
  4. package/dist/admin/routes.js.map +1 -1
  5. package/dist/config/config.d.ts +11 -2
  6. package/dist/config/config.js +2 -1
  7. package/dist/config/config.js.map +1 -1
  8. package/dist/connectors/github-webhook.d.ts +12 -0
  9. package/dist/connectors/github-webhook.js +54 -13
  10. package/dist/connectors/github-webhook.js.map +1 -1
  11. package/dist/engine/agent-executor.js +66 -21
  12. package/dist/engine/agent-executor.js.map +1 -1
  13. package/dist/engine/github/app-jwt.d.ts +12 -0
  14. package/dist/engine/github/app-jwt.js +25 -0
  15. package/dist/engine/github/app-jwt.js.map +1 -0
  16. package/dist/engine/github/git-auth.js +2 -12
  17. package/dist/engine/github/git-auth.js.map +1 -1
  18. package/dist/engine/github/github-tools.d.ts +16 -4
  19. package/dist/engine/github/github-tools.js +58 -3
  20. package/dist/engine/github/github-tools.js.map +1 -1
  21. package/dist/engine/github/github.d.ts +68 -9
  22. package/dist/engine/github/github.js +167 -42
  23. package/dist/engine/github/github.js.map +1 -1
  24. package/dist/engine/github/installations.d.ts +129 -0
  25. package/dist/engine/github/installations.js +264 -0
  26. package/dist/engine/github/installations.js.map +1 -0
  27. package/dist/index.js +69 -27
  28. package/dist/index.js.map +1 -1
  29. package/dist/managed-repos.d.ts +14 -7
  30. package/dist/managed-repos.js +48 -22
  31. package/dist/managed-repos.js.map +1 -1
  32. package/dist/workflows/handlers/post-review.js +0 -1
  33. package/dist/workflows/handlers/post-review.js.map +1 -1
  34. package/package.json +2 -2
@@ -0,0 +1,129 @@
1
+ /**
2
+ * One installation of the GitHub App — i.e. one account (user or org) that
3
+ * installed it. A single App has N of these, and **each has its own
4
+ * installation id**, which is what an installation-token mint is scoped to.
5
+ */
6
+ export interface AppInstallation {
7
+ /** Installation id, as a string (the mint URL takes it verbatim). */
8
+ id: string;
9
+ /** Account login the App is installed on (`cliftonc`, `mirevue`, …). */
10
+ account: string;
11
+ accountType: string;
12
+ /** `all` = every repo in the account; `selected` = an explicit subset. */
13
+ repositorySelection: "all" | "selected";
14
+ suspended: boolean;
15
+ }
16
+ export interface InstallationDirectoryConfig {
17
+ appId: string;
18
+ privateKeyPath: string;
19
+ /**
20
+ * Override the GitHub REST base URL. Prod leaves this unset →
21
+ * `api.github.com`. Mirrors `GitHubAppClientConfig.baseUrl` — a test/eval
22
+ * escape hatch only.
23
+ */
24
+ baseUrl?: string;
25
+ /**
26
+ * Optional legacy seed: the single `GITHUB_APP_INSTALLATION_ID` an older
27
+ * deployment configured. It carries no account login, so it can't answer
28
+ * `resolve()` on its own — it's kept only as the last-resort answer when the
29
+ * App JWT lookup is unavailable (no network, a revoked PEM), so an existing
30
+ * single-installation deployment degrades to exactly its old behaviour rather
31
+ * than to no behaviour.
32
+ */
33
+ fallbackInstallationId?: string;
34
+ }
35
+ /**
36
+ * The single authority for **owner → installation id**.
37
+ *
38
+ * A GitHub App is installed per *account*, so an App installed on two accounts
39
+ * has two installation ids and a token minted against the wrong one 422s with
40
+ * "at least one repository ... is not accessible to the parent installation".
41
+ * Last Light used to carry one statically-configured id
42
+ * (`GITHUB_APP_INSTALLATION_ID`) threaded into every mint and every
43
+ * App-authenticated Octokit, which is exactly that bug for every account but the
44
+ * first.
45
+ *
46
+ * Two feeds, both cheap:
47
+ * - **`note()`** — every webhook delivery carries `payload.installation.id`
48
+ * alongside the account login. Authoritative, free, and covers the account
49
+ * the event came from before we ever ask GitHub anything.
50
+ * - **`refresh()`** — `GET /app/installations` under an App JWT. Needed for the
51
+ * routes with no webhook behind them (boot discovery, cron fan-out, CLI/API
52
+ * triggers).
53
+ *
54
+ * A miss triggers at most one in-flight refresh (`REFRESH_MIN_INTERVAL_MS`
55
+ * apart), so a cron fanning out over N repos in an uninstalled org costs one
56
+ * request, not N.
57
+ */
58
+ export declare class InstallationDirectory {
59
+ private readonly config;
60
+ /** owner login (lowercased) → installation id. */
61
+ private byOwner;
62
+ /** installation id → the full record, for the admin/ops surface. */
63
+ private byId;
64
+ /** owner login (lowercased) → epoch ms when "not installed" was concluded. */
65
+ private negative;
66
+ private inFlight;
67
+ private lastRefreshAt;
68
+ constructor(config: InstallationDirectoryConfig);
69
+ /**
70
+ * Record an owner→installation mapping learned out of band (a webhook
71
+ * payload). Cheaper and fresher than any lookup, so it always wins.
72
+ */
73
+ note(owner: string, id: string | number | undefined | null): void;
74
+ /** Drop an installation entirely (the App was uninstalled from that account). */
75
+ forget(id: string | number): void;
76
+ /**
77
+ * Mark an installation suspended or restored.
78
+ *
79
+ * A suspended installation still EXISTS — it stays in the listing and keeps
80
+ * its id — but every token mint against it 403s. So it is dropped from
81
+ * `resolve()` (the run fails fast, before a sandbox) while staying in
82
+ * `list()`, where the admin surface can say "suspended" rather than the
83
+ * account simply vanishing.
84
+ */
85
+ setSuspended(id: string | number, suspended: boolean): void;
86
+ /** Cached snapshot — never triggers a fetch. Ordered by account login. */
87
+ list(): AppInstallation[];
88
+ /**
89
+ * The installation id when the App is installed on exactly ONE account.
90
+ *
91
+ * The answer for a run that names no owner (a Slack-scoped `explore`, say):
92
+ * it still wants a GitHub token, and with a single installation there is no
93
+ * ambiguity about which — that is the deployment this harness supported
94
+ * before it grew multi-installation support, so it keeps behaving identically.
95
+ * With several installations there is no defensible pick, so the caller goes
96
+ * without a token rather than guessing an account.
97
+ */
98
+ soleInstallationId(): Promise<string | undefined>;
99
+ /**
100
+ * The installation id for `owner`, or `undefined` when the App isn't
101
+ * installed on that account. Cache → one shared refresh → a cached negative.
102
+ *
103
+ * `undefined` means **we asked and the App is genuinely not installed there**,
104
+ * so the caller can fail with an actionable "install the App on `<owner>`"
105
+ * message instead of letting a mint 422 with GitHub's opaque wording. A
106
+ * lookup *failure* (network, bad PEM) is a different thing and falls back to
107
+ * the legacy single id rather than claiming the account isn't installed.
108
+ */
109
+ resolve(owner: string): Promise<string | undefined>;
110
+ /**
111
+ * Re-read every installation of the App. Concurrent callers share one
112
+ * request — a cron fan-out resolves N owners against a single round-trip.
113
+ */
114
+ refresh(): Promise<AppInstallation[]>;
115
+ private fetchAll;
116
+ }
117
+ /**
118
+ * Install the process-wide directory. Called once at boot from the App creds in
119
+ * runtime config; safe to call again (a re-init replaces the cache).
120
+ */
121
+ export declare function initInstallationDirectory(config: InstallationDirectoryConfig): InstallationDirectory;
122
+ /**
123
+ * The process-wide directory, or `undefined` when no GitHub App is configured
124
+ * (PAT / chat-only mode). Callers that need a mapping must handle `undefined` —
125
+ * they are in token mode, where there is no installation to resolve.
126
+ */
127
+ export declare function getInstallationDirectory(): InstallationDirectory | undefined;
128
+ /** Test-only: drop the singleton so each test starts from a clean directory. */
129
+ export declare function resetInstallationDirectoryForTests(): void;
@@ -0,0 +1,264 @@
1
+ import { logger } from "../../logging/logger.js";
2
+ import { appJwt } from "./app-jwt.js";
3
+ const log = logger("installations");
4
+ /** How long a "this owner has no installation" answer is trusted. */
5
+ const NEGATIVE_TTL_MS = 60_000;
6
+ /** Floor between two full refreshes triggered by a cache miss. */
7
+ const REFRESH_MIN_INTERVAL_MS = 10_000;
8
+ /**
9
+ * The single authority for **owner → installation id**.
10
+ *
11
+ * A GitHub App is installed per *account*, so an App installed on two accounts
12
+ * has two installation ids and a token minted against the wrong one 422s with
13
+ * "at least one repository ... is not accessible to the parent installation".
14
+ * Last Light used to carry one statically-configured id
15
+ * (`GITHUB_APP_INSTALLATION_ID`) threaded into every mint and every
16
+ * App-authenticated Octokit, which is exactly that bug for every account but the
17
+ * first.
18
+ *
19
+ * Two feeds, both cheap:
20
+ * - **`note()`** — every webhook delivery carries `payload.installation.id`
21
+ * alongside the account login. Authoritative, free, and covers the account
22
+ * the event came from before we ever ask GitHub anything.
23
+ * - **`refresh()`** — `GET /app/installations` under an App JWT. Needed for the
24
+ * routes with no webhook behind them (boot discovery, cron fan-out, CLI/API
25
+ * triggers).
26
+ *
27
+ * A miss triggers at most one in-flight refresh (`REFRESH_MIN_INTERVAL_MS`
28
+ * apart), so a cron fanning out over N repos in an uninstalled org costs one
29
+ * request, not N.
30
+ */
31
+ export class InstallationDirectory {
32
+ config;
33
+ /** owner login (lowercased) → installation id. */
34
+ byOwner = new Map();
35
+ /** installation id → the full record, for the admin/ops surface. */
36
+ byId = new Map();
37
+ /** owner login (lowercased) → epoch ms when "not installed" was concluded. */
38
+ negative = new Map();
39
+ inFlight = null;
40
+ lastRefreshAt = 0;
41
+ constructor(config) {
42
+ this.config = config;
43
+ }
44
+ /**
45
+ * Record an owner→installation mapping learned out of band (a webhook
46
+ * payload). Cheaper and fresher than any lookup, so it always wins.
47
+ */
48
+ note(owner, id) {
49
+ if (!owner || id === undefined || id === null || id === "")
50
+ return;
51
+ const key = owner.toLowerCase();
52
+ const value = String(id);
53
+ // Never resurrect a suspended installation: it still delivers its own
54
+ // `installation` events, and resolving to it would put the account back in
55
+ // service against tokens GitHub will 403.
56
+ if (this.byId.get(value)?.suspended)
57
+ return;
58
+ this.negative.delete(key);
59
+ if (this.byOwner.get(key) === value)
60
+ return;
61
+ this.byOwner.set(key, value);
62
+ if (!this.byId.has(value)) {
63
+ this.byId.set(value, {
64
+ id: value,
65
+ account: owner,
66
+ accountType: "",
67
+ repositorySelection: "all",
68
+ suspended: false,
69
+ });
70
+ }
71
+ log.info("Learned installation from event", { owner, installationId: value });
72
+ }
73
+ /** Drop an installation entirely (the App was uninstalled from that account). */
74
+ forget(id) {
75
+ const value = String(id);
76
+ const record = this.byId.get(value);
77
+ this.byId.delete(value);
78
+ for (const [owner, installationId] of this.byOwner) {
79
+ if (installationId === value)
80
+ this.byOwner.delete(owner);
81
+ }
82
+ log.info("Forgot installation", { installationId: value, account: record?.account });
83
+ }
84
+ /**
85
+ * Mark an installation suspended or restored.
86
+ *
87
+ * A suspended installation still EXISTS — it stays in the listing and keeps
88
+ * its id — but every token mint against it 403s. So it is dropped from
89
+ * `resolve()` (the run fails fast, before a sandbox) while staying in
90
+ * `list()`, where the admin surface can say "suspended" rather than the
91
+ * account simply vanishing.
92
+ */
93
+ setSuspended(id, suspended) {
94
+ const value = String(id);
95
+ const record = this.byId.get(value);
96
+ if (record)
97
+ record.suspended = suspended;
98
+ const account = record?.account;
99
+ if (suspended) {
100
+ for (const [owner, installationId] of this.byOwner) {
101
+ if (installationId === value)
102
+ this.byOwner.delete(owner);
103
+ }
104
+ }
105
+ else if (account) {
106
+ this.byOwner.set(account.toLowerCase(), value);
107
+ this.negative.delete(account.toLowerCase());
108
+ }
109
+ log.info(suspended ? "Installation suspended" : "Installation unsuspended", {
110
+ installationId: value,
111
+ account,
112
+ });
113
+ }
114
+ /** Cached snapshot — never triggers a fetch. Ordered by account login. */
115
+ list() {
116
+ return [...this.byId.values()].sort((a, b) => a.account.localeCompare(b.account));
117
+ }
118
+ /**
119
+ * The installation id when the App is installed on exactly ONE account.
120
+ *
121
+ * The answer for a run that names no owner (a Slack-scoped `explore`, say):
122
+ * it still wants a GitHub token, and with a single installation there is no
123
+ * ambiguity about which — that is the deployment this harness supported
124
+ * before it grew multi-installation support, so it keeps behaving identically.
125
+ * With several installations there is no defensible pick, so the caller goes
126
+ * without a token rather than guessing an account.
127
+ */
128
+ async soleInstallationId() {
129
+ if (this.byId.size === 0) {
130
+ try {
131
+ await this.refresh();
132
+ }
133
+ catch {
134
+ return this.config.fallbackInstallationId;
135
+ }
136
+ }
137
+ if (this.byId.size === 1)
138
+ return [...this.byId.keys()][0];
139
+ return this.byId.size === 0 ? this.config.fallbackInstallationId : undefined;
140
+ }
141
+ /**
142
+ * The installation id for `owner`, or `undefined` when the App isn't
143
+ * installed on that account. Cache → one shared refresh → a cached negative.
144
+ *
145
+ * `undefined` means **we asked and the App is genuinely not installed there**,
146
+ * so the caller can fail with an actionable "install the App on `<owner>`"
147
+ * message instead of letting a mint 422 with GitHub's opaque wording. A
148
+ * lookup *failure* (network, bad PEM) is a different thing and falls back to
149
+ * the legacy single id rather than claiming the account isn't installed.
150
+ */
151
+ async resolve(owner) {
152
+ if (!owner)
153
+ return undefined;
154
+ const key = owner.toLowerCase();
155
+ const cached = this.byOwner.get(key);
156
+ if (cached)
157
+ return cached;
158
+ const deniedAt = this.negative.get(key);
159
+ if (deniedAt !== undefined && Date.now() - deniedAt < NEGATIVE_TTL_MS) {
160
+ return undefined;
161
+ }
162
+ if (Date.now() - this.lastRefreshAt >= REFRESH_MIN_INTERVAL_MS || this.inFlight) {
163
+ try {
164
+ await this.refresh();
165
+ }
166
+ catch (err) {
167
+ // Never cache a negative off a failed lookup — that would report a
168
+ // perfectly good installation as missing for the next minute.
169
+ log.warn("Installation lookup failed", { owner, err });
170
+ return this.config.fallbackInstallationId;
171
+ }
172
+ const found = this.byOwner.get(key);
173
+ if (found)
174
+ return found;
175
+ }
176
+ this.negative.set(key, Date.now());
177
+ return undefined;
178
+ }
179
+ /**
180
+ * Re-read every installation of the App. Concurrent callers share one
181
+ * request — a cron fan-out resolves N owners against a single round-trip.
182
+ */
183
+ refresh() {
184
+ if (this.inFlight)
185
+ return this.inFlight;
186
+ this.inFlight = this.fetchAll().finally(() => {
187
+ this.inFlight = null;
188
+ this.lastRefreshAt = Date.now();
189
+ });
190
+ return this.inFlight;
191
+ }
192
+ async fetchAll() {
193
+ const jwt = appJwt(this.config.appId, this.config.privateKeyPath);
194
+ const base = (this.config.baseUrl ?? "https://api.github.com").replace(/\/+$/, "");
195
+ const found = [];
196
+ // `GET /app/installations` is App-JWT-authed and paginated. 100/page is the
197
+ // maximum; an App with more than a handful of installations is unusual, but
198
+ // paginating costs nothing and a truncated list would silently look like
199
+ // "not installed" for every account past the first page.
200
+ for (let page = 1; page <= 20; page++) {
201
+ const res = await fetch(`${base}/app/installations?per_page=100&page=${page}`, {
202
+ headers: {
203
+ Authorization: `Bearer ${jwt}`,
204
+ Accept: "application/vnd.github+json",
205
+ },
206
+ });
207
+ if (!res.ok) {
208
+ throw new Error(`GitHub App installations request failed (${res.status}): ${await res.text()}`);
209
+ }
210
+ const batch = (await res.json());
211
+ if (!Array.isArray(batch) || batch.length === 0)
212
+ break;
213
+ for (const raw of batch) {
214
+ const account = raw.account?.login;
215
+ if (!account)
216
+ continue;
217
+ found.push({
218
+ id: String(raw.id),
219
+ account,
220
+ accountType: raw.account?.type ?? "",
221
+ repositorySelection: raw.repository_selection === "selected" ? "selected" : "all",
222
+ suspended: !!raw.suspended_at,
223
+ });
224
+ }
225
+ if (batch.length < 100)
226
+ break;
227
+ }
228
+ // Replace wholesale — an installation that vanished from the listing was
229
+ // uninstalled, and keeping its stale mapping would keep minting 404s. A
230
+ // SUSPENDED one is still listed but cannot mint, so it is kept for the admin
231
+ // surface and withheld from resolution.
232
+ this.byOwner = new Map(found.filter((i) => !i.suspended).map((i) => [i.account.toLowerCase(), i.id]));
233
+ this.byId = new Map(found.map((i) => [i.id, i]));
234
+ this.negative.clear();
235
+ log.info("Refreshed App installations", {
236
+ count: found.length,
237
+ accounts: found.map((i) => `${i.account}=${i.id}`).join(","),
238
+ });
239
+ return found;
240
+ }
241
+ }
242
+ // ── Module singleton ────────────────────────────────────────────────
243
+ let directory = null;
244
+ /**
245
+ * Install the process-wide directory. Called once at boot from the App creds in
246
+ * runtime config; safe to call again (a re-init replaces the cache).
247
+ */
248
+ export function initInstallationDirectory(config) {
249
+ directory = new InstallationDirectory(config);
250
+ return directory;
251
+ }
252
+ /**
253
+ * The process-wide directory, or `undefined` when no GitHub App is configured
254
+ * (PAT / chat-only mode). Callers that need a mapping must handle `undefined` —
255
+ * they are in token mode, where there is no installation to resolve.
256
+ */
257
+ export function getInstallationDirectory() {
258
+ return directory ?? undefined;
259
+ }
260
+ /** Test-only: drop the singleton so each test starts from a clean directory. */
261
+ export function resetInstallationDirectoryForTests() {
262
+ directory = null;
263
+ }
264
+ //# sourceMappingURL=installations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"installations.js","sourceRoot":"","sources":["../../../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AAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;QACjD,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,CAAC;QAEtB,GAAG,CAAC,IAAI,CAAC,6BAA6B,EAAE;YACtC,KAAK,EAAE,KAAK,CAAC,MAAM;YACnB,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC;SAC7D,CAAC,CAAC;QACH,OAAO,KAAK,CAAC;IACf,CAAC;CACF;AAED,uEAAuE;AAEvE,IAAI,SAAS,GAAiC,IAAI,CAAC;AAEnD;;;GAGG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAAmC;IAEnC,SAAS,GAAG,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC9C,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB;IACtC,OAAO,SAAS,IAAI,SAAS,CAAC;AAChC,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,kCAAkC;IAChD,SAAS,GAAG,IAAI,CAAC;AACnB,CAAC"}
package/dist/index.js CHANGED
@@ -12,6 +12,7 @@ import { configureWorkflowAssets, validateAssets, getWorkflow } from "./workflow
12
12
  import { ChatRunner } from "./engine/chat/chat-runner.js";
13
13
  import { buildReadSkillTool, loadChatSkillCatalogue } from "./engine/chat/chat-skills.js";
14
14
  import { configureGitAuth } from "./engine/github/git-auth.js";
15
+ import { getInstallationDirectory, initInstallationDirectory, } from "./engine/github/installations.js";
15
16
  import { StateDb, isTriggerActorType } from "./state/db.js";
16
17
  import { CronScheduler } from "./cron/scheduler.js";
17
18
  import { getJobs } from "./cron/jobs.js";
@@ -73,9 +74,13 @@ function validateConfig(config) {
73
74
  process.exit(78); // EX_CONFIG — sysexits.h convention
74
75
  };
75
76
  if (config.githubApp) {
76
- const { appId, privateKeyPath, installationId } = config.githubApp;
77
- if (!appId || !installationId) {
78
- fatal("GITHUB_APP_ID and GITHUB_APP_INSTALLATION_ID are required when the GitHub App is configured.");
77
+ const { appId, privateKeyPath } = config.githubApp;
78
+ // No installation-id check: installations are DISCOVERED from the App JWT
79
+ // and resolved per repo owner, because an App installed on several accounts
80
+ // has one id per account. `GITHUB_APP_INSTALLATION_ID` is honoured as a
81
+ // legacy fallback when set, and is no longer required.
82
+ if (!appId) {
83
+ fatal("GITHUB_APP_ID is required when the GitHub App is configured.");
79
84
  }
80
85
  if (!existsSync(resolve(privateKeyPath))) {
81
86
  fatal(`GITHUB_APP_PRIVATE_KEY_PATH points to "${privateKeyPath}" which does not exist.`);
@@ -210,21 +215,16 @@ async function main() {
210
215
  else {
211
216
  chatLog.warn("No skills loaded — frontmatter missing or no matching SKILL.md found");
212
217
  }
213
- // Configure git with GitHub App credentials — agents can git clone/push natively.
214
- // Non-fatal: the token is refreshed before each agent execution anyway, so a
215
- // transient failure here (DNS, rate limit) doesn't block startup.
218
+ // The App may be installed on several ACCOUNTS, each with its own installation
219
+ // id — and a token minted against the wrong one is rejected. The directory is
220
+ // the single owner→installation authority every mint and every App-authed
221
+ // Octokit resolves through, so it has to exist before either.
216
222
  if (config.githubApp) {
217
- try {
218
- await configureGitAuth({
219
- appId: config.githubApp.appId,
220
- privateKeyPath: config.githubApp.privateKeyPath,
221
- installationId: config.githubApp.installationId,
222
- botLogin: config.botLogin,
223
- });
224
- }
225
- catch (err) {
226
- logger("git-auth").warn("Initial token mint failed (will retry per-execution)", { err });
227
- }
223
+ initInstallationDirectory({
224
+ appId: config.githubApp.appId,
225
+ privateKeyPath: config.githubApp.privateKeyPath,
226
+ fallbackInstallationId: config.githubApp.installationId,
227
+ });
228
228
  }
229
229
  // GitHub API client for harness-level operations (posting comments, fetching
230
230
  // issues). App auth when configured; otherwise a PAT (read-only unless the
@@ -244,21 +244,60 @@ async function main() {
244
244
  botLogin: config.botLogin,
245
245
  botMention: `@${config.botName}`,
246
246
  });
247
- // Discover the repos the App installation can access and seed the managed-repo
248
- // list. When the overlay's `managedRepos` is empty this becomes the effective
249
- // allowlist (getManagedRepos falls back to it); a configured list still wins.
250
- // Kept live afterwards by installation webhooks (github-webhook.ts). Non-fatal:
251
- // on failure we fall back to whatever `managedRepos` config provides. Runs
252
- // before the HTTP listener opens, so the list is warm before the first event.
247
+ // Discover the repos the App can access — across EVERY installation — and seed
248
+ // the managed-repo list. When the overlay's `managedRepos` is empty this
249
+ // becomes the effective allowlist (getManagedRepos falls back to the union); a
250
+ // configured list still wins. Kept live afterwards by installation webhooks
251
+ // (github-webhook.ts). Non-fatal: on failure we fall back to whatever
252
+ // `managedRepos` config provides. Runs before the HTTP listener opens, so the
253
+ // list is warm before the first event.
253
254
  if (github && config.githubApp) {
254
255
  const githubLog = logger("github");
255
256
  try {
256
- const repos = await github.listInstallationRepos();
257
- setInstallationRepos(repos);
258
- githubLog.info("Discovered installation repos", { count: repos.length });
257
+ const grants = await github.listAllInstallationRepos();
258
+ for (const grant of grants) {
259
+ if (grant.error) {
260
+ githubLog.warn("Installation repo discovery failed for one account", {
261
+ account: grant.account,
262
+ installationId: grant.installationId,
263
+ error: grant.error,
264
+ });
265
+ continue;
266
+ }
267
+ setInstallationRepos(grant.installationId, grant.repos);
268
+ }
269
+ githubLog.info("Discovered App installations", {
270
+ installations: grants.length,
271
+ accounts: grants.map((g) => `${g.account}=${g.installationId}(${g.repos.length})`).join(","),
272
+ });
273
+ if (grants.length === 0) {
274
+ githubLog.warn("The GitHub App has no installations — install it on an account before it can act");
275
+ }
276
+ }
277
+ catch (err) {
278
+ githubLog.warn("Installation discovery failed", { err });
279
+ }
280
+ }
281
+ // Configure git with a GitHub App token — only meaningful when the operator
282
+ // opted into a global `~/.gitconfig` write (LASTLIGHT_WRITE_GLOBAL_GIT=1) and
283
+ // only defensible with a single installation, since a global credential can
284
+ // name exactly one. Every agent run mints its own owner-scoped token
285
+ // regardless, so this is non-fatal and skipped when ambiguous.
286
+ if (config.githubApp) {
287
+ const gitAuthLog = logger("git-auth");
288
+ try {
289
+ const soleInstallation = await getInstallationDirectory()?.soleInstallationId();
290
+ if (soleInstallation) {
291
+ await configureGitAuth({
292
+ appId: config.githubApp.appId,
293
+ privateKeyPath: config.githubApp.privateKeyPath,
294
+ installationId: soleInstallation,
295
+ botLogin: config.botLogin,
296
+ });
297
+ }
259
298
  }
260
299
  catch (err) {
261
- githubLog.warn("Installation repo discovery failed", { err });
300
+ gitAuthLog.warn("Initial token mint failed (will retry per-execution)", { err });
262
301
  }
263
302
  }
264
303
  // Late-bound: constructed after resumeOpts (below) because it closes over
@@ -895,6 +934,9 @@ async function main() {
895
934
  // and a repo that opts itself into `after-checks` under an `eager`
896
935
  // operator is covered by the 30-minute `check-prs-awaiting-review` sweep.
897
936
  reviewTrigger: () => config.review.trigger,
937
+ // The harness client memoizes an Octokit per installation; drop it when
938
+ // the App is uninstalled so a re-install can't be served by a dead one.
939
+ onInstallationRemoved: (installationId) => github?.forgetInstallation(installationId),
898
940
  });
899
941
  registry.register(githubConnector);
900
942
  }