lastlight-core 0.24.5 → 0.25.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 (46) hide show
  1. package/config/default.yaml +31 -0
  2. package/dist/admin/chat-session-reader.js +3 -0
  3. package/dist/admin/chat-session-reader.js.map +1 -1
  4. package/dist/admin/index.js +3 -1
  5. package/dist/admin/index.js.map +1 -1
  6. package/dist/admin/routes.js +86 -19
  7. package/dist/admin/routes.js.map +1 -1
  8. package/dist/admin/sessions.d.ts +23 -2
  9. package/dist/admin/sessions.js +5 -1
  10. package/dist/admin/sessions.js.map +1 -1
  11. package/dist/config/config.d.ts +38 -0
  12. package/dist/config/config.js +16 -0
  13. package/dist/config/config.js.map +1 -1
  14. package/dist/connectors/github-webhook.d.ts +34 -0
  15. package/dist/connectors/github-webhook.js +69 -0
  16. package/dist/connectors/github-webhook.js.map +1 -1
  17. package/dist/engine/dispatcher.js +18 -4
  18. package/dist/engine/dispatcher.js.map +1 -1
  19. package/dist/engine/github/github.d.ts +53 -1
  20. package/dist/engine/github/github.js +176 -2
  21. package/dist/engine/github/github.js.map +1 -1
  22. package/dist/engine/github/team-visibility.d.ts +118 -0
  23. package/dist/engine/github/team-visibility.js +298 -0
  24. package/dist/engine/github/team-visibility.js.map +1 -0
  25. package/dist/index.js +25 -6
  26. package/dist/index.js.map +1 -1
  27. package/dist/state/db.d.ts +9 -0
  28. package/dist/state/db.js +9 -0
  29. package/dist/state/db.js.map +1 -1
  30. package/dist/state/execution-store.d.ts +33 -11
  31. package/dist/state/execution-store.js +174 -77
  32. package/dist/state/execution-store.js.map +1 -1
  33. package/dist/state/migrate.js +133 -0
  34. package/dist/state/migrate.js.map +1 -1
  35. package/dist/state/repo-ref.d.ts +75 -0
  36. package/dist/state/repo-ref.js +104 -0
  37. package/dist/state/repo-ref.js.map +1 -0
  38. package/dist/state/team-store.d.ts +108 -0
  39. package/dist/state/team-store.js +178 -0
  40. package/dist/state/team-store.js.map +1 -0
  41. package/dist/state/workflow-run-store.d.ts +32 -6
  42. package/dist/state/workflow-run-store.js +70 -31
  43. package/dist/state/workflow-run-store.js.map +1 -1
  44. package/dist/workflows/resume.js +5 -2
  45. package/dist/workflows/resume.js.map +1 -1
  46. package/package.json +3 -3
@@ -18,6 +18,10 @@ export function migrate(db) {
18
18
  trigger_type TEXT NOT NULL,
19
19
  trigger_id TEXT NOT NULL,
20
20
  skill TEXT NOT NULL,
21
+ -- The target repo as (owner, BARE repo) — see state/repo-ref.ts, the one
22
+ -- place that rule is expressed. The owner column arrives by ALTER below
23
+ -- on an upgraded DB; it is here too so a fresh DB reaches the same shape.
24
+ owner TEXT,
21
25
  repo TEXT,
22
26
  issue_number INTEGER,
23
27
  started_at TEXT NOT NULL,
@@ -35,6 +39,8 @@ export function migrate(db) {
35
39
  id TEXT PRIMARY KEY,
36
40
  workflow_name TEXT NOT NULL,
37
41
  trigger_id TEXT NOT NULL,
42
+ -- Same (owner, BARE repo) pair as the executions ledger above.
43
+ owner TEXT,
38
44
  repo TEXT,
39
45
  issue_number INTEGER,
40
46
  current_phase TEXT NOT NULL,
@@ -204,6 +210,62 @@ export function migrate(db) {
204
210
  CREATE INDEX IF NOT EXISTS idx_feedback_signals_workflow
205
211
  ON feedback_signals(workflow_name, observed_at DESC);
206
212
  CREATE INDEX IF NOT EXISTS idx_feedback_signals_export ON feedback_signals(exported_at);
213
+
214
+ -- ── GitHub team-based dashboard visibility (issue #169) ────────────────
215
+ -- These four tables are a CACHE, not a mirror of the org. Nothing here is
216
+ -- enumerated up front: rows appear only for the teams a user who actually
217
+ -- logged in belongs to, resolved on demand (see engine/github/team-visibility.ts).
218
+ -- That is the whole scaling story — an org with thousands of repos and
219
+ -- hundreds of teams costs a handful of requests per logged-in person
220
+ -- instead of a full-org crawl. Safe to delete wholesale; it refills.
221
+
222
+ -- One row per team we have ever resolved repos for.
223
+ CREATE TABLE IF NOT EXISTS github_teams (
224
+ org TEXT NOT NULL,
225
+ slug TEXT NOT NULL,
226
+ name TEXT,
227
+ -- When this team's repo grant was last enumerated.
228
+ repos_synced_at TEXT NOT NULL,
229
+ -- 1 when the enumeration hit the per-team page budget and stopped early,
230
+ -- so github_team_repos is a PREFIX of the real grant. A truncated team
231
+ -- forces its members to fail open — a partial list would hide repos the
232
+ -- person really can see, which is worse than not filtering at all.
233
+ truncated INTEGER NOT NULL DEFAULT 0,
234
+ PRIMARY KEY (org, slug)
235
+ );
236
+
237
+ -- A team's grant, already intersected with the managed-repo set. The repo
238
+ -- column holds the owner/repo full name.
239
+ CREATE TABLE IF NOT EXISTS github_team_repos (
240
+ org TEXT NOT NULL,
241
+ team_slug TEXT NOT NULL,
242
+ repo TEXT NOT NULL,
243
+ PRIMARY KEY (org, team_slug, repo)
244
+ );
245
+
246
+ -- Membership we have LEARNED, not enumerated: one row per (team, login)
247
+ -- discovered while resolving that login. Absence means "unknown", never
248
+ -- "not a member" — which is why every read path fails open.
249
+ CREATE TABLE IF NOT EXISTS github_team_members (
250
+ org TEXT NOT NULL,
251
+ team_slug TEXT NOT NULL,
252
+ login TEXT NOT NULL,
253
+ PRIMARY KEY (org, team_slug, login)
254
+ );
255
+ -- reposForLogin joins membership → team_repos on this column.
256
+ CREATE INDEX IF NOT EXISTS idx_github_team_members_login
257
+ ON github_team_members(login);
258
+
259
+ -- Per-login freshness + outcome, so a resolution that failed or blew its
260
+ -- request budget is remembered for the TTL rather than retried on every
261
+ -- dashboard poll. status is one of: ok | empty | truncated | error | disabled.
262
+ CREATE TABLE IF NOT EXISTS github_visibility_sync (
263
+ login TEXT PRIMARY KEY,
264
+ synced_at TEXT NOT NULL,
265
+ status TEXT NOT NULL,
266
+ -- Free-text detail for the error/truncated cases (admin surface only).
267
+ detail TEXT
268
+ );
207
269
  `);
208
270
  // Actor logging (issue #205): who triggered a run and how. Additive on both
209
271
  // the append-only `executions` ledger and the `workflow_runs` aggregate. The
@@ -259,6 +321,77 @@ export function migrate(db) {
259
321
  catch {
260
322
  // Column already exists — ignore
261
323
  }
324
+ // ── One repo-identifier rule: (owner, BARE repo) — issue #279 ──────────────
325
+ //
326
+ // The column above fixed the SHAPE for new rows but left two populations
327
+ // behind, so the same column meant two things depending on who wrote it:
328
+ // rows predating it hold the qualified `owner/repo` in `repo` itself, and
329
+ // `executions` never got an `owner` column at all — the dispatcher wrote the
330
+ // qualified string there while the phase executor wrote the bare name, which
331
+ // is every workflow phase row.
332
+ //
333
+ // Six read sites each re-derived "may be bare or qualified" and disagreed
334
+ // about which source wins; #278 shipped a filter built on one reading, and a
335
+ // non-null non-match HIDES rows rather than showing them. So converge the
336
+ // data instead of teaching the seventh consumer the rule.
337
+ //
338
+ // Ordering matters: `workflow_runs` first, because the `executions` owner
339
+ // backfill reads `workflow_runs.owner` back out. Every statement is a no-op
340
+ // on a second run — after it, `instr(repo, '/') = 0` — so this is safe to
341
+ // re-run, which it is, on every boot.
342
+ try {
343
+ db.exec(`UPDATE workflow_runs
344
+ SET owner = CASE WHEN owner IS NULL OR owner = ''
345
+ THEN substr(repo, 1, instr(repo, '/') - 1)
346
+ ELSE owner END,
347
+ repo = substr(repo, instr(repo, '/') + 1)
348
+ WHERE repo IS NOT NULL AND instr(repo, '/') > 0`);
349
+ // A row from before the owner column whose `context.owner` was absent has
350
+ // one more witness: `trigger_id`, which is built as `owner/repo#N` (or
351
+ // `owner/repo::workflow`) from the same pair at dispatch. `resume.ts` and
352
+ // the approval-resume path already PREFER it over the columns, so reading
353
+ // it here is the existing precedence, not a new guess. Slack-originated
354
+ // ids (`slack:…`) carry no repo and are excluded.
355
+ db.exec(`UPDATE workflow_runs
356
+ SET owner = substr(trigger_id, 1, instr(trigger_id, '/') - 1)
357
+ WHERE (owner IS NULL OR owner = '')
358
+ AND repo IS NOT NULL
359
+ AND trigger_id NOT LIKE 'slack:%'
360
+ AND instr(trigger_id, '/') > 0`);
361
+ }
362
+ catch {
363
+ // Best-effort: a run row that won't split is better left alone than
364
+ // failing boot. The read path still tolerates both shapes.
365
+ }
366
+ try {
367
+ db.exec(`ALTER TABLE executions ADD COLUMN owner TEXT`);
368
+ }
369
+ catch {
370
+ // Column already exists — ignore
371
+ }
372
+ try {
373
+ // 1. The account is already in the row, on the dispatcher-written rows that
374
+ // stored the qualified string.
375
+ db.exec(`UPDATE executions
376
+ SET owner = substr(repo, 1, instr(repo, '/') - 1)
377
+ WHERE (owner IS NULL OR owner = '')
378
+ AND repo IS NOT NULL AND instr(repo, '/') > 0`);
379
+ // 2. Otherwise it comes from the run that owns the execution. This is the
380
+ // bulk: every phase row, written bare from `GitSandboxAccess`.
381
+ // `build-cycle` rows are covered by (1) and chat rows carry no repo at
382
+ // all, so there is nothing left needing a `trigger_id` parse.
383
+ db.exec(`UPDATE executions
384
+ SET owner = (SELECT r.owner FROM workflow_runs r WHERE r.id = executions.workflow_run_id)
385
+ WHERE (owner IS NULL OR owner = '') AND workflow_run_id IS NOT NULL`);
386
+ // 3. Now de-qualify, once the account has been rescued off it.
387
+ db.exec(`UPDATE executions
388
+ SET repo = substr(repo, instr(repo, '/') + 1)
389
+ WHERE repo IS NOT NULL AND instr(repo, '/') > 0`);
390
+ }
391
+ catch {
392
+ // Same best-effort rule as above — the ledger is append-only history, and
393
+ // an un-normalized row degrades a dashboard filter, never a run.
394
+ }
262
395
  // `feedback_anchors.channel` moved from nullable to a '' sentinel (issue
263
396
  // #255) so its UNIQUE actually binds for GitHub — see the CREATE TABLE above.
264
397
  // `CREATE TABLE IF NOT EXISTS` can't restate a column, so backfill any rows
@@ -1 +1 @@
1
- {"version":3,"file":"migrate.js","sourceRoot":"","sources":["../../src/state/migrate.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,OAAO,CAAC,EAAqB;IAC3C,EAAE,CAAC,IAAI,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAC,MAAM,CAAC;QACP,iCAAiC;IACnC,CAAC;IAED,4EAA4E;IAC5E,0EAA0E;IAC1E,gFAAgF;IAChF,IAAI,CAAC;QACH,EAAE,CAAC,IAAI,CAAC,yDAAyD,CAAC,CAAC;IACrE,CAAC;IAAC,MAAM,CAAC;QACP,iCAAiC;IACnC,CAAC;IAED,qEAAqE;IACrE,yEAAyE;IACzE,IAAI,CAAC;QACH,EAAE,CAAC,IAAI,CAAC,mDAAmD,CAAC,CAAC;IAC/D,CAAC;IAAC,MAAM,CAAC;QACP,iCAAiC;IACnC,CAAC;IAED,kEAAkE;IAClE,sEAAsE;IACtE,yEAAyE;IACzE,KAAK,MAAM,GAAG,IAAI;QAChB,eAAe;QACf,sBAAsB;QACtB,qCAAqC;QACrC,iCAAiC;QACjC,uBAAuB;QACvB,yBAAyB;QACzB,kBAAkB;QAClB,gEAAgE;QAChE,kEAAkE;QAClE,gEAAgE;QAChE,oDAAoD;QACpD,sBAAsB;QACtB,iEAAiE;QACjE,+DAA+D;QAC/D,gEAAgE;QAChE,8DAA8D;QAC9D,2DAA2D;QAC3D,kBAAkB;QAClB,8DAA8D;QAC9D,kEAAkE;QAClE,uEAAuE;QACvE,uBAAuB;QACvB,sEAAsE;QACtE,sEAAsE;QACtE,uEAAuE;QACvE,oBAAoB;KACrB,EAAE,CAAC;QACF,IAAI,CAAC;YACH,EAAE,CAAC,IAAI,CAAC,qCAAqC,GAAG,EAAE,CAAC,CAAC;QACtD,CAAC;QAAC,MAAM,CAAC;YACP,iCAAiC;QACnC,CAAC;IACH,CAAC;IACD,IAAI,CAAC;QACH,EAAE,CAAC,IAAI,CACL,8FAA8F,CAC/F,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,gCAAgC;IAClC,CAAC;AACH,CAAC"}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The ONE rule for how a repository is identified in the database (issue #279).
3
+ *
4
+ * **Storage is `owner` + a BARE `repo`.** Every repo-bearing table follows it —
5
+ * `workflow_runs`, `executions`, `feedback_anchors`, `feedback_signals` — and so
6
+ * does `GitSandboxAccess`, so a row read back is directly usable as Octokit's
7
+ * `(owner, repo)` pair with no splitting anywhere. `repo` stays a single
8
+ * path-safe segment because `workflowScopedTaskId` and `prNotesRepoDir` derive
9
+ * filesystem paths from it.
10
+ *
11
+ * Everything a *user* sees speaks the qualified `owner/repo` instead —
12
+ * `getManagedRepos()`, `EventEnvelope.repo`, `PrState.repo`, the artifact-store
13
+ * slugs, `/me/repos`, the dashboard. That join is the only place the two
14
+ * vocabularies meet, and this module is the only place it is expressed.
15
+ *
16
+ * It used to be expressed in six places that disagreed about which source wins
17
+ * (`distinctRepos`, `repoMatchClause`, `QUALIFIED_REPO_SQL`, two helpers in
18
+ * `admin/routes.ts`, and the dashboard's `runRepoPath`). #278 shipped a filter
19
+ * built on one reading and it compared `lastlight` against `{nearform/lastlight}`
20
+ * — a non-null non-match, which **hides** rows rather than showing them.
21
+ *
22
+ * Pure, dependency-free, and deliberately in `state/` beside the stores that
23
+ * enforce it.
24
+ */
25
+ /**
26
+ * Split a possibly-qualified repo into the stored shape.
27
+ *
28
+ * The de-qualifier, applied at the write choke points (`createRun`,
29
+ * `recordStart`) and again on read-back, so a caller that hands us
30
+ * `"nearform/lastlight"` — a test fixture, an eval harness, a row written by an
31
+ * older process before the backfill ran — cannot reintroduce the drift this
32
+ * module exists to end.
33
+ *
34
+ * An explicit `owner` wins over the one embedded in `repo`: the column was
35
+ * populated from `context.owner` by the authoritative dispatch-time split,
36
+ * while a qualified `repo` is the legacy shape. Empty strings normalize to
37
+ * `undefined` so callers can use a plain truthiness check.
38
+ */
39
+ export declare function normalizeRepoRef(owner: string | null | undefined, repo: string | null | undefined): {
40
+ owner?: string;
41
+ repo?: string;
42
+ };
43
+ /**
44
+ * Compose the qualified `owner/repo` a user-facing surface speaks.
45
+ *
46
+ * The inverse of {@link normalizeRepoRef}, and the only recomposition in the
47
+ * codebase. Two degenerate cases, both deliberate:
48
+ *
49
+ * - An already-qualified `repo` (a row predating the backfill) is returned
50
+ * as-is rather than double-qualified — `dispatcher.ts` used to join
51
+ * unconditionally and produced `acme/acme/widgets`, which the dispatch split
52
+ * then read as the repo `acme`, a different real repository.
53
+ * - No owner returns the BARE name. Ambiguous, but it is a name somebody can
54
+ * read; for a SQL *filter*, where a bare name would match nothing in a
55
+ * qualified allow-list and therefore hide the row, use
56
+ * {@link qualifiedRepoSql} with `"null"` instead.
57
+ */
58
+ export declare function qualifyRepo(owner: string | null | undefined, repo: string | null | undefined): string | undefined;
59
+ /**
60
+ * {@link qualifyRepo} as a SQL expression, so the two cannot drift.
61
+ *
62
+ * `unqualifiable` is what to answer for a row with a repo but no owner — the
63
+ * only rows the backfill cannot fix, because nothing on them records the
64
+ * account. **The caller must choose, because the two answers are opposites:**
65
+ *
66
+ * - `"bare"` — the repo name alone. For grouping and display (`distinctRepos`),
67
+ * where showing an under-specified name beats dropping the row.
68
+ * - `"null"` — SQL NULL. For anything a consumer treats as "no repo, always
69
+ * visible" (the per-repo visibility scope, issue #169). A bare name there
70
+ * matches nothing in a qualified allow-list and so silently HIDES the row,
71
+ * which is exactly the #278 bug.
72
+ *
73
+ * Column names are interpolated, so pass literals — never user input.
74
+ */
75
+ export declare function qualifiedRepoSql(ownerCol: string, repoCol: string, unqualifiable: "bare" | "null"): string;
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The ONE rule for how a repository is identified in the database (issue #279).
3
+ *
4
+ * **Storage is `owner` + a BARE `repo`.** Every repo-bearing table follows it —
5
+ * `workflow_runs`, `executions`, `feedback_anchors`, `feedback_signals` — and so
6
+ * does `GitSandboxAccess`, so a row read back is directly usable as Octokit's
7
+ * `(owner, repo)` pair with no splitting anywhere. `repo` stays a single
8
+ * path-safe segment because `workflowScopedTaskId` and `prNotesRepoDir` derive
9
+ * filesystem paths from it.
10
+ *
11
+ * Everything a *user* sees speaks the qualified `owner/repo` instead —
12
+ * `getManagedRepos()`, `EventEnvelope.repo`, `PrState.repo`, the artifact-store
13
+ * slugs, `/me/repos`, the dashboard. That join is the only place the two
14
+ * vocabularies meet, and this module is the only place it is expressed.
15
+ *
16
+ * It used to be expressed in six places that disagreed about which source wins
17
+ * (`distinctRepos`, `repoMatchClause`, `QUALIFIED_REPO_SQL`, two helpers in
18
+ * `admin/routes.ts`, and the dashboard's `runRepoPath`). #278 shipped a filter
19
+ * built on one reading and it compared `lastlight` against `{nearform/lastlight}`
20
+ * — a non-null non-match, which **hides** rows rather than showing them.
21
+ *
22
+ * Pure, dependency-free, and deliberately in `state/` beside the stores that
23
+ * enforce it.
24
+ */
25
+ /**
26
+ * Split a possibly-qualified repo into the stored shape.
27
+ *
28
+ * The de-qualifier, applied at the write choke points (`createRun`,
29
+ * `recordStart`) and again on read-back, so a caller that hands us
30
+ * `"nearform/lastlight"` — a test fixture, an eval harness, a row written by an
31
+ * older process before the backfill ran — cannot reintroduce the drift this
32
+ * module exists to end.
33
+ *
34
+ * An explicit `owner` wins over the one embedded in `repo`: the column was
35
+ * populated from `context.owner` by the authoritative dispatch-time split,
36
+ * while a qualified `repo` is the legacy shape. Empty strings normalize to
37
+ * `undefined` so callers can use a plain truthiness check.
38
+ */
39
+ export function normalizeRepoRef(owner, repo) {
40
+ const rawRepo = repo?.trim() || undefined;
41
+ const rawOwner = owner?.trim() || undefined;
42
+ if (!rawRepo)
43
+ return { owner: rawOwner, repo: undefined };
44
+ // First slash, matching the SQL backfill's `instr(repo, '/')`. A GitHub repo
45
+ // name cannot contain a slash, so anything past the first one is malformed
46
+ // input rather than a shape we need to support.
47
+ const slash = rawRepo.indexOf("/");
48
+ if (slash <= 0)
49
+ return { owner: rawOwner, repo: rawRepo };
50
+ return {
51
+ owner: rawOwner ?? (rawRepo.slice(0, slash) || undefined),
52
+ repo: rawRepo.slice(slash + 1) || undefined,
53
+ };
54
+ }
55
+ /**
56
+ * Compose the qualified `owner/repo` a user-facing surface speaks.
57
+ *
58
+ * The inverse of {@link normalizeRepoRef}, and the only recomposition in the
59
+ * codebase. Two degenerate cases, both deliberate:
60
+ *
61
+ * - An already-qualified `repo` (a row predating the backfill) is returned
62
+ * as-is rather than double-qualified — `dispatcher.ts` used to join
63
+ * unconditionally and produced `acme/acme/widgets`, which the dispatch split
64
+ * then read as the repo `acme`, a different real repository.
65
+ * - No owner returns the BARE name. Ambiguous, but it is a name somebody can
66
+ * read; for a SQL *filter*, where a bare name would match nothing in a
67
+ * qualified allow-list and therefore hide the row, use
68
+ * {@link qualifiedRepoSql} with `"null"` instead.
69
+ */
70
+ export function qualifyRepo(owner, repo) {
71
+ const rawRepo = repo?.trim() || undefined;
72
+ if (!rawRepo)
73
+ return undefined;
74
+ if (rawRepo.includes("/"))
75
+ return rawRepo;
76
+ const rawOwner = owner?.trim() || undefined;
77
+ return rawOwner ? `${rawOwner}/${rawRepo}` : rawRepo;
78
+ }
79
+ /**
80
+ * {@link qualifyRepo} as a SQL expression, so the two cannot drift.
81
+ *
82
+ * `unqualifiable` is what to answer for a row with a repo but no owner — the
83
+ * only rows the backfill cannot fix, because nothing on them records the
84
+ * account. **The caller must choose, because the two answers are opposites:**
85
+ *
86
+ * - `"bare"` — the repo name alone. For grouping and display (`distinctRepos`),
87
+ * where showing an under-specified name beats dropping the row.
88
+ * - `"null"` — SQL NULL. For anything a consumer treats as "no repo, always
89
+ * visible" (the per-repo visibility scope, issue #169). A bare name there
90
+ * matches nothing in a qualified allow-list and so silently HIDES the row,
91
+ * which is exactly the #278 bug.
92
+ *
93
+ * Column names are interpolated, so pass literals — never user input.
94
+ */
95
+ export function qualifiedRepoSql(ownerCol, repoCol, unqualifiable) {
96
+ const fallback = unqualifiable === "bare" ? repoCol : "NULL";
97
+ return `CASE
98
+ WHEN ${repoCol} IS NULL OR ${repoCol} = '' THEN NULL
99
+ WHEN instr(${repoCol}, '/') > 0 THEN ${repoCol}
100
+ WHEN ${ownerCol} IS NOT NULL AND ${ownerCol} <> '' THEN ${ownerCol} || '/' || ${repoCol}
101
+ ELSE ${fallback}
102
+ END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,EAAE,IAAI,SAAS,CAAC;IAC5C,OAAO,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,IAAI,OAAO,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,gBAAgB,CAC9B,QAAgB,EAChB,OAAe,EACf,aAA8B;IAE9B,MAAM,QAAQ,GAAG,aAAa,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;IAC7D,OAAO;WACE,OAAO,eAAe,OAAO;iBACvB,OAAO,mBAAmB,OAAO;WACvC,QAAQ,oBAAoB,QAAQ,eAAe,QAAQ,cAAc,OAAO;WAChF,QAAQ;MACb,CAAC;AACP,CAAC"}
@@ -0,0 +1,108 @@
1
+ import type Database from "better-sqlite3";
2
+ /**
3
+ * Outcome of the last visibility resolution for one login.
4
+ *
5
+ * - `ok` — the login belongs to at least one team with a managed-repo grant.
6
+ * - `empty` — resolved cleanly, but no team grants access to a managed repo.
7
+ * - `truncated` — a team's grant was too large to enumerate inside the budget.
8
+ * - `error` — GitHub said no (permission, rate limit, network).
9
+ * - `disabled` — the feature is off, or there is no App client to ask.
10
+ *
11
+ * Only `ok` produces a filter. Every other status fails OPEN (see the module
12
+ * header of `engine/github/team-visibility.ts`), but they are distinguished
13
+ * because they are remembered for the TTL and shown on the admin surface.
14
+ */
15
+ export type VisibilitySyncStatus = "ok" | "empty" | "truncated" | "error" | "disabled";
16
+ export interface VisibilitySync {
17
+ login: string;
18
+ syncedAt: string;
19
+ status: VisibilitySyncStatus;
20
+ detail?: string;
21
+ }
22
+ /** One team's resolved grant — already intersected with the managed-repo set. */
23
+ export interface ResolvedTeam {
24
+ org: string;
25
+ slug: string;
26
+ name?: string | null;
27
+ /** Managed repos the team can reach. May be a PREFIX when `truncated`. */
28
+ repos: string[];
29
+ /** True when enumeration stopped at the page budget, so `repos` is partial. */
30
+ truncated: boolean;
31
+ }
32
+ /** What the cache can say about a login right now. */
33
+ export interface CachedVisibility {
34
+ repos: string[];
35
+ /** Any of the login's teams was truncated ⇒ the caller must fail open. */
36
+ truncated: boolean;
37
+ /** Teams the login is known to belong to, for the admin/debug surface. */
38
+ teams: Array<{
39
+ org: string;
40
+ slug: string;
41
+ }>;
42
+ }
43
+ /**
44
+ * Owns the four `github_team*` / `github_visibility_sync` tables — the cache
45
+ * behind per-repo dashboard visibility (issue #169).
46
+ *
47
+ * **This is a cache, not a mirror.** Rows exist only for teams a user who
48
+ * actually logged in belongs to, written by the on-demand resolver. That is
49
+ * deliberate: an org with thousands of repos and hundreds of teams would make a
50
+ * full crawl cost thousands of API requests, and almost all of it would describe
51
+ * teams nobody using the dashboard is in. The consequence every read path must
52
+ * respect is that **absence means "unknown", never "no access"** — so a miss
53
+ * fails open rather than hiding repos.
54
+ *
55
+ * Mirrors the other per-table stores ({@link ExecutionStore} /
56
+ * {@link UserStore}): constructed from the single shared `Database`, every
57
+ * multi-row write wrapped in one transaction.
58
+ */
59
+ export declare class TeamStore {
60
+ private db;
61
+ constructor(db: Database.Database);
62
+ /**
63
+ * Replace everything known about ONE login in a single transaction: the teams
64
+ * it belongs to, each of those teams' managed-repo grant, and the freshness
65
+ * row. Atomic because a half-applied membership set would silently narrow
66
+ * what somebody can see.
67
+ *
68
+ * Only touches membership rows for `login` — other logins' rows in the same
69
+ * teams are left alone, since this pass learned nothing about them.
70
+ */
71
+ recordResolution(input: {
72
+ login: string;
73
+ teams: ResolvedTeam[];
74
+ status: VisibilitySyncStatus;
75
+ detail?: string;
76
+ at?: string;
77
+ }): void;
78
+ /** The freshness/outcome row for a login, or null if never resolved. */
79
+ getSync(login: string): VisibilitySync | null;
80
+ /**
81
+ * Whether a login's cached answer is still inside `ttlMs`. A missing row is
82
+ * never fresh; a `synced_at` we can't parse is treated as stale rather than
83
+ * trusted forever.
84
+ */
85
+ isFresh(login: string, ttlMs: number, now?: number): boolean;
86
+ /**
87
+ * Everything the cache knows about a login, joined membership → team_repos.
88
+ * The caller intersects with the live managed-repo list; this returns what was
89
+ * stored, which was already intersected at write time (a repo unmanaged since
90
+ * then must not reappear just because a team still grants it).
91
+ */
92
+ reposForLogin(login: string): CachedVisibility;
93
+ /** Forget one login's answer — it will be re-resolved on the next request. */
94
+ invalidateLogin(login: string): void;
95
+ /**
96
+ * Forget one team — its grant AND every member's cached answer, because their
97
+ * visible-repo set was derived from it. Called from the `team` webhook, where
98
+ * the payload names the team but not who is affected.
99
+ *
100
+ * Returns the logins whose answers were dropped, so the caller can log the
101
+ * blast radius of an org-side change.
102
+ */
103
+ invalidateTeam(org: string, slug: string): string[];
104
+ /** Drop the whole cache (admin re-sync, or an `organization` event we can't scope). */
105
+ invalidateAll(): void;
106
+ /** Most recent successful resolution across all logins — powers the coarse `synced` flag. */
107
+ lastSyncedAt(): string | null;
108
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Owns the four `github_team*` / `github_visibility_sync` tables — the cache
3
+ * behind per-repo dashboard visibility (issue #169).
4
+ *
5
+ * **This is a cache, not a mirror.** Rows exist only for teams a user who
6
+ * actually logged in belongs to, written by the on-demand resolver. That is
7
+ * deliberate: an org with thousands of repos and hundreds of teams would make a
8
+ * full crawl cost thousands of API requests, and almost all of it would describe
9
+ * teams nobody using the dashboard is in. The consequence every read path must
10
+ * respect is that **absence means "unknown", never "no access"** — so a miss
11
+ * fails open rather than hiding repos.
12
+ *
13
+ * Mirrors the other per-table stores ({@link ExecutionStore} /
14
+ * {@link UserStore}): constructed from the single shared `Database`, every
15
+ * multi-row write wrapped in one transaction.
16
+ */
17
+ export class TeamStore {
18
+ db;
19
+ constructor(db) {
20
+ this.db = db;
21
+ }
22
+ /**
23
+ * Replace everything known about ONE login in a single transaction: the teams
24
+ * it belongs to, each of those teams' managed-repo grant, and the freshness
25
+ * row. Atomic because a half-applied membership set would silently narrow
26
+ * what somebody can see.
27
+ *
28
+ * Only touches membership rows for `login` — other logins' rows in the same
29
+ * teams are left alone, since this pass learned nothing about them.
30
+ */
31
+ recordResolution(input) {
32
+ const now = input.at ?? new Date().toISOString();
33
+ const apply = this.db.transaction(() => {
34
+ this.db.prepare(`DELETE FROM github_team_members WHERE login = ?`).run(input.login);
35
+ for (const team of input.teams) {
36
+ this.db
37
+ .prepare(`INSERT INTO github_teams (org, slug, name, repos_synced_at, truncated)
38
+ VALUES (?, ?, ?, ?, ?)
39
+ ON CONFLICT(org, slug) DO UPDATE SET
40
+ name = excluded.name,
41
+ repos_synced_at = excluded.repos_synced_at,
42
+ truncated = excluded.truncated`)
43
+ .run(team.org, team.slug, team.name ?? null, now, team.truncated ? 1 : 0);
44
+ this.db
45
+ .prepare(`DELETE FROM github_team_repos WHERE org = ? AND team_slug = ?`)
46
+ .run(team.org, team.slug);
47
+ const insertRepo = this.db.prepare(`INSERT OR IGNORE INTO github_team_repos (org, team_slug, repo) VALUES (?, ?, ?)`);
48
+ for (const repo of team.repos)
49
+ insertRepo.run(team.org, team.slug, repo);
50
+ this.db
51
+ .prepare(`INSERT OR IGNORE INTO github_team_members (org, team_slug, login) VALUES (?, ?, ?)`)
52
+ .run(team.org, team.slug, input.login);
53
+ }
54
+ this.db
55
+ .prepare(`INSERT INTO github_visibility_sync (login, synced_at, status, detail)
56
+ VALUES (?, ?, ?, ?)
57
+ ON CONFLICT(login) DO UPDATE SET
58
+ synced_at = excluded.synced_at,
59
+ status = excluded.status,
60
+ detail = excluded.detail`)
61
+ .run(input.login, now, input.status, input.detail ?? null);
62
+ });
63
+ apply();
64
+ }
65
+ /** The freshness/outcome row for a login, or null if never resolved. */
66
+ getSync(login) {
67
+ const row = this.db
68
+ .prepare(`SELECT login, synced_at, status, detail FROM github_visibility_sync WHERE login = ?`)
69
+ .get(login);
70
+ if (!row)
71
+ return null;
72
+ return {
73
+ login: row.login,
74
+ syncedAt: row.synced_at,
75
+ status: row.status,
76
+ detail: row.detail ?? undefined,
77
+ };
78
+ }
79
+ /**
80
+ * Whether a login's cached answer is still inside `ttlMs`. A missing row is
81
+ * never fresh; a `synced_at` we can't parse is treated as stale rather than
82
+ * trusted forever.
83
+ */
84
+ isFresh(login, ttlMs, now = Date.now()) {
85
+ const sync = this.getSync(login);
86
+ if (!sync)
87
+ return false;
88
+ const at = Date.parse(sync.syncedAt);
89
+ if (Number.isNaN(at))
90
+ return false;
91
+ return now - at < ttlMs;
92
+ }
93
+ /**
94
+ * Everything the cache knows about a login, joined membership → team_repos.
95
+ * The caller intersects with the live managed-repo list; this returns what was
96
+ * stored, which was already intersected at write time (a repo unmanaged since
97
+ * then must not reappear just because a team still grants it).
98
+ */
99
+ reposForLogin(login) {
100
+ const rows = this.db
101
+ .prepare(`SELECT DISTINCT tr.repo AS repo
102
+ FROM github_team_members m
103
+ JOIN github_team_repos tr
104
+ ON tr.org = m.org AND tr.team_slug = m.team_slug
105
+ WHERE m.login = ?
106
+ ORDER BY tr.repo`)
107
+ .all(login);
108
+ const teams = this.db
109
+ .prepare(`SELECT m.org AS org, m.team_slug AS slug, COALESCE(t.truncated, 0) AS truncated
110
+ FROM github_team_members m
111
+ LEFT JOIN github_teams t ON t.org = m.org AND t.slug = m.team_slug
112
+ WHERE m.login = ?
113
+ ORDER BY m.org, m.team_slug`)
114
+ .all(login);
115
+ return {
116
+ repos: rows.map((r) => r.repo),
117
+ truncated: teams.some((t) => t.truncated === 1),
118
+ teams: teams.map((t) => ({ org: t.org, slug: t.slug })),
119
+ };
120
+ }
121
+ /** Forget one login's answer — it will be re-resolved on the next request. */
122
+ invalidateLogin(login) {
123
+ const apply = this.db.transaction(() => {
124
+ this.db.prepare(`DELETE FROM github_team_members WHERE login = ?`).run(login);
125
+ this.db.prepare(`DELETE FROM github_visibility_sync WHERE login = ?`).run(login);
126
+ });
127
+ apply();
128
+ }
129
+ /**
130
+ * Forget one team — its grant AND every member's cached answer, because their
131
+ * visible-repo set was derived from it. Called from the `team` webhook, where
132
+ * the payload names the team but not who is affected.
133
+ *
134
+ * Returns the logins whose answers were dropped, so the caller can log the
135
+ * blast radius of an org-side change.
136
+ */
137
+ invalidateTeam(org, slug) {
138
+ const members = this.db
139
+ .prepare(`SELECT login FROM github_team_members WHERE org = ? AND team_slug = ?`)
140
+ .all(org, slug);
141
+ const logins = members.map((m) => m.login);
142
+ const apply = this.db.transaction(() => {
143
+ this.db.prepare(`DELETE FROM github_team_repos WHERE org = ? AND team_slug = ?`).run(org, slug);
144
+ this.db.prepare(`DELETE FROM github_teams WHERE org = ? AND slug = ?`).run(org, slug);
145
+ // Drop each affected member ENTIRELY, not just their row in this team.
146
+ // Leaving their other memberships behind would keep a partial repo set in
147
+ // the cache — and a partial set is the one answer this feature must never
148
+ // produce. They re-resolve on their next request regardless, since their
149
+ // freshness row goes with them, so this costs nothing extra.
150
+ const forgetMembership = this.db.prepare(`DELETE FROM github_team_members WHERE login = ?`);
151
+ const forgetSync = this.db.prepare(`DELETE FROM github_visibility_sync WHERE login = ?`);
152
+ for (const login of logins) {
153
+ forgetMembership.run(login);
154
+ forgetSync.run(login);
155
+ }
156
+ });
157
+ apply();
158
+ return logins;
159
+ }
160
+ /** Drop the whole cache (admin re-sync, or an `organization` event we can't scope). */
161
+ invalidateAll() {
162
+ const apply = this.db.transaction(() => {
163
+ this.db.exec(`DELETE FROM github_team_repos`);
164
+ this.db.exec(`DELETE FROM github_team_members`);
165
+ this.db.exec(`DELETE FROM github_teams`);
166
+ this.db.exec(`DELETE FROM github_visibility_sync`);
167
+ });
168
+ apply();
169
+ }
170
+ /** Most recent successful resolution across all logins — powers the coarse `synced` flag. */
171
+ lastSyncedAt() {
172
+ const row = this.db
173
+ .prepare(`SELECT MAX(synced_at) AS at FROM github_visibility_sync`)
174
+ .get();
175
+ return row?.at ?? null;
176
+ }
177
+ }
178
+ //# sourceMappingURL=team-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"team-store.js","sourceRoot":"","sources":["../../src/state/team-store.ts"],"names":[],"mappings":"AA4CA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,OAAO,SAAS;I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