@andrioid/paseo-attention-span 0.6.0 → 0.6.1

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 (71) hide show
  1. package/OVERVIEW.md +3 -1
  2. package/client/attention-screen.tsx +61 -1174
  3. package/client/coverage-settings.tsx +5 -4
  4. package/client/data.ts +4 -2
  5. package/client/feedback.tsx +21 -25
  6. package/client/history.tsx +12 -50
  7. package/client/item-actions.ts +363 -0
  8. package/client/item-row.tsx +450 -0
  9. package/client/new-issue.tsx +244 -0
  10. package/client/next-up.tsx +22 -183
  11. package/client/pickers.tsx +237 -0
  12. package/client/session-menu.ts +3 -11
  13. package/client/sessions.ts +58 -57
  14. package/client/setup.tsx +2 -1
  15. package/client/sheet.tsx +92 -15
  16. package/client/ui.tsx +23 -14
  17. package/client/wrap-up.tsx +151 -85
  18. package/docs/architecture.md +22 -11
  19. package/docs/screenshots/desktop-dark-doing-acknowledge.png +0 -0
  20. package/docs/screenshots/desktop-dark-doing-clear.png +0 -0
  21. package/docs/screenshots/desktop-dark-doing-issue-sheet.png +0 -0
  22. package/docs/screenshots/desktop-dark-doing-reviewers.png +0 -0
  23. package/docs/screenshots/desktop-dark-doing-sheet.png +0 -0
  24. package/docs/screenshots/desktop-dark-doing-wrap-dirty.png +0 -0
  25. package/docs/screenshots/desktop-dark-doing-wrap-multi.png +0 -0
  26. package/docs/screenshots/desktop-dark-doing-wrap.png +0 -0
  27. package/docs/screenshots/desktop-dark-doing.png +0 -0
  28. package/docs/screenshots/desktop-dark-next-up-setup.png +0 -0
  29. package/docs/screenshots/desktop-dark-next-up.png +0 -0
  30. package/docs/screenshots/desktop-dark-settings.png +0 -0
  31. package/docs/screenshots/phone-dark-doing.png +0 -0
  32. package/docs/screenshots/phone-light-next-up-filtered.png +0 -0
  33. package/index.client.tsx +19 -0
  34. package/index.server.ts +43 -26
  35. package/package.json +2 -1
  36. package/requirements.yaml +8 -3
  37. package/server/actions.ts +2 -1
  38. package/server/archive.ts +146 -67
  39. package/server/archived.ts +12 -16
  40. package/server/changes.ts +34 -54
  41. package/server/classify.ts +142 -136
  42. package/server/feedback.ts +2 -6
  43. package/server/fetch.ts +262 -0
  44. package/server/fixture.ts +83 -14
  45. package/server/github-types.ts +3 -1
  46. package/server/markdown.ts +3 -1
  47. package/server/port.ts +46 -0
  48. package/server/queries.ts +33 -23
  49. package/server/service.ts +155 -272
  50. package/server/setup.ts +15 -14
  51. package/server/store.ts +94 -80
  52. package/server/update.ts +34 -13
  53. package/server/view.ts +16 -15
  54. package/shared/archive.ts +116 -13
  55. package/shared/attention.ts +50 -18
  56. package/shared/changes.ts +2 -1
  57. package/shared/config.ts +2 -6
  58. package/shared/drafting.ts +17 -0
  59. package/shared/feedback.ts +6 -5
  60. package/shared/format.ts +2 -1
  61. package/shared/history-report.ts +2 -1
  62. package/shared/item-sessions.ts +76 -0
  63. package/shared/item-view.ts +223 -0
  64. package/shared/linked-sessions.ts +59 -8
  65. package/shared/names.ts +17 -0
  66. package/shared/new-issue.ts +129 -0
  67. package/shared/next-up-filter.ts +137 -0
  68. package/shared/paging.ts +16 -0
  69. package/shared/rpc.ts +23 -10
  70. package/shared/setup.ts +3 -1
  71. package/shared/wrap-up.ts +20 -23
package/server/changes.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { isFinishedChange, isHandover, type OthersChange } from "../shared/changes";
2
- import type { Item } from "../shared/attention";
2
+ import { baseItem, type Item, type SectionId } from "../shared/attention";
3
3
  import type { AssignmentEvent, AssignmentSubject, ClosedIssue, EndedPullRequest, LiveResult, ReopenSubject } from "./github-types";
4
4
  import { prKey } from "./queries";
5
+ import { keySet, sameName } from "../shared/names";
5
6
 
6
7
  // Changed by others: what someone else did to my work, kept between refreshes so a note stays until Got it or an archive
7
8
  // acknowledges it, and so History can list work that left my hands [HIS-06, HIS-07, ATT-22]. Pure, so every rule is
@@ -38,13 +39,12 @@ export type Lookups = Map<string, AssignmentSubject | null>;
38
39
  // Reopen lookups: the PR as it is now, null when it's gone or hidden, missing when the lookup failed.
39
40
  export type ReopenLookups = Map<string, ReopenSubject | null>;
40
41
 
41
- const same = (a: string | null | undefined, b: string | null | undefined) => !!a && !!b && a.toLowerCase() === b.toLowerCase();
42
42
  const present = <T>(nodes: (T | null | undefined)[]) => nodes.filter((node): node is T => !!node && Object.keys(node).length > 0);
43
43
  const logins = (subject: { assignees: { nodes: { login: string }[] } }) => subject.assignees.nodes.map((node) => node.login);
44
44
  // Assigned to someone, and not to me: out of my hands [PRS-08]. A PR of mine with nobody assigned is still mine.
45
45
  const handedOver = (subject: { assignees: { nodes: { login: string }[] } }, me: string) => {
46
46
  const assignees = logins(subject);
47
- return assignees.length > 0 && !assignees.some((login) => same(login, me));
47
+ return assignees.length > 0 && !assignees.some((login) => sameName(login, me));
48
48
  };
49
49
  const signature = (subject: { assignees: { nodes: { login: string }[] } }) =>
50
50
  logins(subject)
@@ -88,72 +88,64 @@ const isAssignment = (node: AssignmentEvent | Record<string, never>): node is As
88
88
  // The new owner is the latest of the current assignees to be assigned. It left my hands with whichever came last of my
89
89
  // removal and the new owner's assignment, and whoever did that is named: "phil took over" when that's the new owner, else
90
90
  // "dave handed it to carol". So a PR I unassigned myself from is still mine until someone else takes it.
91
- export function handover(subject: AssignmentSubject, me: string): OthersChange | null {
91
+ function handover(subject: AssignmentSubject, me: string): OthersChange | null {
92
92
  const assignees = logins(subject);
93
- if (assignees.some((login) => same(login, me))) return null;
93
+ if (assignees.some((login) => sameName(login, me))) return null;
94
94
  if (subject.__typename === "Issue" && subject.state !== "OPEN") return null;
95
95
  const events = present(subject.timelineItems.nodes)
96
96
  .filter(isAssignment)
97
97
  .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
98
- const removal = events.findLast((event) => event.__typename === "UnassignedEvent" && same(event.assignee?.login, me));
99
- const given = events.findLast((event) => event.__typename === "AssignedEvent" && assignees.some((login) => same(login, event.assignee?.login)));
98
+ const removal = events.findLast((event) => event.__typename === "UnassignedEvent" && sameName(event.assignee?.login, me));
99
+ const given = events.findLast((event) => event.__typename === "AssignedEvent" && assignees.some((login) => sameName(login, event.assignee?.login)));
100
100
  const to = given?.assignee?.login ?? assignees[0];
101
101
  // A PR of mine with nobody on it is mine; an issue needs proof I was taken off it.
102
102
  if (subject.__typename === "PullRequest" ? !to : !removal) return null;
103
103
  const by = removal && given && to ? (given.createdAt > removal.createdAt ? given : removal) : (removal ?? given);
104
- if (!by || same(by.actor?.login, me)) return null;
104
+ if (!by || sameName(by.actor?.login, me)) return null;
105
105
  const actor = by.actor?.login;
106
- const kind = !to ? "unassigned" : same(actor, to) ? "took_over" : "handed";
106
+ const kind = !to ? "unassigned" : sameName(actor, to) ? "took_over" : "handed";
107
107
  return change(subject, subject.__typename === "PullRequest" ? "pr" : "issue", kind, by.createdAt, actor, to);
108
108
  }
109
109
 
110
110
  // A PR of mine someone else merged or closed unmerged [HIS-07]. Whether it left my hands before it ended is up to nextLedger,
111
111
  // which knows when that happened.
112
- export function ended(pr: EndedPullRequest, me: string): OthersChange | null {
113
- if (pr.merged) return same(pr.mergedBy?.login, me) || !pr.mergedAt ? null : change(pr, "pr", "merged", pr.mergedAt, pr.mergedBy?.login);
112
+ function ended(pr: EndedPullRequest, me: string): OthersChange | null {
113
+ if (pr.merged) return sameName(pr.mergedBy?.login, me) || !pr.mergedAt ? null : change(pr, "pr", "merged", pr.mergedAt, pr.mergedBy?.login);
114
114
  const closer = pr.timelineItems.nodes.at(-1)?.actor?.login;
115
- return same(closer, me) ? null : change(pr, "pr", "closed", pr.closedAt, closer);
115
+ return sameName(closer, me) ? null : change(pr, "pr", "closed", pr.closedAt, closer);
116
116
  }
117
117
 
118
- // My PRs I closed without merging, from the closed search: finished work whose sessions Wrap up puts away, though no note
119
- // and no week lists them [ATT-22].
118
+ // My PRs that ended lately, from the closed search, as finished work whose sessions Wrap up puts away [ATT-22]: those I
119
+ // closed without merging, which no note and no week lists, and merged ones, which stand in for History's entry until its
120
+ // next fetch has them [FRESH-03]. A merge by someone else says who.
120
121
  export function ownClosed(data: Pick<LiveResult, "ended">, me: string): Item[] {
121
122
  return present(data.ended.nodes)
122
- .filter((pr) => !pr.merged && same(pr.timelineItems.nodes.at(-1)?.actor?.login, me))
123
- .map((pr) => ({
124
- key: prKey(pr),
125
- kind: "pr" as const,
126
- section: "done" as const,
127
- draft: false,
128
- repo: pr.repository.nameWithOwner,
129
- number: pr.number,
130
- title: pr.title,
131
- url: pr.url,
132
- chips: [],
133
- actions: [],
134
- children: [],
135
- target: { kind: "pr" as const, repo: pr.repository.nameWithOwner, number: pr.number, title: pr.title, url: pr.url },
136
- othersActivityAt: pr.closedAt,
137
- closedAt: pr.closedAt,
138
- closedUnmerged: true as const,
139
- }));
123
+ .filter((pr) => pr.merged || sameName(pr.timelineItems.nodes.at(-1)?.actor?.login, me))
124
+ .map((pr) => {
125
+ const item = baseItem({ key: prKey(pr), section: "done", kind: "pr", repo: pr.repository.nameWithOwner, number: pr.number, title: pr.title, url: pr.url }, pr.closedAt);
126
+ // Its branch, so a session left on it finds its row in Wrap up [ATT-22].
127
+ const target = { ...item.target, ...(pr.headRefName ? { headRefName: pr.headRefName } : {}) };
128
+ if (!pr.merged) return { ...item, target, closedAt: pr.closedAt, closedUnmerged: true as const };
129
+ const by = pr.mergedBy?.login;
130
+ return { ...item, target, closedAt: pr.mergedAt ?? pr.closedAt, ...(by && !sameName(by, me) ? { mergedBy: by } : {}) };
131
+ });
140
132
  }
141
133
 
142
134
  // An issue assigned to me someone else closed, as completed or not planned [HIS-07]. My own closes are mine.
143
- export function closedByOther(issue: ClosedIssue, me: string): OthersChange | null {
135
+ function closedByOther(issue: ClosedIssue, me: string): OthersChange | null {
144
136
  const closer = issue.timelineItems.nodes.at(-1)?.actor?.login;
145
- if (same(closer, me)) return null;
137
+ if (sameName(closer, me)) return null;
146
138
  const reason = issue.stateReason === "NOT_PLANNED" ? "not_planned" : issue.stateReason === "COMPLETED" ? "completed" : undefined;
147
139
  return { ...change(issue, "issue", "issue_closed", issue.closedAt, closer), ...(reason ? { reason } : {}) };
148
140
  }
149
141
 
150
142
  // A PR Attention Span saw closed, now open again by someone else [HIS-07]. Only PRs already tracked count, so a first run
151
143
  // doesn't announce every old reopen, and issues don't come here: they surface in Next up.
152
- export function reopened(tracked: TrackedPr, subject: ReopenSubject, me: string): OthersChange | null {
144
+ function reopened(tracked: TrackedPr, subject: ReopenSubject, me: string): OthersChange | null {
153
145
  if (subject.state !== "OPEN") return null;
154
146
  const event = subject.timelineItems.nodes.at(-1);
155
147
  const actor = event?.actor?.login;
156
- if (!actor || same(actor, me)) return null;
148
+ if (!actor || sameName(actor, me)) return null;
157
149
  return {
158
150
  id: `reopened:${subject.id}:${event?.createdAt ?? tracked.closedAt}`,
159
151
  kind: "reopened",
@@ -289,7 +281,7 @@ export function nextLedger(
289
281
  // An archive acknowledges exactly the events on its work at that moment, keyed by "owner/name#number" [ATT-22].
290
282
  // `upTo` keeps what others did after then unread: a session archived in Paseo acknowledges only what came before it.
291
283
  export function acknowledge(ledger: ChangeLedger, keys: string[], upTo?: string): ChangeLedger {
292
- const wanted = new Set(keys.map((key) => key.toLowerCase()));
284
+ const wanted = keySet(keys);
293
285
  const before = (at: string) => !upTo || Date.parse(at) <= Date.parse(upTo);
294
286
  const ids = ledger.events.filter((event) => wanted.has(event.key.toLowerCase()) && before(event.at)).map((event) => event.id);
295
287
  return { ...ledger, gotIt: [...new Set([...ledger.gotIt, ...ids])] };
@@ -308,36 +300,24 @@ export function withGotIt(next: ChangeLedger, gotIt: string[]): ChangeLedger {
308
300
  export function changeItems(ledger: ChangeLedger, now: Date, windowDays: number, historySince: string): { notes: Item[]; history: Item[]; finished: Item[] } {
309
301
  const since = new Date(now.getTime() - windowDays * 86_400_000).toISOString();
310
302
  const gotIt = new Set(ledger.gotIt);
311
- const base = (change: OthersChange): Omit<Item, "key" | "section"> => ({
312
- kind: change.subject,
313
- draft: false,
314
- repo: change.repo,
315
- number: change.number,
316
- title: change.title,
317
- url: change.url,
318
- chips: [],
319
- actions: [],
320
- children: [],
321
- target: { kind: change.subject, repo: change.repo, number: change.number, title: change.title, url: change.url },
322
- othersActivityAt: change.at,
303
+ const base = (change: OthersChange, key: string, section: SectionId): Item => ({
304
+ ...baseItem({ key, section, kind: change.subject, repo: change.repo, number: change.number, title: change.title, url: change.url }, change.at),
323
305
  closedAt: change.at,
324
306
  change,
325
307
  });
326
308
  const notes = ledger.events
327
309
  .filter((change) => !gotIt.has(change.id) && change.at >= since)
328
- .map((change): Item => ({ ...base(change), key: `change:${change.id}`, section: "changed", actions: ["got_it"] }));
310
+ .map((change): Item => ({ ...base(change, `change:${change.id}`, "changed"), actions: ["got_it"] }));
329
311
  const history = ledger.events
330
312
  // A merge or an issue close is the week's Finished, not a change repeated under it [HIS-07].
331
313
  .filter((change) => gotIt.has(change.id) && !isFinishedChange(change) && change.at >= historySince)
332
- .map((change): Item => ({ ...base(change), key: `handed:${change.id}`, section: "handed_off", actions: [] }));
314
+ .map((change) => base(change, `handed:${change.id}`, "handed_off"));
333
315
  // A merge or close someone else did is finished work at once, not only when History's daily fetch catches up [HIS-07].
334
316
  const finished = ledger.events
335
317
  .filter((change) => isFinishedChange(change) && change.at >= historySince)
336
318
  .map(
337
319
  (change): Item => ({
338
- ...base(change),
339
- key: change.key,
340
- section: "done",
320
+ ...base(change, change.key, "done"),
341
321
  // The week's cards say it in the finished wording, not the note's: "merged 2h ago by dave" [HIS-05, HIS-07].
342
322
  change: undefined,
343
323
  ...(change.kind === "merged" && change.actor ? { mergedBy: change.actor } : {}),
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  type ActionId,
3
+ baseItem,
3
4
  type Attention,
4
5
  type Chip,
5
6
  type Item,
@@ -15,7 +16,7 @@ import {
15
16
  type Target,
16
17
  type WaitingOn,
17
18
  } from "../shared/attention";
18
- import { type AttentionConfig, FIELD_ROLES, type MergeMethod, nextUpField, sameField } from "../shared/config";
19
+ import { type AttentionConfig, FIELD_ROLES, type MergeMethod, nextUpField } from "../shared/config";
19
20
  import { ago, daysSince } from "../shared/format";
20
21
  import { workChip, workKind } from "../shared/work";
21
22
  import type { Actor, Comment, Details, HistoryResult, IssueNode, LinkedIssue, LiveResult, MentionNode, PickableNode, ProjectItemNode, PullRequestNode, RequestedReviewer } from "./github-types";
@@ -23,6 +24,7 @@ import { asksQuestion, excerpt, plainText, taggedIn } from "./markdown";
23
24
  import { prKey } from "./queries";
24
25
  import { issueFor } from "./references";
25
26
  import { ISSUE_RULES, type IssueState, nudgeable, pick, PR_RULES, type PrState, replyActions, rulesBlock } from "./rules";
27
+ import { sameName } from "../shared/names";
26
28
 
27
29
  // Turns one refresh worth of GitHub data into what needs me. Pure, so every rule is testable.
28
30
 
@@ -64,6 +66,121 @@ const author = (actor: Actor | null | undefined, since: string): Person | undefi
64
66
  // Search returns empty objects for result types a fragment doesn't cover.
65
67
  const compact = <T>(nodes: (T | null | undefined)[]) => nodes.filter((node): node is T => !!node && Object.keys(node).length > 0);
66
68
 
69
+ // Stacks, followed through base/head branch names, among my PRs and those asking for my review, whoever opened them; each
70
+ // from its bottom PR up [ATT-04]. A fork's branch isn't the repo's, so a PR from a fork is never a parent.
71
+ function buildStacks(prs: PullRequestNode[]) {
72
+ const byHead = new Map(prs.filter((pr) => !pr.isCrossRepository).map((pr) => [`${pr.repository.nameWithOwner}\0${pr.headRefName}`, pr]));
73
+ const parentOf = (pr: PullRequestNode) => {
74
+ const parent = byHead.get(`${pr.repository.nameWithOwner}\0${pr.baseRefName}`);
75
+ return parent === pr ? undefined : parent;
76
+ };
77
+ const stacks: PullRequestNode[][] = [];
78
+ const seen = new Set<PullRequestNode>();
79
+ const walk = (pr: PullRequestNode, stack: PullRequestNode[]) => {
80
+ if (seen.has(pr)) return;
81
+ seen.add(pr);
82
+ stack.push(pr);
83
+ for (const child of prs.filter((candidate) => parentOf(candidate) === pr)) walk(child, stack);
84
+ };
85
+ const byNumber = [...prs].sort((a, b) => a.number - b.number);
86
+ for (const pr of byNumber) if (!parentOf(pr)) stacks.push([]), walk(pr, stacks[stacks.length - 1]);
87
+ for (const pr of byNumber) if (!seen.has(pr)) stacks.push([pr]); // cycles, in theory
88
+ return { stacks, parentOf };
89
+ }
90
+
91
+ // What each PR's checks, reviews and branches say, worked out once per PR.
92
+ function prState(
93
+ pr: PullRequestNode,
94
+ {
95
+ details,
96
+ config,
97
+ now,
98
+ isMe,
99
+ isOther,
100
+ parentOf,
101
+ }: { details: Details; config: AttentionConfig; now: Date; isMe: (actor: Actor | null | undefined) => boolean; isOther: (actor: Actor | null | undefined) => boolean; parentOf: (pr: PullRequestNode) => PullRequestNode | undefined },
102
+ ) {
103
+ const commit = pr.commits.nodes[0]?.commit;
104
+ const ci = commit?.statusCheckRollup?.state;
105
+ const anyFailing = ci === "FAILURE" || ci === "ERROR";
106
+ const anyPending = ci === "PENDING" || ci === "EXPECTED";
107
+ // Asked a few PRs at a time where we could; search's answer is BLOCKED for all once there are more than a few [PRS-13].
108
+ const mergeBlocked = (details.mergeState[prKey(pr)] ?? pr.mergeStateStatus) === "BLOCKED";
109
+ // Where the repo requires checks, only those count; one that hasn't reported yet shows as GitHub blocking while CI runs.
110
+ // Where it requires none, every check counts [PRS-14].
111
+ const required = details.checks[prKey(pr)];
112
+ const ciFailing = required?.required ? required.failing > 0 : anyFailing;
113
+ const ciPending = !ciFailing && (required?.required ? required.pending > 0 || (anyPending && mergeBlocked) : anyPending);
114
+ const unresolved = pr.reviewThreads.nodes.filter((thread) => !thread.isResolved);
115
+ const last = (thread: (typeof unresolved)[number]) => thread.comments.nodes.at(-1);
116
+ const onMe = unresolved.filter((thread) => !isMe(last(thread)?.author));
117
+ const lastCommitAt = commit?.committedDate ?? pr.createdAt;
118
+ const changesRequestedAt = latest(...pr.latestReviews.nodes.filter((r) => r.state === "CHANGES_REQUESTED").map((r) => r.submittedAt));
119
+ const behindBy = details.behind[prKey(pr)] ?? 0;
120
+ return {
121
+ ciFailing,
122
+ ciPending,
123
+ optionalFailing: !ciFailing && anyFailing,
124
+ optionalPending: !ciFailing && !ciPending && anyPending,
125
+ conflicts: pr.mergeable === "CONFLICTING",
126
+ mergeBlocked,
127
+ approved: pr.reviewDecision === "APPROVED",
128
+ // Only what GitHub records as owed: a pending request, even one whose reviewer I can't see, or a decision. Who has
129
+ // reviewed doesn't count; GitHub drops a reviewer's request once they review, so a comment leaves the next move to
130
+ // me. The repo decides what counts as a review, not us [PRS-12].
131
+ asked: pr.reviewRequests.nodes.length > 0 || pr.reviewDecision === "APPROVED" || pr.reviewDecision === "CHANGES_REQUESTED",
132
+ autoMerge: !!pr.autoMergeRequest,
133
+ threadsOnMe: onMe.length,
134
+ botThreadsOnly: onMe.length > 0 && onMe.every((thread) => (thread.opener?.nodes[0] ?? last(thread))?.author?.__typename === "Bot"),
135
+ // Requested changes stay mine until I push after them.
136
+ changes: onMe.length > 0 || (pr.reviewDecision === "CHANGES_REQUESTED" && !(lastCommitAt > changesRequestedAt)),
137
+ repliedAt: latest(...unresolved.filter((thread) => isMe(last(thread)?.author)).map((thread) => last(thread)?.createdAt)),
138
+ lastCommitAt,
139
+ behindBy,
140
+ // A stacked PR no longer builds on its parent's latest version [UPS-02].
141
+ outOfSync: !!parentOf(pr) && behindBy > 0,
142
+ stale: daysSince(pr.updatedAt, now) >= config.staleDraftDays,
143
+ othersActivityAt: latest(
144
+ ...pr.comments.nodes.filter((c) => isOther(c.author)).map((c) => c.createdAt),
145
+ ...pr.reviewThreads.nodes.flatMap((t) => t.comments.nodes).filter((c) => isOther(c.author)).map((c) => c.createdAt),
146
+ ...pr.latestReviews.nodes.filter((r) => isOther(r.author)).map((r) => r.submittedAt),
147
+ ),
148
+ };
149
+ }
150
+
151
+ type PrFacts = ReturnType<typeof prState>;
152
+
153
+ // A PR's chips in order, as [when, chip]: the item's from my stack's bottom PR, and each sub-row's [ATT-04, UPS-07].
154
+ type ChipFacts = { pr: PullRequestNode; s: PrFacts; base: string; now: Date; section?: SectionId; rulesBlocked?: boolean; own?: boolean };
155
+ type ChipRule = [when: (c: ChipFacts) => boolean, chip: Chip | ((c: ChipFacts) => Chip)];
156
+ const CI_FAILING: ChipRule = [({ s }) => s.ciFailing, chip("CI failing", "bad")];
157
+ const CONFLICTS: ChipRule = [({ s }) => s.conflicts, chip("conflicts", "bad")];
158
+ const BEHIND: ChipRule = [({ s }) => s.behindBy > 0, ({ s, base }) => behindChip(s.behindBy, base)];
159
+ const PR_CHIPS: ChipRule[] = [
160
+ [({ pr, s }) => pr.isDraft && s.stale, ({ pr, now }) => chip(`untouched ${ago(pr.updatedAt, now)}`, "warn")],
161
+ [({ pr, s }) => s.approved && !pr.isDraft, chip("approved", "good")],
162
+ [({ rulesBlocked }) => !!rulesBlocked, chip("blocked by repo rules", "warn")],
163
+ [({ s }) => s.autoMerge, chip("auto-merge on", "good")],
164
+ [({ pr }) => pr.reviewDecision === "CHANGES_REQUESTED", chip("changes requested", "warn")],
165
+ [({ s }) => s.threadsOnMe > 0, ({ s }) => chip(`${s.threadsOnMe} unresolved`, "warn")],
166
+ // One CI chip at most: failing, running, optional checks failing, or passed once ready on the current base [PRS-14].
167
+ CI_FAILING,
168
+ [({ s }) => s.ciPending, chip("CI running", "warn")],
169
+ [({ s }) => s.optionalFailing && !s.ciPending, chip("optional checks failing", "warn")],
170
+ [({ s, section }) => section === "ready" && s.behindBy === 0 && !s.ciFailing && !s.ciPending && !s.optionalFailing, ({ s }) => chip(s.optionalPending ? "required checks passed" : "CI passed", "good")],
171
+ CONFLICTS,
172
+ BEHIND,
173
+ ];
174
+ const SUB_CHIPS: ChipRule[] = [
175
+ [({ s }) => s.approved, chip("approved", "good")],
176
+ // Only mine are mine to ask someone on [PRS-12].
177
+ [({ pr, s, own }) => !!own && !pr.isDraft && !s.asked, chip("no reviewer", "warn")],
178
+ CI_FAILING,
179
+ CONFLICTS,
180
+ BEHIND,
181
+ ];
182
+ const chipsFor = (rules: ChipRule[], facts: ChipFacts) => rules.filter(([when]) => when(facts)).map(([, made]) => (typeof made === "function" ? made(facts) : made));
183
+
67
184
  export function classify({ data, details, config, now }: ClassifyInput): Attention {
68
185
  const me = data.viewer.login.toLowerCase();
69
186
  const isMe = (actor: { login: string } | null | undefined) => actor?.login.toLowerCase() === me;
@@ -97,74 +214,11 @@ export function classify({ data, details, config, now }: ClassifyInput): Attenti
97
214
  const requests = compact(data.reviews.nodes).filter((pr) => !ownKeys.has(prKey(pr)));
98
215
  const isOwn = (pr: PullRequestNode) => ownKeys.has(prKey(pr));
99
216
 
100
- // Stacks, followed through base/head branch names, among my PRs and those asking for my review, whoever opened them [ATT-04].
101
- // A fork's branch isn't the repo's, so a PR from a fork is never a parent.
102
217
  const prs = [...mine, ...requests];
103
- const byHead = new Map(prs.filter((pr) => !pr.isCrossRepository).map((pr) => [`${pr.repository.nameWithOwner}\0${pr.headRefName}`, pr]));
104
- const parentOf = (pr: PullRequestNode) => {
105
- const parent = byHead.get(`${pr.repository.nameWithOwner}\0${pr.baseRefName}`);
106
- return parent === pr ? undefined : parent;
107
- };
108
- const stacks: PullRequestNode[][] = [];
109
- const seen = new Set<PullRequestNode>();
110
- const walk = (pr: PullRequestNode, stack: PullRequestNode[]) => {
111
- if (seen.has(pr)) return;
112
- seen.add(pr);
113
- stack.push(pr);
114
- for (const child of prs.filter((candidate) => parentOf(candidate) === pr)) walk(child, stack);
115
- };
116
- const byNumber = [...prs].sort((a, b) => a.number - b.number);
117
- for (const pr of byNumber) if (!parentOf(pr)) stacks.push([]), walk(pr, stacks[stacks.length - 1]);
118
- for (const pr of byNumber) if (!seen.has(pr)) stacks.push([pr]); // cycles, in theory
218
+ const { stacks, parentOf } = buildStacks(prs);
119
219
 
120
- const state = (pr: PullRequestNode) => {
121
- const commit = pr.commits.nodes[0]?.commit;
122
- const ci = commit?.statusCheckRollup?.state;
123
- const anyFailing = ci === "FAILURE" || ci === "ERROR";
124
- const anyPending = ci === "PENDING" || ci === "EXPECTED";
125
- // Asked a few PRs at a time where we could; search's answer is BLOCKED for all once there are more than a few [PRS-13].
126
- const mergeBlocked = (details.mergeState[prKey(pr)] ?? pr.mergeStateStatus) === "BLOCKED";
127
- // Where the repo requires checks, only those count; one that hasn't reported yet shows as GitHub blocking while CI runs.
128
- // Where it requires none, every check counts [PRS-14].
129
- const required = details.checks[prKey(pr)];
130
- const ciFailing = required?.required ? required.failing > 0 : anyFailing;
131
- const ciPending = !ciFailing && (required?.required ? required.pending > 0 || (anyPending && mergeBlocked) : anyPending);
132
- const unresolved = pr.reviewThreads.nodes.filter((thread) => !thread.isResolved);
133
- const last = (thread: (typeof unresolved)[number]) => thread.comments.nodes.at(-1);
134
- const onMe = unresolved.filter((thread) => !isMe(last(thread)?.author));
135
- const lastCommitAt = commit?.committedDate ?? pr.createdAt;
136
- const changesRequestedAt = latest(...pr.latestReviews.nodes.filter((r) => r.state === "CHANGES_REQUESTED").map((r) => r.submittedAt));
137
- const behindBy = details.behind[prKey(pr)] ?? 0;
138
- return {
139
- ciFailing,
140
- ciPending,
141
- optionalFailing: !ciFailing && anyFailing,
142
- optionalPending: !ciFailing && !ciPending && anyPending,
143
- conflicts: pr.mergeable === "CONFLICTING",
144
- mergeBlocked,
145
- approved: pr.reviewDecision === "APPROVED",
146
- // Only what GitHub records as owed: a pending request, even one whose reviewer I can't see, or a decision. Who has
147
- // reviewed doesn't count; GitHub drops a reviewer's request once they review, so a comment leaves the next move to
148
- // me. The repo decides what counts as a review, not us [PRS-12].
149
- asked: pr.reviewRequests.nodes.length > 0 || pr.reviewDecision === "APPROVED" || pr.reviewDecision === "CHANGES_REQUESTED",
150
- autoMerge: !!pr.autoMergeRequest,
151
- threadsOnMe: onMe.length,
152
- botThreadsOnly: onMe.length > 0 && onMe.every((thread) => (thread.opener?.nodes[0] ?? last(thread))?.author?.__typename === "Bot"),
153
- // Requested changes stay mine until I push after them.
154
- changes: onMe.length > 0 || (pr.reviewDecision === "CHANGES_REQUESTED" && !(lastCommitAt > changesRequestedAt)),
155
- repliedAt: latest(...unresolved.filter((thread) => isMe(last(thread)?.author)).map((thread) => last(thread)?.createdAt)),
156
- lastCommitAt,
157
- behindBy,
158
- // A stacked PR no longer builds on its parent's latest version [UPS-02].
159
- outOfSync: !!parentOf(pr) && behindBy > 0,
160
- stale: daysSince(pr.updatedAt, now) >= config.staleDraftDays,
161
- othersActivityAt: latest(
162
- ...pr.comments.nodes.filter((c) => isOther(c.author)).map((c) => c.createdAt),
163
- ...pr.reviewThreads.nodes.flatMap((t) => t.comments.nodes).filter((c) => isOther(c.author)).map((c) => c.createdAt),
164
- ...pr.latestReviews.nodes.filter((r) => isOther(r.author)).map((r) => r.submittedAt),
165
- ),
166
- };
167
- };
220
+ const states = new Map(prs.map((pr) => [pr, prState(pr, { details, config, now, isMe, isOther, parentOf })]));
221
+ const state = (pr: PullRequestNode) => states.get(pr)!;
168
222
 
169
223
  const items: Item[] = [];
170
224
  const listed = new Set<string>();
@@ -226,19 +280,7 @@ export function classify({ data, details, config, now }: ClassifyInput): Attenti
226
280
  ? undefined
227
281
  : "review";
228
282
 
229
- const chips: Chip[] = [];
230
- if (bottom.isDraft && s.stale) chips.push(chip(`untouched ${ago(bottom.updatedAt, now)}`, "warn"));
231
- if (s.approved && !bottom.isDraft) chips.push(chip("approved", "good"));
232
- if (rulesBlocked) chips.push(chip("blocked by repo rules", "warn"));
233
- if (s.autoMerge) chips.push(chip("auto-merge on", "good"));
234
- if (bottom.reviewDecision === "CHANGES_REQUESTED") chips.push(chip("changes requested", "warn"));
235
- if (s.threadsOnMe > 0) chips.push(chip(`${s.threadsOnMe} unresolved`, "warn"));
236
- if (s.ciFailing) chips.push(chip("CI failing", "bad"));
237
- else if (s.ciPending) chips.push(chip("CI running", "warn"));
238
- else if (s.optionalFailing) chips.push(chip("optional checks failing", "warn"));
239
- else if (section === "ready" && s.behindBy === 0) chips.push(chip(s.optionalPending ? "required checks passed" : "CI passed", "good"));
240
- if (s.conflicts) chips.push(chip("conflicts", "bad"));
241
- if (s.behindBy > 0) chips.push(behindChip(s.behindBy, base));
283
+ const chips = chipsFor(PR_CHIPS, { pr: bottom, s, base, now, section, rulesBlocked });
242
284
 
243
285
  return {
244
286
  section,
@@ -292,14 +334,8 @@ export function classify({ data, details, config, now }: ClassifyInput): Attenti
292
334
  const subRow = (pr: PullRequestNode, index: number, stack: PullRequestNode[]): SubRow => {
293
335
  const s = state(pr);
294
336
  const parent = parentOf(pr);
295
- const chips: Chip[] = [];
296
- if (stack.length > 1) chips.push(chip(`${index + 1}/${stack.length}`));
297
- if (s.approved) chips.push(chip("approved", "good"));
298
- // Only mine are mine to ask someone on [PRS-12].
299
- if (isOwn(pr) && !pr.isDraft && !s.asked) chips.push(chip("no reviewer", "warn"));
300
- if (s.ciFailing) chips.push(chip("CI failing", "bad"));
301
- if (s.conflicts) chips.push(chip("conflicts", "bad"));
302
- if (s.behindBy > 0) chips.push(behindChip(s.behindBy, parent ? `#${parent.number}` : pr.baseRefName));
337
+ const facts = { pr, s, base: parent ? `#${parent.number}` : pr.baseRefName, now, own: isOwn(pr) };
338
+ const chips = [...(stack.length > 1 ? [chip(`${index + 1}/${stack.length}`)] : []), ...chipsFor(SUB_CHIPS, facts)];
303
339
  return { key: prKey(pr), number: pr.number, title: pr.title, url: pr.url, draft: pr.isDraft, chips, attention: s.outOfSync || s.conflicts || s.ciFailing };
304
340
  };
305
341
 
@@ -368,24 +404,7 @@ export function classify({ data, details, config, now }: ClassifyInput): Attenti
368
404
  const waiting = mentions.get(key);
369
405
  if (!waiting || listed.has(key)) continue;
370
406
  listed.add(key);
371
- const kind = node.__typename === "PullRequest" ? "pr" : "issue";
372
- const repo = node.repository.nameWithOwner;
373
- items.push({
374
- key,
375
- section: "reply",
376
- kind,
377
- draft: false,
378
- repo,
379
- number: node.number,
380
- title: node.title,
381
- url: node.url,
382
- chips: [],
383
- person: waiting,
384
- actions: replyActions(waiting),
385
- children: [],
386
- target: { kind, repo, number: node.number, title: node.title, url: node.url },
387
- othersActivityAt: waiting.since,
388
- });
407
+ items.push({ ...plain(node, node.__typename === "PullRequest" ? "pr" : "issue", "reply"), person: waiting, actions: replyActions(waiting), othersActivityAt: waiting.since });
389
408
  }
390
409
 
391
410
  // Issues and others' PRs I'm in: answered, or waiting on others, too long after waitingTooLongDays [WAI-01, ATT-11, ATT-16].
@@ -433,6 +452,11 @@ export function classifyHistory(data: HistoryResult): Item[] {
433
452
  const work = workKind({ type: node.issueType?.name, labels: node.labels?.nodes.map((label) => label.name), title: node.title });
434
453
  return work ? { ...item, work, chips: [workChip(work), ...item.chips] } : item;
435
454
  };
455
+ // Who merged a PR, when it wasn't me, alone or under its issue [HIS-05].
456
+ const mergedBy = (pr: { mergedBy?: { login: string } | null }) => {
457
+ const by = pr.mergedBy?.login;
458
+ return by && me && by.toLowerCase() !== me ? { mergedBy: by } : {};
459
+ };
436
460
  for (const issue of compact(data.closed.nodes)) {
437
461
  const notPlanned = issue.stateReason === "NOT_PLANNED";
438
462
  // Who closed it, when it wasn't me [HIS-07].
@@ -447,22 +471,19 @@ export function classifyHistory(data: HistoryResult): Item[] {
447
471
  // Each merged PR on its own: its branches are gone, so it can't be put back in its stack [ATT-03].
448
472
  const linked = { repo: pr.repository.nameWithOwner, body: pr.body, linked: pr.closingIssuesReferences.nodes.map(prKey) };
449
473
  const issue = closed.get(issueFor([linked], (key) => closed.has(key)) ?? "");
450
- // Who merged it, when it wasn't me, alone or under its issue [HIS-05].
451
- const by = pr.mergedBy?.login;
452
- const mergedBy = by && me && by.toLowerCase() !== me ? { mergedBy: by } : {};
453
- if (issue) issue.children.push({ key: prKey(pr), number: pr.number, title: pr.title, url: pr.url, draft: false, chips: [], attention: false, ...mergedBy });
454
- else items.push(kinded({ ...plain(pr, "pr", "done"), closedAt: pr.mergedAt, ...mergedBy }, pr));
474
+ const head = pr.headRefName ? { headRefName: pr.headRefName } : {};
475
+ if (issue) issue.children.push({ key: prKey(pr), number: pr.number, title: pr.title, url: pr.url, draft: false, chips: [], attention: false, ...mergedBy(pr), ...head, mergedAt: pr.mergedAt });
476
+ else {
477
+ const item = plain(pr, "pr", "done");
478
+ items.push(kinded({ ...item, target: { ...item.target, ...head }, closedAt: pr.mergedAt, ...mergedBy(pr) }, pr));
479
+ }
455
480
  }
456
481
  for (const pr of compact(data.reviewed.nodes)) {
457
- const by = pr.mergedBy?.login;
458
- const mergedBy = by && me && by.toLowerCase() !== me ? { mergedBy: by } : {};
459
- items.push(kinded({ ...plain(pr, "pr", "reviewed"), closedAt: pr.mergedAt, person: author(pr.author, pr.mergedAt), ...mergedBy }, pr));
482
+ items.push(kinded({ ...plain(pr, "pr", "reviewed"), closedAt: pr.mergedAt, person: author(pr.author, pr.mergedAt), ...mergedBy(pr) }, pr));
460
483
  }
461
484
  return items.sort(order);
462
485
  }
463
486
 
464
- // Whether my last comment on an issue is the last one from a person, and if not, the answers since that I haven't 👍'd.
465
- // Bots don't count [MEN-05]. Only the last comments are fetched: once mine is out of them the conversation has moved on.
466
487
  // Whether my last comment on a thread is the last one from a person, and if not, the recent comments since that I haven't 👍'd.
467
488
  // On a thread I opened, my opening counts as my last word until I comment. Bots don't count [MEN-05]. Only the last comments
468
489
  // are fetched: on someone else's thread, once mine is out of them the conversation has moved on.
@@ -519,7 +540,7 @@ function taggedSince(run: Comment[], me: string, url: string): WaitingOn[] {
519
540
  const tagged: WaitingOn[] = [];
520
541
  for (const comment of run) {
521
542
  for (const { login, team } of taggedIn(comment.bodyHTML)) {
522
- const seen = (other: { login: string }) => other.login.toLowerCase() === login.toLowerCase();
543
+ const seen = (other: { login: string }) => sameName(other.login, login);
523
544
  if (login.toLowerCase() === me || tagged.some(seen)) continue;
524
545
  tagged.push({ login, team, avatarUrl: team ? undefined : `${origin}/${login}.png?size=64`, since: comment.createdAt });
525
546
  }
@@ -531,7 +552,7 @@ function taggedSince(run: Comment[], me: string, url: string): WaitingOn[] {
531
552
  function reviewers(actors: (Actor | null | undefined)[], since: string): WaitingOn[] {
532
553
  const list: WaitingOn[] = [];
533
554
  for (const actor of actors) {
534
- if (!actor || list.some((other) => other.login.toLowerCase() === actor.login.toLowerCase())) continue;
555
+ if (!actor || list.some((other) => sameName(other.login, actor.login))) continue;
535
556
  list.push({ login: actor.login, avatarUrl: actor.avatarUrl, team: actor.__typename === "Team", ...(actor.__typename === "Bot" ? { bot: true } : {}), since });
536
557
  }
537
558
  return list;
@@ -566,22 +587,7 @@ function recentReviewers(mine: PullRequestNode[], isOther: (actor: Actor | null
566
587
 
567
588
  // An item with nothing to act on: waiting, history.
568
589
  function plain(node: { repository: { nameWithOwner: string }; number: number; title: string; url: string }, kind: "pr" | "issue", section: SectionId): Item {
569
- const repo = node.repository.nameWithOwner;
570
- return {
571
- key: prKey(node),
572
- section,
573
- kind,
574
- draft: false,
575
- repo,
576
- number: node.number,
577
- title: node.title,
578
- url: node.url,
579
- chips: [],
580
- actions: [],
581
- children: [],
582
- target: { kind, repo, number: node.number, title: node.title, url: node.url },
583
- othersActivityAt: EPOCH,
584
- };
590
+ return baseItem({ key: prKey(node), section, kind, repo: node.repository.nameWithOwner, number: node.number, title: node.title, url: node.url });
585
591
  }
586
592
 
587
593
  export function mergeMethodFor(pr: PullRequestNode, config: AttentionConfig): MergeMethod {
@@ -593,11 +599,11 @@ export function mergeMethodFor(pr: PullRequestNode, config: AttentionConfig): Me
593
599
 
594
600
  function rankIssues(nodes: PickableNode[], details: Details, config: AttentionConfig): NextUpIssue[] {
595
601
  const [priority, effort, scope] = FIELD_ROLES.map((role) => nextUpField(config, role));
596
- const valueOf = (node: PickableNode, field: string | undefined) => node.issueFieldValues.nodes.find((value) => sameField(value.field?.name, field))?.name;
602
+ const valueOf = (node: PickableNode, field: string | undefined) => node.issueFieldValues.nodes.find((value) => sameName(value.field?.name, field))?.name;
597
603
  // A field of the issue's own org: its options' order, or the colors it gave them. Two orgs may both have a Priority field,
598
604
  // ordered and colored differently [NXT-02, NXT-10].
599
605
  const ofOrg = <T,>(byOrg: Record<string, Record<string, T>> | undefined, node: PickableNode, field: string) =>
600
- Object.entries(byOrg?.[node.repository.nameWithOwner.split("/")[0].toLowerCase()] ?? {}).find(([name]) => sameField(name, field))?.[1];
606
+ Object.entries(byOrg?.[node.repository.nameWithOwner.split("/")[0].toLowerCase()] ?? {}).find(([name]) => sameName(name, field))?.[1];
601
607
  // Position in the configured order (matched by name), else in the issue's org's own options; missing goes last.
602
608
  const position = (node: PickableNode, ranked: { field: string; order?: string[] } | undefined) => {
603
609
  const value = valueOf(node, ranked?.field);
@@ -10,17 +10,13 @@ const run = promisify(execFile);
10
10
  // A scratch directory for the session, where this plugin is installed and which version it is [FB-01].
11
11
  export async function feedbackInfo(): Promise<FeedbackInfo> {
12
12
  const cwd = mkdtempSync(join(tmpdir(), "attention-span-feedback-"));
13
- const source = pluginDir();
13
+ const source = ourInstall()?.path ?? null;
14
14
  return { cwd, source, version: source ? await version(source) : null };
15
15
  }
16
16
 
17
+ // The runtime ID this plugin is installed under, and its source. The update check names the ID [UPD-01].
17
18
  // Paseo evaluates the server as a bundle, so it has no file location of its own (import.meta.url is undefined).
18
19
  // Paseo's config.json records where each plugin's source is: take this plugin's, by its manifest's ID.
19
- export function pluginDir(paseoHome?: string): string | null {
20
- return ourInstall(paseoHome)?.path ?? null;
21
- }
22
-
23
- // The runtime ID this plugin is installed under, and its source. The update check names the ID [UPD-01].
24
20
  export function ourInstall(paseoHome = process.env.PASEO_HOME || join(homedir(), ".paseo")): { id: string; path: string } | null {
25
21
  try {
26
22
  const { plugins = {} } = JSON.parse(readFileSync(join(paseoHome, "config.json"), "utf8")) as { plugins?: Record<string, { path?: string }> };