co-maintainer 0.6.8 → 0.6.10

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 (75) hide show
  1. package/dist/package.json +1 -1
  2. package/dist/src/ai/fake.d.ts +10 -1
  3. package/dist/src/ai/fake.js +39 -4
  4. package/dist/src/cli/args.js +2 -0
  5. package/dist/src/cli/command_json.d.ts +6 -0
  6. package/dist/src/cli/command_json.js +1 -0
  7. package/dist/src/cli/commands/probe.js +25 -0
  8. package/dist/src/cli/commands/registry.js +11 -0
  9. package/dist/src/cli/commands/review.js +5 -1
  10. package/dist/src/cli/commands/serve.js +10 -0
  11. package/dist/src/cli/commands/set.js +23 -2
  12. package/dist/src/cli/review_args.d.ts +9 -0
  13. package/dist/src/cli/review_args.js +36 -1
  14. package/dist/src/cli/review_github.js +6 -2
  15. package/dist/src/cli/review_result.js +6 -5
  16. package/dist/src/github/app.d.ts +4 -0
  17. package/dist/src/github/app.js +10 -1
  18. package/dist/src/github/permissions.js +40 -0
  19. package/dist/src/local/git_ops.js +3 -2
  20. package/dist/src/local/git_revision.d.ts +5 -2
  21. package/dist/src/local/git_revision.js +17 -10
  22. package/dist/src/pr/checkout.js +14 -5
  23. package/dist/src/pr/codegraph_tools.js +5 -3
  24. package/dist/src/pr/reviewer.d.ts +2 -0
  25. package/dist/src/pr/reviewer.js +1 -1
  26. package/dist/src/remote/client.js +14 -4
  27. package/dist/src/remote/push_client.d.ts +7 -0
  28. package/dist/src/remote/push_client.js +287 -0
  29. package/dist/src/remote/server/body.d.ts +11 -0
  30. package/dist/src/remote/server/body.js +14 -5
  31. package/dist/src/remote/server/routes.d.ts +1 -0
  32. package/dist/src/remote/server/routes.js +61 -4
  33. package/dist/src/remote/server/sync.js +11 -3
  34. package/dist/src/remote/validate.js +17 -0
  35. package/dist/src/server/api/repos.js +13 -2
  36. package/dist/src/server/app.js +5 -6
  37. package/dist/src/server/http.js +5 -0
  38. package/dist/src/server/pages/layout.js +1 -0
  39. package/dist/src/server/pages/repo.d.ts +3 -1
  40. package/dist/src/server/pages/repo.js +4 -1
  41. package/dist/src/server/pages/repo_pushes.d.ts +7 -0
  42. package/dist/src/server/pages/repo_pushes.js +144 -0
  43. package/dist/src/server/pages/repo_settings.js +45 -1
  44. package/dist/src/server/pages/router.js +34 -5
  45. package/dist/src/server/pages/settings.js +1 -1
  46. package/dist/src/server/webhook/index.js +24 -7
  47. package/dist/src/services/dashboard.d.ts +46 -0
  48. package/dist/src/services/dashboard.js +24 -0
  49. package/dist/src/services/jobs.js +18 -3
  50. package/dist/src/services/push_review.d.ts +51 -0
  51. package/dist/src/services/push_review.js +878 -0
  52. package/dist/src/services/setup.js +21 -0
  53. package/dist/src/services/watch_comments.d.ts +10 -0
  54. package/dist/src/services/watch_comments.js +179 -0
  55. package/dist/src/services/watch_issues.d.ts +70 -0
  56. package/dist/src/services/watch_issues.js +266 -0
  57. package/dist/src/services/watch_notes.d.ts +8 -0
  58. package/dist/src/services/watch_notes.js +80 -0
  59. package/dist/src/services/watch_status.d.ts +25 -0
  60. package/dist/src/services/watch_status.js +101 -0
  61. package/dist/src/services/webhook.js +107 -3
  62. package/dist/src/store/migrations.js +63 -0
  63. package/dist/src/store/repos.d.ts +1 -1
  64. package/dist/src/store/rows.d.ts +6 -0
  65. package/dist/src/store/sessions.d.ts +3 -0
  66. package/dist/src/store/sessions.js +5 -0
  67. package/dist/src/store/watch.d.ts +108 -0
  68. package/dist/src/store/watch.js +186 -0
  69. package/dist/src/types.d.ts +2 -0
  70. package/dist/src/util/repo_name.d.ts +2 -0
  71. package/dist/src/util/repo_name.js +56 -0
  72. package/dist/src/util/runtime.js +7 -0
  73. package/dist/src/util/sanitize.d.ts +6 -0
  74. package/dist/src/util/sanitize.js +10 -0
  75. package/package.json +1 -1
@@ -0,0 +1,25 @@
1
+ import { type PushSource } from "../store/watch.ts";
2
+ import type { ReviewRow } from "../store/rows.ts";
3
+ export type AppPushState =
4
+ /** No App is configured, or GitHub could not be asked. */
5
+ "unknown"
6
+ /** No installation of the App covers the repository. */
7
+ | "not-installed" | "off" | "on";
8
+ export type WatchStatus = {
9
+ app: AppPushState;
10
+ /** A CI step has sent at least one push. */
11
+ ci: boolean;
12
+ lastPush: (ReviewRow & {
13
+ via: PushSource[];
14
+ }) | undefined;
15
+ };
16
+ /** For tests: forget what GitHub said. */
17
+ export declare function clearWatchStatusCache(): void;
18
+ export declare function appPushState(repo: string): Promise<AppPushState>;
19
+ /** For `probe`, which runs without app.db: whether the App's installation on
20
+ * the repository receives `push`. Undefined when this machine has no App
21
+ * configured, the App is not installed there, or GitHub could not be asked:
22
+ * then `probe` says nothing about commit watch. */
23
+ export declare function appPushStateWithoutDb(repo: string): Promise<"on" | "off" | undefined>;
24
+ export declare function pushVia(repo: string, review: ReviewRow): PushSource[];
25
+ export declare function watchStatus(repo: string): Promise<WatchStatus>;
@@ -0,0 +1,101 @@
1
+ /** Is commit watch on for a repository, and through what.
2
+ *
3
+ * The App watches when its installation for the repository receives the
4
+ * `push` event. That is a setting on GitHub, so it is read from
5
+ * `GET /app/installations`, and cached for a minute so a page view does not
6
+ * call GitHub every time. CI watches when a CI step has sent a push. */
7
+ import { AppJwtClient, findInstallationForRepo } from "../github/app.js";
8
+ import { readConfig, resolveAppPrivateKey } from "../config.js";
9
+ import { getRepo } from "../store/repos.js";
10
+ import { getAppDb } from "../store/app_db.js";
11
+ import { latestPushReview } from "../store/watch.js";
12
+ const CACHE_MS = 60_000;
13
+ let cache;
14
+ /** The events each installation receives, by installation id. */
15
+ async function installationEvents() {
16
+ if (cache && Date.now() - cache.at < CACHE_MS)
17
+ return cache.events;
18
+ const config = readConfig();
19
+ const pem = resolveAppPrivateKey(config);
20
+ if (!config.githubAppId || !pem)
21
+ return undefined;
22
+ try {
23
+ const installations = await new AppJwtClient(config.githubAppId, pem).listInstallations();
24
+ const events = new Map(installations.map((installation) => [
25
+ installation.id,
26
+ installation.events ?? [],
27
+ ]));
28
+ cache = { at: Date.now(), events };
29
+ return events;
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ }
35
+ /** For tests: forget what GitHub said. */
36
+ export function clearWatchStatusCache() {
37
+ cache = undefined;
38
+ }
39
+ export async function appPushState(repo) {
40
+ const events = await installationEvents();
41
+ if (!events)
42
+ return "unknown";
43
+ const id = getRepo(repo)?.installation_id;
44
+ if (!id || !events.has(id))
45
+ return "not-installed";
46
+ return events.get(id).includes("push") ? "on" : "off";
47
+ }
48
+ /** For `probe`, which runs without app.db: whether the App's installation on
49
+ * the repository receives `push`. Undefined when this machine has no App
50
+ * configured, the App is not installed there, or GitHub could not be asked:
51
+ * then `probe` says nothing about commit watch. */
52
+ export async function appPushStateWithoutDb(repo) {
53
+ const config = readConfig();
54
+ const pem = resolveAppPrivateKey(config);
55
+ if (!config.githubAppId || !pem)
56
+ return undefined;
57
+ try {
58
+ const id = await findInstallationForRepo(config.githubAppId, pem, repo);
59
+ if (id === undefined)
60
+ return undefined;
61
+ const events = await installationEvents();
62
+ const list = events?.get(id);
63
+ if (!list)
64
+ return undefined;
65
+ return list.includes("push") ? "on" : "off";
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ function ciHasPushed(repo) {
72
+ const row = getAppDb()
73
+ .prepare(`SELECT COUNT(*) AS n FROM push_events
74
+ WHERE repo = ? AND sources LIKE '%"ci"%'`)
75
+ .get(repo);
76
+ return Number(row?.n ?? 0) > 0;
77
+ }
78
+ function viaOf(repo, review) {
79
+ const row = getAppDb()
80
+ .prepare(`SELECT sources FROM push_events WHERE repo = ? AND review_id = ?
81
+ ORDER BY created_at DESC LIMIT 1`)
82
+ .get(repo, review.id);
83
+ try {
84
+ const parsed = JSON.parse(row?.sources ?? "[]");
85
+ return parsed.filter((s) => s === "app" || s === "ci");
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ }
91
+ export function pushVia(repo, review) {
92
+ return viaOf(repo, review);
93
+ }
94
+ export async function watchStatus(repo) {
95
+ const last = latestPushReview(repo);
96
+ return {
97
+ app: await appPushState(repo),
98
+ ci: ciHasPushed(repo),
99
+ lastPush: last ? { ...last, via: viaOf(repo, last) } : undefined,
100
+ };
101
+ }
@@ -8,8 +8,14 @@ import { latestPostedReview } from "../store/reviews.js";
8
8
  import { getQueuedJob } from "../store/jobs.js";
9
9
  import { markInstallationRemoved, markInstallationSuspended, upsertInstallation, } from "../store/installations.js";
10
10
  import { readConfig } from "../config.js";
11
+ import { getWatchIssue } from "../store/watch.js";
12
+ import { canonicalRepoName } from "../util/repo_name.js";
13
+ import { isSha, isZeroSha, queuePush } from "./push_review.js";
14
+ import { WATCH_COMMENT_JOB } from "./watch_comments.js";
11
15
  import { carriesEarlierRequest, evaluatePolicy, isRequestCommand, legacyPolicy, parsePolicy, } from "./review_policy.js";
12
16
  export const REVIEW_DEBOUNCE_MS = 20_000;
17
+ /** Who may talk to commit watch on its issues: people with write access. */
18
+ const WRITE_ASSOCIATIONS = new Set(["OWNER", "MEMBER", "COLLABORATOR"]);
13
19
  const PR_ACTIONS = new Set([
14
20
  "opened",
15
21
  "reopened",
@@ -260,8 +266,9 @@ function applyInstallationRepositories(payload) {
260
266
  if (Array.isArray(added)) {
261
267
  for (const item of added) {
262
268
  const fullName = asString(asRecord(item)?.full_name);
263
- if (fullName)
264
- setInstallationId(fullName, installationId);
269
+ if (fullName) {
270
+ setInstallationId(canonicalRepoName(fullName), installationId);
271
+ }
265
272
  }
266
273
  }
267
274
  return { outcome: "ignored", reason: "repositories-added" };
@@ -272,7 +279,7 @@ function applyInstallationRepositories(payload) {
272
279
  for (const item of removed) {
273
280
  const fullName = asString(asRecord(item)?.full_name);
274
281
  if (fullName)
275
- deactivateRepo(fullName);
282
+ deactivateRepo(canonicalRepoName(fullName));
276
283
  }
277
284
  }
278
285
  return { outcome: "ignored", reason: "repositories-removed" };
@@ -511,9 +518,106 @@ function issueCommentEvent(payload, deliveryId) {
511
518
  }
512
519
  return enqueueReply(payload, deliveryId, "issue_comment", String(sourceId), repo, prNumber, body, asString(author?.login));
513
520
  }
521
+ /** Commit watch through the App: a push to the repository's default branch.
522
+ * Any other branch, a deleted branch and a tag are ignored. */
523
+ function pushEvent(payload, deliveryId) {
524
+ const repository = asRecord(payload.repository);
525
+ const repo = asString(repository?.full_name);
526
+ const ref = asString(payload.ref) ?? "";
527
+ const before = asString(payload.before) ?? "";
528
+ const after = asString(payload.after) ?? "";
529
+ const defaultBranch = asString(repository?.default_branch);
530
+ if (!repo || !defaultBranch || ref !== `refs/heads/${defaultBranch}`) {
531
+ return { outcome: "ignored", reason: "not-default-branch", repo };
532
+ }
533
+ if (asBool(payload.deleted) || !isSha(after) || isZeroSha(after)) {
534
+ return { outcome: "ignored", reason: "branch-deleted", repo };
535
+ }
536
+ if (!isSha(before))
537
+ return { outcome: "ignored", repo };
538
+ const installationId = asNumber(asRecord(payload.installation)?.id);
539
+ if (installationId !== undefined)
540
+ setInstallationId(repo, installationId);
541
+ const outcome = queuePush({
542
+ repo,
543
+ before,
544
+ after,
545
+ ref,
546
+ source: "app",
547
+ deliveryId,
548
+ });
549
+ switch (outcome.kind) {
550
+ case "enqueued":
551
+ case "attached":
552
+ return { outcome: "enqueued", repo, jobId: outcome.jobId };
553
+ case "no_changes":
554
+ return { outcome: "skipped", reason: "no-changes", repo };
555
+ case "extend":
556
+ // Only a CI diff can need a wider range, and this push has none.
557
+ return { outcome: "skipped", reason: "range-extend", repo };
558
+ case "skipped":
559
+ return { outcome: "skipped", reason: outcome.reason, repo };
560
+ }
561
+ }
562
+ /** A comment on an issue commit watch opened. Only someone with write access
563
+ * is listened to, and the comment job decides whether it was meant for us. */
564
+ function watchIssueCommentEvent(payload, deliveryId) {
565
+ const issue = asRecord(payload.issue);
566
+ const comment = asRecord(payload.comment);
567
+ const repo = asString(asRecord(payload.repository)?.full_name);
568
+ const number = asNumber(issue?.number);
569
+ const commentId = comment?.id;
570
+ if (asString(payload.action) !== "created" ||
571
+ !repo ||
572
+ number === undefined ||
573
+ (typeof commentId !== "number" && typeof commentId !== "string")) {
574
+ return { outcome: "ignored", repo };
575
+ }
576
+ if (!getWatchIssue(repo, number)) {
577
+ return { outcome: "ignored", reason: "not-a-watch-issue", repo };
578
+ }
579
+ const author = asRecord(comment?.user);
580
+ if (isBot(author)) {
581
+ return { outcome: "skipped", reason: "own-comment", repo };
582
+ }
583
+ const association = asString(comment?.author_association) ?? "NONE";
584
+ if (!WRITE_ASSOCIATIONS.has(association)) {
585
+ return {
586
+ outcome: "skipped",
587
+ reason: `no-write-access: ${association}`,
588
+ repo,
589
+ };
590
+ }
591
+ const row = getRepo(repo);
592
+ if (!row || row.active !== 1) {
593
+ return { outcome: "skipped", reason: "repo-not-active", repo };
594
+ }
595
+ const installationId = asNumber(asRecord(payload.installation)?.id);
596
+ if (installationId !== undefined)
597
+ setInstallationId(repo, installationId);
598
+ const { id } = enqueue({
599
+ type: WATCH_COMMENT_JOB,
600
+ repo,
601
+ deliveryId,
602
+ queueKey: `watch-comment:${repo}:${String(commentId)}`,
603
+ args: {
604
+ issueNumber: number,
605
+ commentId: String(commentId),
606
+ author: asString(author?.login) ?? null,
607
+ body: (asString(comment?.body) ?? "").slice(0, 20_000),
608
+ },
609
+ });
610
+ return { outcome: "enqueued", repo, jobId: id };
611
+ }
514
612
  export function dispatchGithubEvent(event, payload, deliveryId, maxDiffLines) {
515
613
  if (event === "installation")
516
614
  return applyInstallation(payload);
615
+ if (event === "push")
616
+ return pushEvent(payload, deliveryId);
617
+ if (event === "issue_comment" &&
618
+ !asRecord(asRecord(payload.issue)?.pull_request)) {
619
+ return watchIssueCommentEvent(payload, deliveryId);
620
+ }
517
621
  if (event === "installation_repositories") {
518
622
  return applyInstallationRepositories(payload);
519
623
  }
@@ -289,4 +289,67 @@ export const migrations = [
289
289
  // (registered by init itself, or found on disk by serve after an upgrade),
290
290
  // NULL for one added from the dashboard.
291
291
  [`ALTER TABLE repos ADD COLUMN added_from TEXT`],
292
+ // 15 — commit watch: pushes to the default branch, the issues opened for
293
+ // their P0/P1 findings, and the maintainer notes left on those issues.
294
+ [
295
+ `ALTER TABLE repos ADD COLUMN watch_open_issues INTEGER NOT NULL DEFAULT 1`,
296
+ `ALTER TABLE repos ADD COLUMN watch_push_mode TEXT NOT NULL DEFAULT 'queue'`,
297
+ `CREATE TABLE push_events (
298
+ repo TEXT NOT NULL,
299
+ after_sha TEXT NOT NULL,
300
+ before_sha TEXT NOT NULL,
301
+ ref TEXT NOT NULL,
302
+ sources TEXT NOT NULL DEFAULT '[]',
303
+ review_id TEXT,
304
+ job_id TEXT,
305
+ created_at TEXT NOT NULL,
306
+ PRIMARY KEY (repo, after_sha)
307
+ )`,
308
+ `CREATE INDEX idx_push_events_review ON push_events(review_id)`,
309
+ `CREATE TABLE push_inputs (
310
+ job_id TEXT PRIMARY KEY,
311
+ revision_json TEXT NOT NULL,
312
+ created_at TEXT NOT NULL
313
+ )`,
314
+ `CREATE TABLE push_results (
315
+ review_id TEXT PRIMARY KEY,
316
+ result_json TEXT NOT NULL,
317
+ created_at TEXT NOT NULL
318
+ )`,
319
+ `CREATE TABLE watch_issues (
320
+ id TEXT PRIMARY KEY,
321
+ repo TEXT NOT NULL,
322
+ issue_number INTEGER NOT NULL,
323
+ severity TEXT NOT NULL,
324
+ title TEXT NOT NULL,
325
+ body_md TEXT NOT NULL,
326
+ path TEXT,
327
+ line_from INTEGER,
328
+ line_to INTEGER,
329
+ anchor_text TEXT,
330
+ state TEXT NOT NULL,
331
+ closed_check TEXT,
332
+ opened_review_id TEXT NOT NULL,
333
+ last_review_id TEXT,
334
+ last_check TEXT,
335
+ last_check_at TEXT,
336
+ created_at TEXT NOT NULL,
337
+ updated_at TEXT NOT NULL
338
+ )`,
339
+ `CREATE UNIQUE INDEX idx_watch_issues_number
340
+ ON watch_issues(repo, issue_number)`,
341
+ `CREATE TABLE watch_notes (
342
+ id TEXT PRIMARY KEY,
343
+ repo TEXT NOT NULL,
344
+ issue_number INTEGER NOT NULL,
345
+ comment_id TEXT NOT NULL,
346
+ author TEXT,
347
+ kind TEXT NOT NULL,
348
+ body TEXT NOT NULL,
349
+ note TEXT,
350
+ created_at TEXT NOT NULL,
351
+ applied_at TEXT,
352
+ UNIQUE(repo, comment_id)
353
+ )`,
354
+ ],
292
355
  ];
@@ -7,7 +7,7 @@ export declare function activateRepo(fullName: string, installationId: number |
7
7
  export declare function registerCliRepo(fullName: string, knowledgeBuiltAt?: string): boolean;
8
8
  export declare function deactivateRepo(fullName: string): void;
9
9
  export declare function deactivateReposForInstallation(installationId: number): void;
10
- export declare function updateRepoSettings(fullName: string, patch: Partial<Pick<RepoRow, "auto_review" | "review_scope" | "skip_drafts" | "skip_bots" | "use_codegraph" | "review_policy_json">>): void;
10
+ export declare function updateRepoSettings(fullName: string, patch: Partial<Pick<RepoRow, "auto_review" | "review_scope" | "skip_drafts" | "skip_bots" | "use_codegraph" | "review_policy_json" | "watch_open_issues" | "watch_push_mode">>): void;
11
11
  export declare function markKnowledgeBuilt(fullName: string, baseSha: string): void;
12
12
  /** Forgets the built knowledge: the stamp every review and the dashboard read
13
13
  * as "built", and the drift baseline that only meant anything against it. */
@@ -30,6 +30,12 @@ export type RepoRow = {
30
30
  /** `'cli'` when a CLI init built it, NULL when added from the dashboard.
31
31
  * Optional so a row built by hand (a test fixture) need not name it. */
32
32
  added_from?: string | null;
33
+ /** Commit watch: 1 opens an issue for each P0/P1 finding. Optional so a
34
+ * hand-built fixture need not name it; missing means on. */
35
+ watch_open_issues?: number;
36
+ /** Commit watch: `queue` reviews pushes in a row one by one,
37
+ * `cancel-and-merge` folds a waiting or running review into the next. */
38
+ watch_push_mode?: string;
33
39
  };
34
40
  export type JobRow = {
35
41
  id: string;
@@ -7,3 +7,6 @@ export declare function getSession(tokenHash: string): SessionRow | undefined;
7
7
  export declare function deleteSession(tokenHash: string): void;
8
8
  export declare function deleteExpiredSessions(): void;
9
9
  export declare function deleteOtherSessions(keepTokenHash: string): void;
10
+ /** Drop every dashboard session. Used when a credential is reset from the CLI,
11
+ * so a leaked cookie cannot outlive the password it was issued under. */
12
+ export declare function deleteAllSessions(): void;
@@ -37,3 +37,8 @@ export function deleteOtherSessions(keepTokenHash) {
37
37
  .prepare(`DELETE FROM sessions WHERE token_hash != ?`)
38
38
  .run(keepTokenHash);
39
39
  }
40
+ /** Drop every dashboard session. Used when a credential is reset from the CLI,
41
+ * so a leaked cookie cannot outlive the password it was issued under. */
42
+ export function deleteAllSessions() {
43
+ getAppDb().prepare(`DELETE FROM sessions`).run();
44
+ }
@@ -0,0 +1,108 @@
1
+ import type { ReviewRow, SubjectRow } from "./rows.ts";
2
+ export type PushSource = "app" | "ci";
3
+ export type PushEventRow = {
4
+ repo: string;
5
+ after_sha: string;
6
+ before_sha: string;
7
+ ref: string;
8
+ /** JSON array of `PushSource`. */
9
+ sources: string;
10
+ review_id: string | null;
11
+ job_id: string | null;
12
+ created_at: string;
13
+ };
14
+ export type WatchIssueState = "open" | "closed_by_us" | "closed_by_user" | "ignored";
15
+ /** For an issue a maintainer closed: `pending` until the first push review
16
+ * after the closing checks it, then `still_found` or `fixed`. */
17
+ export type ClosedCheck = "pending" | "still_found" | "fixed";
18
+ export type WatchIssueRow = {
19
+ id: string;
20
+ repo: string;
21
+ issue_number: number;
22
+ severity: string;
23
+ title: string;
24
+ body_md: string;
25
+ path: string | null;
26
+ line_from: number | null;
27
+ line_to: number | null;
28
+ anchor_text: string | null;
29
+ state: WatchIssueState;
30
+ closed_check: ClosedCheck | null;
31
+ opened_review_id: string;
32
+ last_review_id: string | null;
33
+ last_check: string | null;
34
+ last_check_at: string | null;
35
+ created_at: string;
36
+ updated_at: string;
37
+ };
38
+ export type WatchNoteRow = {
39
+ id: string;
40
+ repo: string;
41
+ issue_number: number;
42
+ comment_id: string;
43
+ author: string | null;
44
+ kind: "ignore" | "info";
45
+ body: string;
46
+ note: string | null;
47
+ created_at: string;
48
+ applied_at: string | null;
49
+ };
50
+ export declare function pushSources(row: PushEventRow): PushSource[];
51
+ export declare function getPushEvent(repo: string, afterSha: string): PushEventRow | undefined;
52
+ export declare function insertPushEvent(row: {
53
+ repo: string;
54
+ afterSha: string;
55
+ beforeSha: string;
56
+ ref: string;
57
+ source: PushSource;
58
+ }): void;
59
+ export declare function addPushSource(repo: string, afterSha: string, source: PushSource): void;
60
+ export declare function setPushEventReview(repo: string, afterSha: string, reviewId: string, jobId: string): void;
61
+ /** Every push whose review moves to a merged one, so a CI step still waiting
62
+ * on an older push finds the review that now covers it. */
63
+ export declare function movePushEvents(fromReviewId: string, toReviewId: string, toJobId: string): void;
64
+ export declare function listPushEventsForReview(reviewId: string): PushEventRow[];
65
+ export declare function getOrCreatePushSubject(repo: string, branch: string): SubjectRow;
66
+ export declare function insertPushReview(row: {
67
+ id: string;
68
+ subjectId: string;
69
+ repo: string;
70
+ branch: string;
71
+ jobId: string;
72
+ beforeSha: string;
73
+ afterSha: string;
74
+ model: string;
75
+ }): void;
76
+ export declare function setPushReviewRange(reviewId: string, beforeSha: string): void;
77
+ export declare function listPushReviewsForRepo(repo: string, limit?: number): ReviewRow[];
78
+ export declare function latestPushReview(repo: string): ReviewRow | undefined;
79
+ export declare function savePushInput(jobId: string, revisionJson: string): void;
80
+ export declare function getPushInput(jobId: string): string | undefined;
81
+ export declare function deletePushInput(jobId: string): void;
82
+ export declare function savePushResult(reviewId: string, result: unknown): void;
83
+ export declare function getPushResult(reviewId: string): Record<string, unknown> | undefined;
84
+ export declare function insertWatchIssue(row: {
85
+ repo: string;
86
+ issueNumber: number;
87
+ severity: string;
88
+ title: string;
89
+ bodyMd: string;
90
+ path: string | null;
91
+ lineFrom: number | null;
92
+ lineTo: number | null;
93
+ anchorText: string | null;
94
+ reviewId: string;
95
+ }): WatchIssueRow;
96
+ export declare function getWatchIssue(repo: string, issueNumber: number): WatchIssueRow | undefined;
97
+ export declare function listWatchIssues(repo: string): WatchIssueRow[];
98
+ export declare function updateWatchIssue(id: string, patch: Partial<Pick<WatchIssueRow, "state" | "closed_check" | "path" | "line_from" | "line_to" | "anchor_text" | "last_review_id" | "last_check" | "last_check_at">>): void;
99
+ export declare function insertWatchNote(row: {
100
+ repo: string;
101
+ issueNumber: number;
102
+ commentId: string;
103
+ author: string | null;
104
+ kind: "ignore" | "info";
105
+ body: string;
106
+ }): boolean;
107
+ export declare function listWatchNotes(repo: string): WatchNoteRow[];
108
+ export declare function markWatchNoteApplied(id: string, note: string): void;
@@ -0,0 +1,186 @@
1
+ /** Commit watch tables: the pushes to a default branch, the issues opened
2
+ * for their P0/P1 findings, and the notes maintainers left on those issues. */
3
+ import { getAppDb } from "./app_db.js";
4
+ import { nowIso } from "../util/time.js";
5
+ export function pushSources(row) {
6
+ try {
7
+ const parsed = JSON.parse(row.sources);
8
+ return Array.isArray(parsed)
9
+ ? parsed.filter((s) => s === "app" || s === "ci")
10
+ : [];
11
+ }
12
+ catch {
13
+ return [];
14
+ }
15
+ }
16
+ export function getPushEvent(repo, afterSha) {
17
+ return getAppDb()
18
+ .prepare(`SELECT * FROM push_events WHERE repo = ? AND after_sha = ?`)
19
+ .get(repo, afterSha);
20
+ }
21
+ export function insertPushEvent(row) {
22
+ getAppDb()
23
+ .prepare(`INSERT INTO push_events
24
+ (repo, after_sha, before_sha, ref, sources, review_id, job_id, created_at)
25
+ VALUES (?, ?, ?, ?, ?, NULL, NULL, ?)`)
26
+ .run(row.repo, row.afterSha, row.beforeSha, row.ref, JSON.stringify([row.source]), nowIso());
27
+ }
28
+ export function addPushSource(repo, afterSha, source) {
29
+ const row = getPushEvent(repo, afterSha);
30
+ if (!row)
31
+ return;
32
+ const sources = new Set(pushSources(row));
33
+ sources.add(source);
34
+ getAppDb()
35
+ .prepare(`UPDATE push_events SET sources = ? WHERE repo = ? AND after_sha = ?`)
36
+ .run(JSON.stringify([...sources]), repo, afterSha);
37
+ }
38
+ export function setPushEventReview(repo, afterSha, reviewId, jobId) {
39
+ getAppDb()
40
+ .prepare(`UPDATE push_events SET review_id = ?, job_id = ?
41
+ WHERE repo = ? AND after_sha = ?`)
42
+ .run(reviewId, jobId, repo, afterSha);
43
+ }
44
+ /** Every push whose review moves to a merged one, so a CI step still waiting
45
+ * on an older push finds the review that now covers it. */
46
+ export function movePushEvents(fromReviewId, toReviewId, toJobId) {
47
+ getAppDb()
48
+ .prepare(`UPDATE push_events SET review_id = ?, job_id = ? WHERE review_id = ?`)
49
+ .run(toReviewId, toJobId, fromReviewId);
50
+ }
51
+ export function listPushEventsForReview(reviewId) {
52
+ return getAppDb()
53
+ .prepare(`SELECT * FROM push_events WHERE review_id = ? ORDER BY created_at`)
54
+ .all(reviewId);
55
+ }
56
+ export function getOrCreatePushSubject(repo, branch) {
57
+ const db = getAppDb();
58
+ const existing = db
59
+ .prepare(`SELECT * FROM subjects WHERE kind = 'push' AND repo = ? AND branch = ?`)
60
+ .get(repo, branch);
61
+ if (existing)
62
+ return existing;
63
+ const row = {
64
+ id: crypto.randomUUID(),
65
+ kind: "push",
66
+ repo,
67
+ pr_number: null,
68
+ branch,
69
+ token_id: null,
70
+ created_at: nowIso(),
71
+ updated_at: nowIso(),
72
+ };
73
+ db.prepare(`INSERT INTO subjects (id, kind, repo, pr_number, branch, token_id, created_at, updated_at)
74
+ VALUES (?, 'push', ?, NULL, ?, NULL, ?, ?)`).run(row.id, repo, branch, row.created_at, row.updated_at);
75
+ return row;
76
+ }
77
+ export function insertPushReview(row) {
78
+ getAppDb()
79
+ .prepare(`INSERT INTO reviews
80
+ (id, kind, subject_id, repo, pr_number, branch, token_id, token_name,
81
+ job_id, head_sha, base_sha, scope, model, status, created_at, round,
82
+ "trigger", cost_status, cost_note, billed_to)
83
+ VALUES (?, 'push', ?, ?, NULL, ?, NULL, NULL, ?, ?, ?, 'push', ?, 'queued', ?, 1,
84
+ 'push', 'unknown', 'not_recorded', 'server')`)
85
+ .run(row.id, row.subjectId, row.repo, row.branch, row.jobId, row.afterSha, row.beforeSha, row.model, nowIso());
86
+ }
87
+ export function setPushReviewRange(reviewId, beforeSha) {
88
+ getAppDb()
89
+ .prepare(`UPDATE reviews SET base_sha = ? WHERE id = ?`)
90
+ .run(beforeSha, reviewId);
91
+ }
92
+ export function listPushReviewsForRepo(repo, limit = 50) {
93
+ return getAppDb()
94
+ .prepare(`SELECT * FROM reviews WHERE repo = ? AND kind = 'push'
95
+ ORDER BY created_at DESC LIMIT ?`)
96
+ .all(repo, limit);
97
+ }
98
+ export function latestPushReview(repo) {
99
+ return getAppDb()
100
+ .prepare(`SELECT * FROM reviews WHERE repo = ? AND kind = 'push'
101
+ ORDER BY created_at DESC LIMIT 1`)
102
+ .get(repo);
103
+ }
104
+ export function savePushInput(jobId, revisionJson) {
105
+ getAppDb()
106
+ .prepare(`INSERT OR REPLACE INTO push_inputs (job_id, revision_json, created_at)
107
+ VALUES (?, ?, ?)`)
108
+ .run(jobId, revisionJson, nowIso());
109
+ }
110
+ export function getPushInput(jobId) {
111
+ return getAppDb()
112
+ .prepare(`SELECT revision_json FROM push_inputs WHERE job_id = ?`)
113
+ .get(jobId)?.revision_json;
114
+ }
115
+ export function deletePushInput(jobId) {
116
+ getAppDb().prepare(`DELETE FROM push_inputs WHERE job_id = ?`).run(jobId);
117
+ }
118
+ export function savePushResult(reviewId, result) {
119
+ getAppDb()
120
+ .prepare(`INSERT OR REPLACE INTO push_results (review_id, result_json, created_at)
121
+ VALUES (?, ?, ?)`)
122
+ .run(reviewId, JSON.stringify(result), nowIso());
123
+ }
124
+ export function getPushResult(reviewId) {
125
+ const raw = getAppDb()
126
+ .prepare(`SELECT result_json FROM push_results WHERE review_id = ?`)
127
+ .get(reviewId)?.result_json;
128
+ if (!raw)
129
+ return undefined;
130
+ try {
131
+ return JSON.parse(raw);
132
+ }
133
+ catch {
134
+ return undefined;
135
+ }
136
+ }
137
+ export function insertWatchIssue(row) {
138
+ const id = crypto.randomUUID();
139
+ const now = nowIso();
140
+ getAppDb()
141
+ .prepare(`INSERT INTO watch_issues
142
+ (id, repo, issue_number, severity, title, body_md, path, line_from,
143
+ line_to, anchor_text, state, closed_check, opened_review_id,
144
+ last_review_id, last_check, last_check_at, created_at, updated_at)
145
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'open', NULL, ?, ?, NULL, NULL, ?, ?)`)
146
+ .run(id, row.repo, row.issueNumber, row.severity, row.title, row.bodyMd, row.path, row.lineFrom, row.lineTo, row.anchorText, row.reviewId, row.reviewId, now, now);
147
+ return getWatchIssue(row.repo, row.issueNumber);
148
+ }
149
+ export function getWatchIssue(repo, issueNumber) {
150
+ return getAppDb()
151
+ .prepare(`SELECT * FROM watch_issues WHERE repo = ? AND issue_number = ?`)
152
+ .get(repo, issueNumber);
153
+ }
154
+ export function listWatchIssues(repo) {
155
+ return getAppDb()
156
+ .prepare(`SELECT * FROM watch_issues WHERE repo = ? ORDER BY issue_number`)
157
+ .all(repo);
158
+ }
159
+ export function updateWatchIssue(id, patch) {
160
+ const fields = Object.keys(patch);
161
+ if (fields.length === 0)
162
+ return;
163
+ const set = [...fields.map((field) => `${field} = ?`), "updated_at = ?"].join(", ");
164
+ getAppDb()
165
+ .prepare(`UPDATE watch_issues SET ${set} WHERE id = ?`)
166
+ .run(...fields.map((field) => (patch[field] ?? null)), nowIso(), id);
167
+ }
168
+ export function insertWatchNote(row) {
169
+ const result = getAppDb()
170
+ .prepare(`INSERT OR IGNORE INTO watch_notes
171
+ (id, repo, issue_number, comment_id, author, kind, body, note,
172
+ created_at, applied_at)
173
+ VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, NULL)`)
174
+ .run(crypto.randomUUID(), row.repo, row.issueNumber, row.commentId, row.author, row.kind, row.body, nowIso());
175
+ return Number(result.changes ?? 0) > 0;
176
+ }
177
+ export function listWatchNotes(repo) {
178
+ return getAppDb()
179
+ .prepare(`SELECT * FROM watch_notes WHERE repo = ? ORDER BY created_at`)
180
+ .all(repo);
181
+ }
182
+ export function markWatchNoteApplied(id, note) {
183
+ getAppDb()
184
+ .prepare(`UPDATE watch_notes SET note = ?, applied_at = ? WHERE id = ?`)
185
+ .run(note, nowIso(), id);
186
+ }
@@ -78,6 +78,8 @@ export type GitHubClient = {
78
78
  /** POST JSON. Optional so collect-test fakes stay GET-only. Review
79
79
  * posting requires it. */
80
80
  write?<T>(endpoint: string, body: unknown): Promise<T>;
81
+ /** PATCH JSON, for closing an issue. Only the App client has it. */
82
+ patch?<T>(endpoint: string, body: unknown): Promise<T>;
81
83
  /** GitHub Checks API operations. Optional so read-only test clients and
82
84
  * older integrations can continue to review without check runs. */
83
85
  createCheckRun?<T>(endpoint: string, body: unknown): Promise<T>;