@jive-sh/skill-sync 0.11.0-latest-darwin-x64 → 0.11.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 (236) hide show
  1. package/README.md +346 -0
  2. package/bin/package.json +1 -0
  3. package/bin/skill-sync +34 -0
  4. package/bin/skill-sync-daemon +34 -0
  5. package/dist/daemons/skill-sync-daemon.js +664 -0
  6. package/dist/daemons/skill-sync-daemon.js.map +1 -0
  7. package/dist/entrypoints/skill-sync.js +7 -0
  8. package/dist/entrypoints/skill-sync.js.map +1 -0
  9. package/dist/index.js +10 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/internal/agents/agent-tool.js +102 -0
  12. package/dist/internal/agents/agent-tool.js.map +1 -0
  13. package/dist/internal/agents/claude.js +424 -0
  14. package/dist/internal/agents/claude.js.map +1 -0
  15. package/dist/internal/agents/codex.js +270 -0
  16. package/dist/internal/agents/codex.js.map +1 -0
  17. package/dist/internal/agents/command.js +219 -0
  18. package/dist/internal/agents/command.js.map +1 -0
  19. package/dist/internal/agents/grok.js +170 -0
  20. package/dist/internal/agents/grok.js.map +1 -0
  21. package/dist/internal/agents/index.js +70 -0
  22. package/dist/internal/agents/index.js.map +1 -0
  23. package/dist/internal/cli.js +218 -0
  24. package/dist/internal/cli.js.map +1 -0
  25. package/dist/internal/comment-watch/held.js +14 -0
  26. package/dist/internal/comment-watch/held.js.map +1 -0
  27. package/dist/internal/comment-watch/key.js +4 -0
  28. package/dist/internal/comment-watch/key.js.map +1 -0
  29. package/dist/internal/comment-watch/message.js +37 -0
  30. package/dist/internal/comment-watch/message.js.map +1 -0
  31. package/dist/internal/comment-watch/paths.js +16 -0
  32. package/dist/internal/comment-watch/paths.js.map +1 -0
  33. package/dist/internal/comment-watch/platform.js +66 -0
  34. package/dist/internal/comment-watch/platform.js.map +1 -0
  35. package/dist/internal/comment-watch/protocol.js +124 -0
  36. package/dist/internal/comment-watch/protocol.js.map +1 -0
  37. package/dist/internal/comment-watch/recent.js +27 -0
  38. package/dist/internal/comment-watch/recent.js.map +1 -0
  39. package/dist/internal/comment-watch/replies.js +28 -0
  40. package/dist/internal/comment-watch/replies.js.map +1 -0
  41. package/dist/internal/comment-watch/service.js +174 -0
  42. package/dist/internal/comment-watch/service.js.map +1 -0
  43. package/dist/internal/comment-watch/settings.js +66 -0
  44. package/dist/internal/comment-watch/settings.js.map +1 -0
  45. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js +85 -0
  46. package/dist/internal/comment-watch/source/github-pull-requests/conversations.js.map +1 -0
  47. package/dist/internal/comment-watch/source/github-pull-requests/impl.js +276 -0
  48. package/dist/internal/comment-watch/source/github-pull-requests/impl.js.map +1 -0
  49. package/dist/internal/comment-watch/source/github-pull-requests/queries.js +97 -0
  50. package/dist/internal/comment-watch/source/github-pull-requests/queries.js.map +1 -0
  51. package/dist/internal/comment-watch/source/google-doc/doc.js +57 -0
  52. package/dist/internal/comment-watch/source/google-doc/doc.js.map +1 -0
  53. package/dist/internal/comment-watch/source/google-doc/impl.js +190 -0
  54. package/dist/internal/comment-watch/source/google-doc/impl.js.map +1 -0
  55. package/dist/internal/comment-watch/source/http-api.js +74 -0
  56. package/dist/internal/comment-watch/source/http-api.js.map +1 -0
  57. package/dist/internal/comment-watch/source/interface.js +48 -0
  58. package/dist/internal/comment-watch/source/interface.js.map +1 -0
  59. package/dist/internal/comment-watch/source/sign-in.js +40 -0
  60. package/dist/internal/comment-watch/source/sign-in.js.map +1 -0
  61. package/dist/internal/comment-watch/source/sources.js +15 -0
  62. package/dist/internal/comment-watch/source/sources.js.map +1 -0
  63. package/dist/internal/comment-watch/store/impl.js +242 -0
  64. package/dist/internal/comment-watch/store/impl.js.map +1 -0
  65. package/dist/internal/comment-watch/store/interface.js +10 -0
  66. package/dist/internal/comment-watch/store/interface.js.map +1 -0
  67. package/dist/internal/comment-watch/t3.js +49 -0
  68. package/dist/internal/comment-watch/t3.js.map +1 -0
  69. package/dist/internal/comment-watch/watching.js +65 -0
  70. package/dist/internal/comment-watch/watching.js.map +1 -0
  71. package/dist/internal/comment-watch/workflow/comment-watch.js +19 -0
  72. package/dist/internal/comment-watch/workflow/comment-watch.js.map +1 -0
  73. package/dist/internal/comment-watch/workflow/deliver.js +104 -0
  74. package/dist/internal/comment-watch/workflow/deliver.js.map +1 -0
  75. package/dist/internal/comment-watch/workflow/find.js +67 -0
  76. package/dist/internal/comment-watch/workflow/find.js.map +1 -0
  77. package/dist/internal/comment-watch/workflow/post-once.js +66 -0
  78. package/dist/internal/comment-watch/workflow/post-once.js.map +1 -0
  79. package/dist/internal/comment-watch/workflow/post.js +40 -0
  80. package/dist/internal/comment-watch/workflow/post.js.map +1 -0
  81. package/dist/internal/config.js +131 -0
  82. package/dist/internal/config.js.map +1 -0
  83. package/dist/internal/control.js +113 -0
  84. package/dist/internal/control.js.map +1 -0
  85. package/dist/internal/daemon-control/impl.js +80 -0
  86. package/dist/internal/daemon-control/impl.js.map +1 -0
  87. package/dist/internal/daemon-control/interface.js +4 -0
  88. package/dist/internal/daemon-control/interface.js.map +1 -0
  89. package/dist/internal/folders.js +47 -0
  90. package/dist/internal/folders.js.map +1 -0
  91. package/dist/internal/local-skills.js +43 -0
  92. package/dist/internal/local-skills.js.map +1 -0
  93. package/dist/internal/path.js +36 -0
  94. package/dist/internal/path.js.map +1 -0
  95. package/dist/internal/server.js +80 -0
  96. package/dist/internal/server.js.map +1 -0
  97. package/dist/internal/skill-check.js +83 -0
  98. package/dist/internal/skill-check.js.map +1 -0
  99. package/dist/internal/skill-refinement/evals/cases.js +143 -0
  100. package/dist/internal/skill-refinement/evals/cases.js.map +1 -0
  101. package/dist/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  102. package/dist/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  103. package/dist/internal/skill-refinement/feedback/import-legacy.js +13 -0
  104. package/dist/internal/skill-refinement/feedback/import-legacy.js.map +1 -0
  105. package/dist/internal/skill-refinement/feedback/intake.js +52 -0
  106. package/dist/internal/skill-refinement/feedback/intake.js.map +1 -0
  107. package/dist/internal/skill-refinement/feedback/managed-intake.js +19 -0
  108. package/dist/internal/skill-refinement/feedback/managed-intake.js.map +1 -0
  109. package/dist/internal/skill-refinement/feedback/outbox.js +44 -0
  110. package/dist/internal/skill-refinement/feedback/outbox.js.map +1 -0
  111. package/dist/internal/skill-refinement/jev/impl.js +63 -0
  112. package/dist/internal/skill-refinement/jev/impl.js.map +1 -0
  113. package/dist/internal/skill-refinement/jev/interface.js +6 -0
  114. package/dist/internal/skill-refinement/jev/interface.js.map +1 -0
  115. package/dist/internal/skill-refinement/managed-daemon.js +30 -0
  116. package/dist/internal/skill-refinement/managed-daemon.js.map +1 -0
  117. package/dist/internal/skill-refinement/managed-worker-credentials.js +60 -0
  118. package/dist/internal/skill-refinement/managed-worker-credentials.js.map +1 -0
  119. package/dist/internal/skill-refinement/managed-worker-files.js +25 -0
  120. package/dist/internal/skill-refinement/managed-worker-files.js.map +1 -0
  121. package/dist/internal/skill-refinement/managed-worker-loop.js +36 -0
  122. package/dist/internal/skill-refinement/managed-worker-loop.js.map +1 -0
  123. package/dist/internal/skill-refinement/organization-site.js +13 -0
  124. package/dist/internal/skill-refinement/organization-site.js.map +1 -0
  125. package/dist/internal/skill-refinement/paths.js +62 -0
  126. package/dist/internal/skill-refinement/paths.js.map +1 -0
  127. package/dist/internal/skill-refinement/platform.js +67 -0
  128. package/dist/internal/skill-refinement/platform.js.map +1 -0
  129. package/dist/internal/skill-refinement/service.js +365 -0
  130. package/dist/internal/skill-refinement/service.js.map +1 -0
  131. package/dist/internal/skill-refinement/skills/skill-text.js +219 -0
  132. package/dist/internal/skill-refinement/skills/skill-text.js.map +1 -0
  133. package/dist/internal/skill-refinement/workflow/retry.js +44 -0
  134. package/dist/internal/skill-refinement/workflow/retry.js.map +1 -0
  135. package/dist/internal/skill-refinement/workflow/skill-refinement.js +690 -0
  136. package/dist/internal/skill-refinement/workflow/skill-refinement.js.map +1 -0
  137. package/dist/internal/skill-refinement/writer/impl.js +2 -0
  138. package/dist/internal/skill-refinement/writer/impl.js.map +1 -0
  139. package/dist/internal/skill-refinement/writer/interface.js +2 -0
  140. package/dist/internal/skill-refinement/writer/interface.js.map +1 -0
  141. package/dist/internal/sync.js +182 -0
  142. package/dist/internal/sync.js.map +1 -0
  143. package/dist/internal/wire.js +31 -0
  144. package/dist/internal/wire.js.map +1 -0
  145. package/dist/internal/writer/claude.js +84 -0
  146. package/dist/internal/writer/claude.js.map +1 -0
  147. package/dist/internal/writer/codex.js +102 -0
  148. package/dist/internal/writer/codex.js.map +1 -0
  149. package/dist/internal/writer/interface.js +6 -0
  150. package/dist/internal/writer/interface.js.map +1 -0
  151. package/dist/internal/writer/live.js +13 -0
  152. package/dist/internal/writer/live.js.map +1 -0
  153. package/dist/internal/writer/reset.js +38 -0
  154. package/dist/internal/writer/reset.js.map +1 -0
  155. package/dist/internal/writer/selection.js +79 -0
  156. package/dist/internal/writer/selection.js.map +1 -0
  157. package/package.json +45 -11
  158. package/postinstall.cjs +663 -0
  159. package/src/daemons/skill-sync-daemon.ts +677 -0
  160. package/src/entrypoints/skill-sync.ts +12 -0
  161. package/src/index.ts +15 -0
  162. package/src/internal/agents/agent-tool.ts +149 -0
  163. package/src/internal/agents/claude.ts +442 -0
  164. package/src/internal/agents/codex.ts +288 -0
  165. package/src/internal/agents/command.ts +257 -0
  166. package/src/internal/agents/grok.ts +174 -0
  167. package/src/internal/agents/index.ts +74 -0
  168. package/src/internal/cli.ts +249 -0
  169. package/src/internal/comment-watch/held.ts +20 -0
  170. package/src/internal/comment-watch/key.ts +5 -0
  171. package/src/internal/comment-watch/message.ts +39 -0
  172. package/src/internal/comment-watch/paths.ts +17 -0
  173. package/src/internal/comment-watch/platform.ts +69 -0
  174. package/src/internal/comment-watch/protocol.ts +140 -0
  175. package/src/internal/comment-watch/recent.ts +26 -0
  176. package/src/internal/comment-watch/replies.ts +28 -0
  177. package/src/internal/comment-watch/service.ts +198 -0
  178. package/src/internal/comment-watch/settings.ts +82 -0
  179. package/src/internal/comment-watch/source/github-pull-requests/conversations.ts +111 -0
  180. package/src/internal/comment-watch/source/github-pull-requests/impl.ts +291 -0
  181. package/src/internal/comment-watch/source/github-pull-requests/queries.ts +113 -0
  182. package/src/internal/comment-watch/source/google-doc/doc.ts +76 -0
  183. package/src/internal/comment-watch/source/google-doc/impl.ts +198 -0
  184. package/src/internal/comment-watch/source/http-api.ts +93 -0
  185. package/src/internal/comment-watch/source/interface.ts +116 -0
  186. package/src/internal/comment-watch/source/sign-in.ts +45 -0
  187. package/src/internal/comment-watch/source/sources.ts +20 -0
  188. package/src/internal/comment-watch/store/impl.ts +268 -0
  189. package/src/internal/comment-watch/store/interface.ts +83 -0
  190. package/src/internal/comment-watch/t3.ts +68 -0
  191. package/src/internal/comment-watch/watching.ts +122 -0
  192. package/src/internal/comment-watch/workflow/comment-watch.ts +34 -0
  193. package/src/internal/comment-watch/workflow/deliver.ts +115 -0
  194. package/src/internal/comment-watch/workflow/find.ts +78 -0
  195. package/src/internal/comment-watch/workflow/post-once.ts +72 -0
  196. package/src/internal/comment-watch/workflow/post.ts +56 -0
  197. package/src/internal/config.ts +172 -0
  198. package/src/internal/control.ts +165 -0
  199. package/src/internal/daemon-control/impl.ts +94 -0
  200. package/src/internal/daemon-control/interface.ts +46 -0
  201. package/src/internal/folders.ts +50 -0
  202. package/src/internal/local-skills.ts +58 -0
  203. package/src/internal/path.ts +32 -0
  204. package/src/internal/server.ts +76 -0
  205. package/src/internal/skill-check.ts +97 -0
  206. package/src/internal/skill-refinement/evals/cases.ts +167 -0
  207. package/src/internal/skill-refinement/evals/opus-action-judge-original.json +350 -0
  208. package/src/internal/skill-refinement/evals/opus-judge-original.json +165 -0
  209. package/src/internal/skill-refinement/feedback/import-legacy.ts +16 -0
  210. package/src/internal/skill-refinement/feedback/intake.ts +66 -0
  211. package/src/internal/skill-refinement/feedback/managed-intake.ts +19 -0
  212. package/src/internal/skill-refinement/feedback/outbox.ts +50 -0
  213. package/src/internal/skill-refinement/jev/impl.ts +76 -0
  214. package/src/internal/skill-refinement/jev/interface.ts +56 -0
  215. package/src/internal/skill-refinement/managed-daemon.ts +38 -0
  216. package/src/internal/skill-refinement/managed-worker-credentials.ts +59 -0
  217. package/src/internal/skill-refinement/managed-worker-files.ts +24 -0
  218. package/src/internal/skill-refinement/managed-worker-loop.ts +46 -0
  219. package/src/internal/skill-refinement/organization-site.ts +15 -0
  220. package/src/internal/skill-refinement/paths.ts +87 -0
  221. package/src/internal/skill-refinement/platform.ts +71 -0
  222. package/src/internal/skill-refinement/service.ts +418 -0
  223. package/src/internal/skill-refinement/skills/skill-text.ts +292 -0
  224. package/src/internal/skill-refinement/workflow/retry.ts +61 -0
  225. package/src/internal/skill-refinement/workflow/skill-refinement.ts +777 -0
  226. package/src/internal/skill-refinement/writer/impl.ts +1 -0
  227. package/src/internal/skill-refinement/writer/interface.ts +1 -0
  228. package/src/internal/sync.ts +216 -0
  229. package/src/internal/wire.ts +439 -0
  230. package/src/internal/writer/claude.ts +98 -0
  231. package/src/internal/writer/codex.ts +93 -0
  232. package/src/internal/writer/interface.ts +48 -0
  233. package/src/internal/writer/live.ts +19 -0
  234. package/src/internal/writer/reset.ts +34 -0
  235. package/src/internal/writer/selection.ts +84 -0
  236. package/multi-call-binary +0 -4
@@ -0,0 +1,291 @@
1
+ /**
2
+ * The watched authors' open pull requests in the watched repositories, as one source: one cheap poll covers them all
3
+ * (`queries.ts`). What they say is worked out from GitHub on every listing (`conversations.ts`).
4
+ */
5
+ import { Effect, Option, Result, Schema } from 'effect';
6
+ import type { HttpClient } from 'effect/http';
7
+ import type { RepositoryAuthor } from '../../settings';
8
+ import type { NamedPlace } from '../../watching';
9
+ import { HttpApi, type Answer } from '../http-api';
10
+ import { Refused, ServiceUnavailable, type ICommentSource, type Listing, type Shown, type SourceEvent, type SourceFailure, type ThreadPost } from '../interface';
11
+ import type { ISignIn } from '../sign-in';
12
+ import { readConversations, updated, type Conversations, type PullRef } from './conversations';
13
+ import * as q from './queries';
14
+
15
+ const ORIGIN = 'https://api.github.com';
16
+ const SERVICE = 'GitHub';
17
+ const PER_PAGE = 100;
18
+ /** How long after a pull request's newest change a read of it is sure to hold every one of that second. */
19
+ const SETTLED_AFTER_MS = 5_000;
20
+ const UNKNOWN_SHAPE = `${SERVICE} answered in a way this version doesn't know`;
21
+ const NOT_THERE = "not there, or the signed-in account can't see it";
22
+
23
+ const User = Schema.NullOr(Schema.Struct({ login: Schema.String }));
24
+ /** A comment as REST gives it: what Post reads and makes, which costs no GraphQL points. */
25
+ const Made = Schema.Struct({ id: Schema.Finite, html_url: Schema.String, user: User, body: Schema.optionalKey(Schema.NullOr(Schema.String)) });
26
+ const Line = Schema.Struct({ ...Made.fields, in_reply_to_id: Schema.optionalKey(Schema.NullOr(Schema.Finite)) });
27
+
28
+ const GraphQL = Schema.Struct({
29
+ data: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
30
+ errors: Schema.optionalKey(Schema.Array(Schema.Struct({ message: Schema.String, type: Schema.optionalKey(Schema.String), path: Schema.optionalKey(Schema.NullOr(Schema.Array(Schema.Union([Schema.String, Schema.Finite])))) }))),
31
+ });
32
+
33
+ const Cursor = Schema.fromJsonString(Schema.Struct({
34
+ /** When each author was first watched in each repository, by GitHub's clock: what was written earlier was there before. */
35
+ since: Schema.Record(Schema.String, Schema.String),
36
+ /** The pull requests open at the last listing: one no longer open is read a last time, for what was left before it closed. */
37
+ open: Schema.Record(Schema.String, Schema.String),
38
+ }));
39
+ const Ref = Schema.fromJsonString(Schema.Struct({ repository: Schema.String, pull: Schema.Finite, thread: Schema.NullOr(Schema.String) }));
40
+
41
+ const pairKey = (p: RepositoryAuthor) => `${p.repository} ${p.author}`.toLowerCase();
42
+ const distinct = (names: ReadonlyArray<string>) => [...new Map(names.map((n) => [n.toLowerCase(), n])).values()];
43
+ const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase();
44
+
45
+ /** The next page's URL, as GitHub gives it: never built here. Pure. */
46
+ export const nextPage = (link: string | undefined): string | null => /<([^>]+)>;\s*rel="next"/.exec(link ?? '')?.[1] ?? null;
47
+
48
+ interface Spent { cost: number; remaining: number | null }
49
+ interface Asked { readonly data: Readonly<Record<string, unknown>>; readonly failed: ReadonlyMap<string, string>; readonly date: string | undefined }
50
+ interface Read { readonly updatedAt: string; readonly since: string; readonly pair: string; readonly pull: q.PullRequest }
51
+
52
+ export class GitHubPullRequestsSource implements ICommentSource {
53
+ readonly id = 'github';
54
+ readonly settings: ReadonlyArray<NamedPlace>;
55
+ readonly maxPostBytes = Option.none<number>();
56
+ private readonly api: HttpApi;
57
+ private readonly repositories: ReadonlyArray<string>;
58
+ private readonly authors: ReadonlyArray<string>;
59
+ /** Each open pull request as it was last read in full, by node id. */
60
+ private readonly read = new Map<string, Read>();
61
+ private openPlans: ReadonlyArray<string> = [];
62
+ private eyes: Conversations['eyes'] = [];
63
+
64
+ constructor(private readonly set: { readonly pairs: ReadonlyArray<RepositoryAuthor>; readonly tag: string }, deps: { readonly client: HttpClient.HttpClient; readonly signIn: ISignIn }) {
65
+ this.repositories = distinct(set.pairs.map((p) => p.repository));
66
+ this.authors = distinct(set.pairs.map((p) => p.author));
67
+ this.settings = this.repositories.map((r) => this.place({ repository: r, name: r, link: `https://github.com/${r}`, missing: null, entry: (a) => ({ id: a.toLowerCase(), name: a, link: `https://github.com/${a}`, missing: null, pulls: [] }) }));
68
+ this.api = new HttpApi({ service: SERVICE, origin: ORIGIN, headers: { accept: 'application/vnd.github+json', 'x-github-api-version': '2026-03-10', 'user-agent': 'comment-watch' }, ...deps });
69
+ }
70
+
71
+ *newSince(cursor: Option.Option<string>): Effect.fn.Return<Listing, SourceFailure> {
72
+ const was = Option.isNone(cursor) ? { since: {}, open: {} } : yield* Effect.orDie(Schema.decodeUnknownEffect(Cursor)(cursor.value));
73
+ const spent: Spent = { cost: 0, remaining: null };
74
+ const plans = this.openPlans;
75
+ const poll = q.pollQuery({ repositories: this.repositories, authors: this.authors, pairs: this.set.pairs, plans: plans.slice(0, q.PLANS_A_QUERY) });
76
+ const asked = yield* this.ask(poll.query, poll.variables, spent);
77
+ const me = (yield* this.part(q.Viewer, asked.data['viewer'])).login;
78
+ const now = yield* this.clock(asked.date);
79
+
80
+ // The reactions on open plans, first: a pull request read in full below has newer ones.
81
+ this.takePlans(yield* this.part(q.Plans, asked.data['plans']));
82
+ for (let at = q.PLANS_A_QUERY; at < plans.length; at += q.PLANS_A_QUERY) {
83
+ const more = yield* this.ask(q.PLANS, { plans: plans.slice(at, at + q.PLANS_A_QUERY) }, spent);
84
+ this.takePlans(yield* this.part(q.Plans, more.data['plans']));
85
+ }
86
+
87
+ const repositories = yield* Effect.forEach(this.repositories, (repository, i) =>
88
+ Effect.map(this.part(q.Repository, asked.data[`r${i}`] ?? null), (found) => ({ repository, found, missing: found === null ? asked.failed.get(`r${i}`) ?? NOT_THERE : null })));
89
+ const accounts = yield* Effect.forEach(this.authors, (author, i) => Effect.map(this.part(q.Account, asked.data[`u${i}`] ?? null), (found) => ({ author, found })));
90
+ const repositoryOf = (name: string) => repositories.find((r) => same(r.repository, name))!;
91
+ const accountOf = (name: string) => accounts.find((a) => same(a.author, name))!.found;
92
+
93
+ const open = new Map<string, q.OpenPull & { readonly pair: string }>();
94
+ const since: Record<string, string> = {};
95
+ /** Why a repository and author could not be read now, by pair: what is known of them stands. */
96
+ const unread = new Map<string, string>();
97
+ for (const [i, pair] of this.set.pairs.entries()) {
98
+ const key = pairKey(pair);
99
+ const found = asked.data[`s${i}`] ?? null;
100
+ const why = repositoryOf(pair.repository).missing ?? asked.failed.get(`s${i}`) ?? (found === null ? UNKNOWN_SHAPE : null);
101
+ if (why !== null) unread.set(key, why);
102
+ if (why !== null || accountOf(pair.author) === null) {
103
+ // One never read starts when it first is.
104
+ if (was.since[key] !== undefined) since[key] = was.since[key];
105
+ continue;
106
+ }
107
+ since[key] = was.since[key] ?? now;
108
+ for (let page = yield* this.part(q.Search, found); ;) {
109
+ for (const pull of page.nodes) open.set(pull.id, { ...pull, pair: key });
110
+ if (!page.pageInfo.hasNextPage || page.pageInfo.endCursor === null) break;
111
+ page = yield* this.part(q.Search, (yield* this.ask(q.MORE_OPEN, { q: q.searchOf(pair), after: page.pageInfo.endCursor }, spent)).data['found']);
112
+ }
113
+ }
114
+
115
+ for (const [id, read] of this.read) if (!open.has(id) && !unread.has(read.pair)) this.read.delete(id);
116
+ const changed = [...open.values()].filter((p) => this.read.get(p.id)?.updatedAt !== p.updatedAt);
117
+ // GitHub's times are to the second: one that changed as it was read may change again in that second, so it is read once more.
118
+ const settled = (p: q.OpenPull) => Date.parse(p.updatedAt) < Date.parse(now) - SETTLED_AFTER_MS;
119
+ for (const entry of yield* this.details(changed.map((p) => ({ id: p.id, updatedAt: settled(p) ? p.updatedAt : '', pair: p.pair, since: since[p.pair]! })), spent)) this.read.set(entry.pull.id, entry);
120
+ // One that has closed since is read a last time. Until this listing is taken the cursor still names it, so it is read again.
121
+ const closed = yield* this.details(Object.entries(was.open).flatMap(([id, pair]) => (open.has(id) || unread.has(pair) || since[pair] === undefined ? [] : [{ id, updatedAt: '', pair, since: since[pair] }])), spent);
122
+
123
+ const said = readConversations({ pulls: [...this.read.values()], me, tag: this.set.tag });
124
+ const saidLast = readConversations({ pulls: closed, me, tag: this.set.tag });
125
+ this.openPlans = said.openPlans;
126
+ this.eyes = [...said.eyes, ...saidLast.eyes];
127
+ const keptOpen = Object.entries(was.open).filter(([, pair]) => unread.has(pair));
128
+ return {
129
+ events: [...said.events, ...saidLast.events].map((event) => ({ event, before: false })),
130
+ cursor: JSON.stringify({ since, open: Object.fromEntries([...keptOpen, ...[...open.values()].map((p) => [p.id, p.pair] as const)]) } satisfies (typeof Cursor)['Type']),
131
+ watched: repositories.map(({ repository, found, missing }) => this.place({
132
+ repository, name: found?.nameWithOwner ?? repository, link: found?.url ?? `https://github.com/${repository}`, missing,
133
+ entry: (author) => {
134
+ const account = accountOf(author);
135
+ return {
136
+ id: author.toLowerCase(), name: account?.login ?? author, link: account?.url ?? `https://github.com/${author}`,
137
+ missing: account === null ? `${SERVICE} has no such account` : missing === null ? unread.get(pairKey({ repository, author })) ?? null : null,
138
+ pulls: [...open.values()].filter((p) => p.pair === pairKey({ repository, author })).map((p) => ({ title: p.title, number: p.number, link: p.url })),
139
+ };
140
+ },
141
+ })),
142
+ notes: [`${spent.cost} point${spent.cost === 1 ? '' : 's'}${spent.remaining === null ? '' : `, ${spent.remaining} left this hour`}; ${changed.length + closed.length} of ${open.size} pull requests read in full, ${plans.length} open plans checked`],
143
+ };
144
+ }
145
+
146
+ *showReceived({ isQueued, isAnswered }: Parameters<ICommentSource['showReceived']>[0]): Effect.fn.Return<Shown> {
147
+ // It shows from when it is queued until a reply to it is recorded; any other 👀 of this account's is left as it is.
148
+ const changes = this.eyes.flatMap((e) => {
149
+ if (e.shown) return isAnswered(e.key) ? [{ subject: e.subject, eyes: false }] : [];
150
+ return isQueued(e.key) && !isAnswered(e.key) ? [{ subject: e.subject, eyes: true }] : [];
151
+ });
152
+ const failed: string[] = [];
153
+ for (const { subject, eyes } of changes) {
154
+ const done = yield* Effect.result(Effect.gen(() => this.ask(eyes ? q.ADD_EYES : q.REMOVE_EYES, { id: subject }, { cost: 0, remaining: null })));
155
+ if (Result.isFailure(done)) {
156
+ failed.push(`👀 could not be ${eyes ? 'put on' : 'taken off'} a comment: ${done.failure.reason}`);
157
+ continue;
158
+ }
159
+ // A reaction doesn't change its pull request's `updatedAt`, so it is not read again for this.
160
+ for (const [pull, entry] of this.read) this.read.set(pull, { ...entry, pull: updated(entry.pull, subject, { eyes }) });
161
+ }
162
+ return { changed: changes.length - failed.length, failed };
163
+ }
164
+
165
+ *thread(event: Pick<SourceEvent, 'key' | 'ref'>): Effect.fn.Return<ReadonlyArray<ThreadPost>, SourceFailure> {
166
+ const ref = yield* this.refOf(event);
167
+ const me = (yield* this.api.get(`${ORIGIN}/user`, Schema.Struct({ login: Schema.String }))).body.login;
168
+ const post = (kind: 'line' | 'conversation') => (c: typeof Made.Type): ThreadPost => ({ post: `${kind}:${c.id}`, author: c.user?.login ?? 'a deleted account', text: c.body ?? '', url: c.html_url, mine: c.user !== null && same(c.user.login, me) });
169
+ if (ref.thread === null) return (yield* this.every(`${ORIGIN}/repos/${ref.repository}/issues/${ref.pull}/comments?per_page=${PER_PAGE}`, Made)).map(post('conversation'));
170
+ const lines = yield* this.every(`${ORIGIN}/repos/${ref.repository}/pulls/${ref.pull}/comments?per_page=${PER_PAGE}`, Line);
171
+ return lines.filter((c) => String(c.id) === ref.thread || String(c.in_reply_to_id) === ref.thread).map(post('line'));
172
+ }
173
+
174
+ *reply(event: Pick<SourceEvent, 'key' | 'ref'>, text: string): Effect.fn.Return<ThreadPost, SourceFailure> {
175
+ const ref = yield* this.refOf(event);
176
+ const url = ref.thread === null ? `${ORIGIN}/repos/${ref.repository}/issues/${ref.pull}/comments` : `${ORIGIN}/repos/${ref.repository}/pulls/${ref.pull}/comments/${ref.thread}/replies`;
177
+ const { body } = yield* this.api.send({ method: 'POST', url, body: { body: text } }, Made);
178
+ return { post: `${ref.thread === null ? 'conversation' : 'line'}:${body.id}`, author: body.user?.login ?? 'this account', text, url: body.html_url, mine: true };
179
+ }
180
+
181
+ *edit(event: Pick<SourceEvent, 'key' | 'ref'>, post: string, text: string): Effect.fn.Return<void, SourceFailure> {
182
+ const ref = yield* this.refOf(event);
183
+ const [kind, id] = post.split(':');
184
+ yield* this.api.send({ method: 'PATCH', url: `${ORIGIN}/repos/${ref.repository}/${kind === 'line' ? 'pulls' : 'issues'}/comments/${id}`, body: { body: text } }, Made);
185
+ }
186
+
187
+ /** Pull requests read in full, with every comment and review since each was first watched. One GitHub no longer has is left out. */
188
+ private *details(wanted: ReadonlyArray<Omit<Read, 'pull'> & { readonly id: string }>, spent: Spent): Effect.fn.Return<ReadonlyArray<Read>, SourceFailure> {
189
+ const read: Read[] = [];
190
+ for (let at = 0; at < wanted.length; at += q.DETAILS_A_QUERY) {
191
+ const batch = wanted.slice(at, at + q.DETAILS_A_QUERY);
192
+ const found = yield* this.part(q.Details, (yield* this.ask(q.DETAILS, { ids: batch.map((w) => w.id) }, spent)).data['found']);
193
+ for (const { id, ...w } of batch) {
194
+ const pull = found.find((p) => p?.id === id) ?? null;
195
+ if (pull !== null) read.push({ ...w, pull: yield* this.whole(pull, w.since, spent) });
196
+ }
197
+ }
198
+ return read;
199
+ }
200
+
201
+ /** A pull request with every comment and review since a time: its first read holds the newest of each. */
202
+ private *whole(pull: q.PullRequest, since: string, spent: Spent): Effect.fn.Return<q.PullRequest, SourceFailure> {
203
+ const before = (page: q.PullRequest['comments']['pageInfo'], oldest: string | null | undefined): string | null =>
204
+ page.hasPreviousPage && (oldest === null || oldest === undefined || Date.parse(oldest) >= Date.parse(since)) ? page.startCursor : null;
205
+ const comments = [...pull.comments.nodes];
206
+ for (let from = before(pull.comments.pageInfo, comments[0]?.createdAt); from !== null;) {
207
+ const more = yield* this.part(q.MoreComments, (yield* this.ask(q.MORE_COMMENTS, { id: pull.id, before: from }, spent)).data['found'] ?? null);
208
+ if (more === null) break;
209
+ comments.unshift(...more.comments.nodes);
210
+ from = before(more.comments.pageInfo, comments[0]?.createdAt);
211
+ }
212
+ const reviews = [...pull.reviews.nodes];
213
+ for (let from = before(pull.reviews.pageInfo, reviews[0]?.submittedAt); from !== null;) {
214
+ const more = yield* this.part(q.MoreReviews, (yield* this.ask(q.MORE_REVIEWS, { id: pull.id, before: from }, spent)).data['found'] ?? null);
215
+ if (more === null) break;
216
+ reviews.unshift(...more.reviews.nodes);
217
+ from = before(more.reviews.pageInfo, reviews[0]?.submittedAt);
218
+ }
219
+ const whole: q.Review[] = [];
220
+ for (const review of reviews) {
221
+ const lines = [...review.comments.nodes];
222
+ for (let page = review.comments.pageInfo; page.hasNextPage && page.endCursor !== null;) {
223
+ const more = yield* this.part(q.MoreReviewComments, (yield* this.ask(q.MORE_REVIEW_COMMENTS, { id: review.id, after: page.endCursor }, spent)).data['found'] ?? null);
224
+ if (more === null) break;
225
+ lines.push(...more.comments.nodes);
226
+ page = more.comments.pageInfo;
227
+ }
228
+ whole.push({ ...review, comments: { ...review.comments, nodes: lines } });
229
+ }
230
+ return { ...pull, comments: { ...pull.comments, nodes: comments }, reviews: { ...pull.reviews, nodes: whole } };
231
+ }
232
+
233
+ private takePlans(plans: typeof q.Plans.Type): void {
234
+ for (const plan of plans) {
235
+ if (plan?.id === undefined || plan.reactions === undefined) continue;
236
+ for (const [id, entry] of this.read) this.read.set(id, { ...entry, pull: updated(entry.pull, plan.id, { reactions: plan.reactions }) });
237
+ }
238
+ }
239
+
240
+ /** Asks GraphQL. GitHub answers a part it refuses with none of it and an error naming it, beside the parts it gives. */
241
+ private *ask(query: string, variables: object, spent: Spent): Effect.fn.Return<Asked, SourceFailure> {
242
+ const { body, headers } = yield* this.api.send({ method: 'POST', url: `${ORIGIN}/graphql`, body: { query, variables } }, GraphQL);
243
+ const errors = body.errors ?? [];
244
+ const why = errors.map((e) => e.message).join('; ');
245
+ // A limit reached is answered with 200 and an error.
246
+ if (errors.some((e) => e.type === 'RATE_LIMITED' || /rate limit/i.test(e.message)) || (errors.length > 0 && headers['x-ratelimit-remaining'] === '0')) {
247
+ return yield* Effect.fail(new ServiceUnavailable({ service: SERVICE, reason: why, plain: `${SERVICE}'s limit on requests is reached` }));
248
+ }
249
+ const isMutation = query.startsWith('mutation');
250
+ const named = errors.filter((e) => e.path !== undefined && e.path !== null && e.path.length > 0);
251
+ if (isMutation && errors.length > 0) return yield* Effect.fail(new Refused({ service: SERVICE, reason: why, status: null, plain: `${SERVICE} refused` }));
252
+ if (typeof body.data !== 'object' || body.data === null || named.length < errors.length) return yield* Effect.fail(new ServiceUnavailable({ service: SERVICE, reason: why === '' ? 'no data' : why, plain: UNKNOWN_SHAPE }));
253
+ const data = body.data as Readonly<Record<string, unknown>>;
254
+ if (!isMutation) {
255
+ const { rateLimit } = yield* this.part(q.Answered, data);
256
+ spent.cost += rateLimit.cost;
257
+ spent.remaining = rateLimit.remaining;
258
+ }
259
+ const plain = (type: string | undefined) => (type === 'NOT_FOUND' ? NOT_THERE : type === 'FORBIDDEN' ? "the signed-in account isn't allowed to" : `${SERVICE} refused`);
260
+ return { data, failed: new Map(named.map((e) => [String(e.path![0]), plain(e.type)])), date: headers['date'] };
261
+ }
262
+
263
+ private part<A>(schema: Schema.Codec<A, unknown>, value: unknown): Effect.Effect<A, SourceFailure> {
264
+ return Effect.mapError(Schema.decodeUnknownEffect(schema)(value), (e) => new ServiceUnavailable({ service: SERVICE, reason: `an answer of a shape this version does not know: ${e.message.slice(0, 300)}`, plain: UNKNOWN_SHAPE }));
265
+ }
266
+
267
+ /** GitHub's clock, never this machine's: the times compared with it are GitHub's. */
268
+ private *clock(date: string | undefined): Effect.fn.Return<string, SourceFailure> {
269
+ if (date === undefined || Number.isNaN(Date.parse(date))) return yield* Effect.fail(new ServiceUnavailable({ service: SERVICE, reason: 'its answer carries no date', plain: UNKNOWN_SHAPE }));
270
+ return new Date(Date.parse(date)).toISOString();
271
+ }
272
+
273
+ /** Every item of a REST listing, following GitHub's own link to each next page. */
274
+ private *every<A>(first: string, item: Schema.Codec<A, unknown>): Effect.fn.Return<ReadonlyArray<A>, SourceFailure> {
275
+ const all: A[] = [];
276
+ for (let url: string | null = first; url !== null;) {
277
+ const page: Answer<ReadonlyArray<A>> = yield* this.api.get(url, Schema.Array(item));
278
+ all.push(...page.body);
279
+ url = nextPage(page.headers['link']);
280
+ }
281
+ return all;
282
+ }
283
+
284
+ private place(p: { readonly repository: string; readonly name: string; readonly link: string; readonly missing: string | null; readonly entry: (author: string) => NamedPlace['entries'][number] }): NamedPlace {
285
+ return { id: p.repository.toLowerCase(), kind: 'github-pull-requests', name: p.name, link: p.link, missing: p.missing, entries: this.set.pairs.filter((x) => same(x.repository, p.repository)).map((x) => p.entry(x.author)) };
286
+ }
287
+
288
+ private *refOf(event: Pick<SourceEvent, 'ref'>): Effect.fn.Return<PullRef> {
289
+ return yield* Effect.orDie(Schema.decodeUnknownEffect(Ref)(event.ref));
290
+ }
291
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * WHAT IS ASKED OF GITHUB, AND WHAT IT COSTS. The account's 5,000 GraphQL points an hour are shared with every agent's `gh`,
3
+ * so each poll asks only which watched pull requests are open and when each was last updated, and the reactions on open
4
+ * plans: 1 point up to 100 searches and plans. A pull request's comments, about 16 points, are read only when its
5
+ * `updatedAt` changed. A reaction doesn't change it, which is why open plans are read on their own.
6
+ */
7
+ import { Schema } from 'effect';
8
+ import type { RepositoryAuthor } from '../../settings';
9
+
10
+ const Author = Schema.NullOr(Schema.Struct({ login: Schema.String }));
11
+ export const Reactions = Schema.Struct({ nodes: Schema.Array(Schema.Struct({ id: Schema.String, content: Schema.String, createdAt: Schema.String, user: Author })) });
12
+ /** Which reactions the signed-in account has left, which is how its own 👀 is known to be there. */
13
+ const ReactionGroups = Schema.Array(Schema.Struct({ content: Schema.String, viewerHasReacted: Schema.Boolean }));
14
+ const Before = Schema.Struct({ hasPreviousPage: Schema.Boolean, startCursor: Schema.NullOr(Schema.String) });
15
+ const After = Schema.Struct({ hasNextPage: Schema.Boolean, endCursor: Schema.NullOr(Schema.String) });
16
+
17
+ /** GraphQL's big integers come as text, and as numbers where they fit: the REST ids the reply and edit endpoints take. */
18
+ const RestId = Schema.Union([Schema.String, Schema.Finite]);
19
+
20
+ export const IssueComment = Schema.Struct({ id: Schema.String, fullDatabaseId: RestId, url: Schema.String, body: Schema.String, createdAt: Schema.String, author: Author, reactions: Reactions, reactionGroups: Schema.NullOr(ReactionGroups) });
21
+ export type IssueComment = typeof IssueComment.Type;
22
+ export const ReviewComment = Schema.Struct({
23
+ id: Schema.String, fullDatabaseId: RestId,
24
+ /** The review thread's first comment, for a reply in it: GitHub takes replies to that one alone. */
25
+ replyTo: Schema.NullOr(Schema.Struct({ fullDatabaseId: RestId })),
26
+ url: Schema.String, body: Schema.String, createdAt: Schema.String, path: Schema.String, line: Schema.NullOr(Schema.Finite), originalLine: Schema.NullOr(Schema.Finite),
27
+ author: Author, reactions: Reactions, reactionGroups: Schema.NullOr(ReactionGroups),
28
+ });
29
+ export type ReviewComment = typeof ReviewComment.Type;
30
+ export const Review = Schema.Struct({
31
+ id: Schema.String, url: Schema.String, /** None while it is still being written. */
32
+ body: Schema.String, submittedAt: Schema.NullOr(Schema.String), author: Author, reactionGroups: Schema.NullOr(ReactionGroups),
33
+ comments: Schema.Struct({ pageInfo: After, nodes: Schema.Array(ReviewComment) }),
34
+ });
35
+ export type Review = typeof Review.Type;
36
+ export const PullRequest = Schema.Struct({
37
+ id: Schema.String, url: Schema.String, number: Schema.Finite, title: Schema.String, author: Author, repository: Schema.Struct({ nameWithOwner: Schema.String }),
38
+ comments: Schema.Struct({ pageInfo: Before, nodes: Schema.Array(IssueComment) }),
39
+ reviews: Schema.Struct({ pageInfo: Before, nodes: Schema.Array(Review) }),
40
+ });
41
+ export type PullRequest = typeof PullRequest.Type;
42
+
43
+ const RateLimit = Schema.Struct({ cost: Schema.Finite, remaining: Schema.Finite });
44
+
45
+ const OpenPull = Schema.Struct({ id: Schema.String, url: Schema.String, number: Schema.Finite, title: Schema.String, updatedAt: Schema.String });
46
+ export type OpenPull = typeof OpenPull.Type;
47
+ export const Search = Schema.Struct({ pageInfo: After, nodes: Schema.Array(OpenPull) });
48
+
49
+ /** A query's answer: what it cost, and each alias's own part, decoded by whoever asked for it. */
50
+ export const Answered = Schema.StructWithRest(Schema.Struct({ rateLimit: RateLimit }), [Schema.Record(Schema.String, Schema.Unknown)]);
51
+ export const Viewer = Schema.Struct({ login: Schema.String });
52
+ export const Repository = Schema.NullOr(Schema.Struct({ nameWithOwner: Schema.String, url: Schema.String }));
53
+ export const Account = Schema.NullOr(Schema.Struct({ login: Schema.String, url: Schema.String }));
54
+ export const Plans = Schema.Array(Schema.NullOr(Schema.Struct({ id: Schema.optionalKey(Schema.String), reactions: Schema.optionalKey(Reactions) })));
55
+ export const Details = Schema.Array(Schema.NullOr(PullRequest));
56
+ export const MoreComments = Schema.NullOr(Schema.Struct({ comments: PullRequest.fields.comments }));
57
+ export const MoreReviews = Schema.NullOr(Schema.Struct({ reviews: PullRequest.fields.reviews }));
58
+ export const MoreReviewComments = Schema.NullOr(Schema.Struct({ comments: Review.fields.comments }));
59
+
60
+ const RATE_LIMIT = 'rateLimit { cost remaining }';
61
+ const REACTIONS = 'reactions(last: 10) { nodes { id content createdAt user { login } } }';
62
+ const GROUPS = 'reactionGroups { content viewerHasReacted }';
63
+ const COMMENT = `id fullDatabaseId url body createdAt author { login } ${REACTIONS} ${GROUPS}`;
64
+ const REVIEW_COMMENT = `id fullDatabaseId replyTo { fullDatabaseId } url body createdAt path line originalLine author { login } ${REACTIONS} ${GROUPS}`;
65
+ const REVIEW = `id url body submittedAt author { login } ${GROUPS} comments(first: 50) { pageInfo { hasNextPage endCursor } nodes { ${REVIEW_COMMENT} } }`;
66
+ const OPEN_PULL = '... on PullRequest { id url number title updatedAt }';
67
+
68
+ /** GitHub refuses a query that could give over 500,000 nodes: 25 pull requests of 30 reviews of 50 comments of 10 reactions stays under it. */
69
+ export const DETAILS_A_QUERY = 25;
70
+ /** Open plans, and searches, a poll asks for at once: more than 100 would cost it another point. */
71
+ export const PLANS_A_QUERY = 50;
72
+
73
+ /** One poll over every repository and author watched, as one query. Pure. */
74
+ export const pollQuery = (input: { readonly repositories: ReadonlyArray<string>; readonly authors: ReadonlyArray<string>; readonly pairs: ReadonlyArray<RepositoryAuthor>; readonly plans: ReadonlyArray<string> }) => {
75
+ const { repositories, authors, pairs, plans } = input;
76
+ const declared = [
77
+ ...repositories.flatMap((_, i) => [`$ro${i}: String!`, `$rn${i}: String!`]),
78
+ ...authors.map((_, i) => `$u${i}: String!`),
79
+ ...pairs.map((_, i) => `$q${i}: String!`),
80
+ '$plans: [ID!]!',
81
+ ];
82
+ return {
83
+ query: `query Poll(${declared.join(', ')}) {
84
+ ${RATE_LIMIT}
85
+ viewer { login }
86
+ ${repositories.map((_, i) => `r${i}: repository(owner: $ro${i}, name: $rn${i}) { nameWithOwner url }`).join('\n')}
87
+ ${authors.map((_, i) => `u${i}: user(login: $u${i}) { login url }`).join('\n')}
88
+ ${pairs.map((_, i) => `s${i}: search(query: $q${i}, type: ISSUE, first: 50) { pageInfo { hasNextPage endCursor } nodes { ${OPEN_PULL} } }`).join('\n')}
89
+ plans: nodes(ids: $plans) { ... on IssueComment { id ${REACTIONS} } ... on PullRequestReviewComment { id ${REACTIONS} } }
90
+ }`,
91
+ variables: {
92
+ ...Object.fromEntries(repositories.flatMap((r, i) => [[`ro${i}`, r.split('/')[0]!], [`rn${i}`, r.split('/')[1]!]])),
93
+ ...Object.fromEntries(authors.map((a, i) => [`u${i}`, a])),
94
+ ...Object.fromEntries(pairs.map((p, i) => [`q${i}`, searchOf(p)])),
95
+ plans,
96
+ },
97
+ };
98
+ };
99
+
100
+ export const searchOf = (p: RepositoryAuthor): string => `is:pr is:open archived:false repo:${p.repository} author:${p.author}`;
101
+
102
+ export const MORE_OPEN = `query MoreOpen($q: String!, $after: String!) { ${RATE_LIMIT} found: search(query: $q, type: ISSUE, first: 50, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${OPEN_PULL} } } }`;
103
+ export const PLANS = `query Plans($plans: [ID!]!) { ${RATE_LIMIT} plans: nodes(ids: $plans) { ... on IssueComment { id ${REACTIONS} } ... on PullRequestReviewComment { id ${REACTIONS} } } }`;
104
+ export const DETAILS = `query Details($ids: [ID!]!) { ${RATE_LIMIT} found: nodes(ids: $ids) { ... on PullRequest {
105
+ id url number title author { login } repository { nameWithOwner }
106
+ comments(last: 30) { pageInfo { hasPreviousPage startCursor } nodes { ${COMMENT} } }
107
+ reviews(last: 30) { pageInfo { hasPreviousPage startCursor } nodes { ${REVIEW} } }
108
+ } } }`;
109
+ export const MORE_COMMENTS = `query MoreComments($id: ID!, $before: String!) { ${RATE_LIMIT} found: node(id: $id) { ... on PullRequest { comments(last: 100, before: $before) { pageInfo { hasPreviousPage startCursor } nodes { ${COMMENT} } } } } }`;
110
+ export const MORE_REVIEWS = `query MoreReviews($id: ID!, $before: String!) { ${RATE_LIMIT} found: node(id: $id) { ... on PullRequest { reviews(last: 30, before: $before) { pageInfo { hasPreviousPage startCursor } nodes { ${REVIEW} } } } } }`;
111
+ export const MORE_REVIEW_COMMENTS = `query MoreReviewComments($id: ID!, $after: String!) { ${RATE_LIMIT} found: node(id: $id) { ... on PullRequestReview { comments(first: 100, after: $after) { pageInfo { hasNextPage endCursor } nodes { ${REVIEW_COMMENT} } } } } }`;
112
+ export const ADD_EYES = 'mutation AddEyes($id: ID!) { addReaction(input: { subjectId: $id, content: EYES }) { clientMutationId } }';
113
+ export const REMOVE_EYES = 'mutation RemoveEyes($id: ID!) { removeReaction(input: { subjectId: $id, content: EYES }) { clientMutationId } }';
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A GOOGLE DOC AS THE WATCH READS IT, from one `documents.get` with tabs and comments: which tab each comment is on, and the
3
+ * posts of each. Pure: the API is `impl.ts`'s.
4
+ *
5
+ * A comment's tab is in no field of the comment. Its thread names an `anchorId`, and each tab's `commentAnchors` is keyed by
6
+ * the anchors in that tab, so the tab holding the anchor is the comment's.
7
+ */
8
+ import { Schema } from 'effect';
9
+
10
+ const Post = Schema.Struct({
11
+ postId: Schema.String,
12
+ content: Schema.optionalKey(Schema.String),
13
+ deleted: Schema.optionalKey(Schema.Boolean),
14
+ author: Schema.optionalKey(Schema.Struct({ displayName: Schema.optionalKey(Schema.String), me: Schema.optionalKey(Schema.Boolean), anonymous: Schema.optionalKey(Schema.Boolean) })),
15
+ });
16
+ export type Post = typeof Post.Type;
17
+
18
+ const CommentThread = Schema.Struct({
19
+ commentId: Schema.String,
20
+ anchorId: Schema.optionalKey(Schema.String),
21
+ headPost: Post,
22
+ replies: Schema.optionalKey(Schema.Array(Post)),
23
+ plainTextQuote: Schema.optionalKey(Schema.String),
24
+ });
25
+ export type CommentThread = typeof CommentThread.Type;
26
+
27
+ /** Only which anchors a tab holds is read, by their keys. */
28
+ const Anchor = Schema.Struct({});
29
+
30
+ interface Tab {
31
+ readonly tabProperties: { readonly tabId: string; readonly title?: string };
32
+ readonly documentTab?: { readonly commentAnchors?: Readonly<Record<string, typeof Anchor.Type>> };
33
+ readonly childTabs?: ReadonlyArray<Tab>;
34
+ }
35
+ const Tab: Schema.Codec<Tab> = Schema.Struct({
36
+ tabProperties: Schema.Struct({ tabId: Schema.String, title: Schema.optionalKey(Schema.String) }),
37
+ documentTab: Schema.optionalKey(Schema.Struct({ commentAnchors: Schema.optionalKey(Schema.Record(Schema.String, Anchor)) })),
38
+ childTabs: Schema.optionalKey(Schema.Array(Schema.suspend((): Schema.Codec<Tab> => Tab))),
39
+ });
40
+
41
+ export const Doc = Schema.Struct({
42
+ title: Schema.optionalKey(Schema.String),
43
+ /** The mode the read was made in: without it, no comments looks like a Doc with none. */
44
+ commentsViewMode: Schema.optionalKey(Schema.String),
45
+ tabs: Schema.Array(Tab),
46
+ comments: Schema.optionalKey(Schema.Array(CommentThread)),
47
+ });
48
+ export type Doc = typeof Doc.Type;
49
+
50
+ /** Every tab, whatever it is nested under. Pure. */
51
+ const everyTab = (tabs: ReadonlyArray<Tab>): ReadonlyArray<Tab> => tabs.flatMap((t) => [t, ...everyTab(t.childTabs ?? [])]);
52
+
53
+ /** Each tab's path as a reader sees it: the titles of the tabs it is under, and its own. Pure. */
54
+ export const tabPaths = (doc: Doc): ReadonlyMap<string, string> => {
55
+ const paths = (tabs: ReadonlyArray<Tab>, above: ReadonlyArray<string>): ReadonlyArray<readonly [string, string]> => tabs.flatMap((t) => {
56
+ const path = [...above, t.tabProperties.title ?? 'Untitled'];
57
+ return [[t.tabProperties.tabId, path.join(' › ')] as const, ...paths(t.childTabs ?? [], path)];
58
+ });
59
+ return new Map(paths(doc.tabs, []));
60
+ };
61
+
62
+ export const tabIds = (doc: Doc): ReadonlyArray<string> => everyTab(doc.tabs).map((t) => t.tabProperties.tabId);
63
+
64
+ /** Each thread's tab: the one holding its anchor now, else the one it was last known on; none for a thread on no tab. Pure. */
65
+ export const threadTabs = (input: { readonly doc: Doc; readonly known: Readonly<Record<string, string>> }): ReadonlyMap<string, string> => {
66
+ const tabOfAnchor = new Map(everyTab(input.doc.tabs).flatMap((t) => Object.keys(t.documentTab?.commentAnchors ?? {}).map((anchor) => [anchor, t.tabProperties.tabId] as const)));
67
+ return new Map((input.doc.comments ?? []).flatMap((c) => {
68
+ const tab = (c.anchorId === undefined ? undefined : tabOfAnchor.get(c.anchorId)) ?? input.known[c.commentId];
69
+ return tab === undefined ? [] : [[c.commentId, tab] as const];
70
+ }));
71
+ };
72
+
73
+ /** A thread's posts that hold words, oldest first: a deleted post holds none, nor does a bare resolve or reopen. Pure. */
74
+ export const postsOf = (thread: CommentThread): ReadonlyArray<Post> =>
75
+ [thread.headPost, ...(thread.replies ?? [])].filter((p) => p.deleted !== true && (p.content ?? '').trim() !== '');
76
+