lastlight-core 0.24.4 → 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 +64 -0
  15. package/dist/connectors/github-webhook.js +233 -131
  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 +88 -1
  20. package/dist/engine/github/github.js +292 -5
  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 +35 -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 +4 -4
@@ -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`;
103
+ }
104
+ //# sourceMappingURL=repo-ref.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"repo-ref.js","sourceRoot":"","sources":["../../src/state/repo-ref.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AAEH;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,gBAAgB,CAC9B,KAAgC,EAChC,IAA+B;IAE/B,MAAM,OAAO,GAAG,IAAI,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IAC1C,MAAM,QAAQ,GAAG,KAAK,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IAC5C,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;IAE1D,6EAA6E;IAC7E,2EAA2E;IAC3E,gDAAgD;IAChD,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACnC,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC1D,OAAO;QACL,KAAK,EAAE,QAAQ,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,CAAC,IAAI,SAAS,CAAC;QACzD,IAAI,EAAE,OAAO,CAAC,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,IAAI,SAAS;KAC5C,CAAC;AACJ,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,WAAW,CACzB,KAAgC,EAChC,IAA+B;IAE/B,MAAM,OAAO,GAAG,IAAI,EAAE,IAAI,EAAE,IAAI,SAAS,CAAC;IAC1C,IAAI,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IAC/B,IAAI,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC;QAAE,OAAO,OAAO,CAAC;IAC1C,MAAM,QAAQ,GAAG,KAAK,EAAE,IAAI,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;IACA;IAApB,YAAoB,EAAqB;QAArB,OAAE,GAAF,EAAE,CAAmB;IAAG,CAAC;IAE7C;;;;;;;;OAQG;IACH,gBAAgB,CAAC,KAMhB;QACC,MAAM,GAAG,GAAG,KAAK,CAAC,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;QACjD,MAAM,KAAK,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE;YACrC,IAAI,CAAC,EAAE,CAAC,OAAO,CAAC,iDAAiD,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;YACpF,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;gBAC/B,IAAI,CAAC,EAAE;qBACJ,OAAO,CACN;;;;;8CAKkC,CACnC;qBACA,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,IAAI,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,SAAS,CAAC,CAA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AO,MAAM,CAAC;IAChB,CAAC;IAED,uFAAuF;IACvF,aAAa;QACX,MAAM,KAAK,GAAG,IAAI,CAAC,EAAE,CAAC,WAAW,CAAC,GAAG,EAAE;YACrC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,+BAA+B,CAAC,CAAC;YAC9C,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,iCAAiC,CAAC,CAAC;YAChD,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;YACzC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,oCAAoC,CAAC,CAAC;QACrD,CAAC,CAAC,CAAC;QACH,KAAK,EAAE,CAAC;IACV,CAAC;IAED,6FAA6F;IAC7F,YAAY;QACV,MAAM,GAAG,GAAG,IAAI,CAAC,EAAE;aAChB,OAAO,CAAC,yDAAyD,CAAC;aAClE,GAAG,EAAuC,CAAC;QAC9C,OAAO,GAAG,EAAE,EAAE,IAAI,IAAI,CAAC;IACzB,CAAC;CACF"}
@@ -14,7 +14,13 @@ export interface WorkflowRun {
14
14
  /** GitHub org/user that owns {@link repo}. Stored as its own column so the
15
15
  * runs list (which omits `context`) can compose the qualified `owner/repo`. */
16
16
  owner?: string;
17
- /** BARE repo name (no owner) — kept path-safe for taskIds / workspace dirs. */
17
+ /**
18
+ * BARE repo name (no owner) — kept path-safe for taskIds / workspace dirs.
19
+ *
20
+ * Normalized on the way in AND on the way back out (`state/repo-ref.ts`), so
21
+ * a consumer can hand `(run.owner, run.repo)` to Octokit unsplit. Reach for
22
+ * `qualifyRepo` when you need the user-facing `owner/repo`.
23
+ */
18
24
  repo?: string;
19
25
  issueNumber?: number;
20
26
  /**
@@ -136,7 +142,14 @@ export declare class WorkflowRunStore {
136
142
  * failing must not cost the others their notification.
137
143
  */
138
144
  private notifyTerminal;
139
- /** Create a new workflow run record */
145
+ /**
146
+ * Create a new workflow run record.
147
+ *
148
+ * The (owner, BARE repo) invariant is enforced HERE rather than asked of
149
+ * callers (issue #279) — a fixture, an eval harness or a future caller
150
+ * passing `"owner/repo"` is split rather than stored as a third shape. See
151
+ * `state/repo-ref.ts`.
152
+ */
140
153
  createRun(run: Omit<WorkflowRun, "phaseHistory" | "updatedAt">): void;
141
154
  /**
142
155
  * Top-level merge of `patch` into the workflow run's scratch state.
@@ -250,6 +263,15 @@ export declare class WorkflowRunStore {
250
263
  sinceIso?: string;
251
264
  workflowName?: string;
252
265
  repo?: string;
266
+ /**
267
+ * Restrict to a SET of repos — the dashboard's per-repo visibility scope
268
+ * (issue #169), where a user's GitHub teams resolve to several repos at
269
+ * once. Plural sibling of `repo`, matched with the same both-shapes rule;
270
+ * an empty array means "no rows", which the caller must avoid by not
271
+ * passing it. Ignored when `repo` is also set (the single-repo Repos tab
272
+ * is the narrower ask).
273
+ */
274
+ repos?: string[];
253
275
  statuses?: string[];
254
276
  }): {
255
277
  runs: WorkflowRun[];
@@ -292,10 +314,14 @@ export declare class WorkflowRunStore {
292
314
  * which annotates the managed-repo list with recent activity and sorts by it.
293
315
  * Ordered newest-activity first.
294
316
  *
295
- * The `repo` key is the QUALIFIED `owner/repo` (owner-less legacy rows fall
296
- * back to the bare name) so it aligns with `getManagedRepos()` and the
297
- * artifact-store slugs the `/repos` endpoint unions it against — without this
298
- * a repo split into two rows (bare-with-runs vs qualified-managed-with-zero).
317
+ * The `repo` key is the QUALIFIED `owner/repo` (owner-less rows fall back to
318
+ * the bare name) so it aligns with `getManagedRepos()` and the artifact-store
319
+ * slugs the `/repos` endpoint unions it against — without this a repo splits
320
+ * into two rows (bare-with-runs vs qualified-managed-with-zero).
321
+ *
322
+ * That join is the one in `state/repo-ref.ts`, expressed in SQL so it groups
323
+ * correctly: two rows for the same repo that disagree about shape collapse
324
+ * into one bucket here rather than after the fact.
299
325
  */
300
326
  distinctRepos(): {
301
327
  repo: string;
@@ -1,3 +1,4 @@
1
+ import { normalizeRepoRef, qualifiedRepoSql } from "./repo-ref.js";
1
2
  import { logger } from "../logging/logger.js";
2
3
  const log = logger("runs");
3
4
  /**
@@ -23,6 +24,32 @@ const ACTIVE_FIRST = `CASE status
23
24
  WHEN 'queued' THEN 2
24
25
  ELSE 3
25
26
  END`;
27
+ /**
28
+ * Match one `owner/repo` against a `workflow_runs` row, in SQL.
29
+ *
30
+ * Exists because callers filter by the qualified name while the table stores
31
+ * the pair — `owner` + a BARE `repo` (see `state/repo-ref.ts`). That is the
32
+ * rule, and `owner = ? AND repo = ?` is it. A bare filter value has no owner to
33
+ * split off, so it matches `repo` alone.
34
+ *
35
+ * The trailing `OR repo = ?` is **legacy-row handling, not the rule** (issue
36
+ * #279). Rows written before the backfill put the qualified string in `repo`
37
+ * itself; the migration converges them and both write choke points keep new
38
+ * ones honest, so this arm should match nothing on a migrated DB. It is kept
39
+ * because a `SELECT` is not the place to discover that a backfill didn't run,
40
+ * and because dropping a row from a filter is the failure mode that hides
41
+ * things silently.
42
+ */
43
+ function repoMatchClause(repo) {
44
+ const slash = repo.indexOf("/");
45
+ if (slash > 0) {
46
+ return {
47
+ sql: "((owner = ? AND repo = ?) OR repo = ?)",
48
+ values: [repo.slice(0, slash), repo.slice(slash + 1), repo],
49
+ };
50
+ }
51
+ return { sql: "repo = ?", values: [repo] };
52
+ }
26
53
  export class WorkflowRunStore {
27
54
  db;
28
55
  approvals;
@@ -64,13 +91,21 @@ export class WorkflowRunStore {
64
91
  }
65
92
  }
66
93
  // ── Plain single-mutation operations ───────────────────────────
67
- /** Create a new workflow run record */
94
+ /**
95
+ * Create a new workflow run record.
96
+ *
97
+ * The (owner, BARE repo) invariant is enforced HERE rather than asked of
98
+ * callers (issue #279) — a fixture, an eval harness or a future caller
99
+ * passing `"owner/repo"` is split rather than stored as a third shape. See
100
+ * `state/repo-ref.ts`.
101
+ */
68
102
  createRun(run) {
69
103
  const now = new Date().toISOString();
104
+ const ref = normalizeRepoRef(run.owner, run.repo);
70
105
  this.db.prepare(`
71
106
  INSERT INTO workflow_runs (id, workflow_name, trigger_id, owner, repo, issue_number, current_phase, phase_history, status, context, scratch, started_at, updated_at, triggered_by, trigger_actor_type)
72
107
  VALUES (?, ?, ?, ?, ?, ?, ?, '[]', ?, ?, ?, ?, ?, ?, ?)
73
- `).run(run.id, run.workflowName, run.triggerId, run.owner ?? null, run.repo ?? null, run.issueNumber ?? null, run.currentPhase, run.status, run.context ? JSON.stringify(run.context) : null, run.scratch ? JSON.stringify(run.scratch) : null, run.startedAt, now, run.triggeredBy ?? null, run.triggerActorType ?? null);
108
+ `).run(run.id, run.workflowName, run.triggerId, ref.owner ?? null, ref.repo ?? null, run.issueNumber ?? null, run.currentPhase, run.status, run.context ? JSON.stringify(run.context) : null, run.scratch ? JSON.stringify(run.scratch) : null, run.startedAt, now, run.triggeredBy ?? null, run.triggerActorType ?? null);
74
109
  }
75
110
  /**
76
111
  * Top-level merge of `patch` into the workflow run's scratch state.
@@ -288,20 +323,17 @@ export class WorkflowRunStore {
288
323
  params.push(opts.workflowName);
289
324
  }
290
325
  if (opts.repo) {
291
- // The Repos tab filters by the qualified `owner/repo`, but the column is
292
- // the bare repo (+ a separate `owner`). Match EITHER shape: new rows
293
- // (`owner` set, `repo` bare) via `owner = ? AND repo = ?`, OR legacy rows
294
- // that stored the qualified string in `repo` itself via `repo = ?`. A
295
- // bare filter value has no owner to split, so it just matches `repo`.
296
- const slash = opts.repo.indexOf("/");
297
- if (slash > 0) {
298
- where.push("((owner = ? AND repo = ?) OR repo = ?)");
299
- params.push(opts.repo.slice(0, slash), opts.repo.slice(slash + 1), opts.repo);
300
- }
301
- else {
302
- where.push("repo = ?");
303
- params.push(opts.repo);
304
- }
326
+ const { sql, values } = repoMatchClause(opts.repo);
327
+ where.push(sql);
328
+ params.push(...values);
329
+ }
330
+ else if (opts.repos && opts.repos.length > 0) {
331
+ // OR the per-repo clauses. Not an `IN (...)`, because the column doesn't
332
+ // hold the value being matched — see `repoMatchClause`.
333
+ const parts = opts.repos.map((r) => repoMatchClause(r));
334
+ where.push(`(${parts.map((p) => p.sql).join(" OR ")})`);
335
+ for (const p of parts)
336
+ params.push(...p.values);
305
337
  }
306
338
  if (opts.statuses && opts.statuses.length > 0) {
307
339
  where.push(`status IN (${opts.statuses.map(() => "?").join(",")})`);
@@ -425,24 +457,24 @@ export class WorkflowRunStore {
425
457
  * which annotates the managed-repo list with recent activity and sorts by it.
426
458
  * Ordered newest-activity first.
427
459
  *
428
- * The `repo` key is the QUALIFIED `owner/repo` (owner-less legacy rows fall
429
- * back to the bare name) so it aligns with `getManagedRepos()` and the
430
- * artifact-store slugs the `/repos` endpoint unions it against — without this
431
- * a repo split into two rows (bare-with-runs vs qualified-managed-with-zero).
460
+ * The `repo` key is the QUALIFIED `owner/repo` (owner-less rows fall back to
461
+ * the bare name) so it aligns with `getManagedRepos()` and the artifact-store
462
+ * slugs the `/repos` endpoint unions it against — without this a repo splits
463
+ * into two rows (bare-with-runs vs qualified-managed-with-zero).
464
+ *
465
+ * That join is the one in `state/repo-ref.ts`, expressed in SQL so it groups
466
+ * correctly: two rows for the same repo that disagree about shape collapse
467
+ * into one bucket here rather than after the fact.
432
468
  */
433
469
  distinctRepos() {
434
- const rows = this.db
435
- .prepare(`SELECT owner, repo, COUNT(*) AS c, MAX(started_at) AS last
470
+ const qualified = qualifiedRepoSql("owner", "repo", "bare");
471
+ return this.db
472
+ .prepare(`SELECT ${qualified} AS repo, COUNT(*) AS runCount, MAX(started_at) AS lastRunAt
436
473
  FROM workflow_runs
437
474
  WHERE repo IS NOT NULL AND repo != ''
438
- GROUP BY owner, repo
439
- ORDER BY last DESC`)
475
+ GROUP BY ${qualified}
476
+ ORDER BY lastRunAt DESC`)
440
477
  .all();
441
- return rows.map((r) => ({
442
- repo: r.owner && !r.repo.includes("/") ? `${r.owner}/${r.repo}` : r.repo,
443
- runCount: r.c,
444
- lastRunAt: r.last,
445
- }));
446
478
  }
447
479
  /**
448
480
  * Mark a workflow run as finished. Plain status flip when called with just
@@ -587,12 +619,19 @@ export class WorkflowRunStore {
587
619
  return row?.restart_count ?? 0;
588
620
  }
589
621
  deserialize(row) {
622
+ // The compatibility shim for the (owner, BARE repo) invariant (issue #279).
623
+ // The backfill converges stored rows and `createRun` keeps new ones honest,
624
+ // so this only ever fires for a row written by an older process before the
625
+ // migration ran — but it fires at the ONE boundary every consumer crosses,
626
+ // which is what lets `admission.ts` and `feedback-poll.ts` hand
627
+ // `(run.owner, run.repo)` straight to Octokit with no split of their own.
628
+ const ref = normalizeRepoRef(row.owner, row.repo);
590
629
  return {
591
630
  id: row.id,
592
631
  workflowName: row.workflow_name,
593
632
  triggerId: row.trigger_id,
594
- owner: row.owner ?? undefined,
595
- repo: row.repo,
633
+ owner: ref.owner,
634
+ repo: ref.repo,
596
635
  issueNumber: row.issue_number,
597
636
  triggeredBy: row.triggered_by ?? undefined,
598
637
  triggerActorType: row.trigger_actor_type ?? undefined,