@omercnet/paseo-pr-radar 3.3.0-next.529.1 → 3.3.0-next.532.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-pr-radar",
3
- "version": "3.3.0-next.529.1",
3
+ "version": "3.3.0-next.532.1",
4
4
  "type": "module",
5
5
  "description": "A viewer-aware delivery queue for pull requests linked to Paseo workspaces.",
6
6
  "license": "MIT",
@@ -200,16 +200,21 @@ async function searchIssues(
200
200
  "--order=desc",
201
201
  `--json=${fields}`,
202
202
  ]);
203
- const parsed = JSON.parse(output);
204
- return {
205
- records: Array.isArray(parsed) ? (parsed as IssueSearchRecord[]) : [],
206
- failed: false,
207
- };
203
+ const parsed: unknown = JSON.parse(output);
204
+ if (!Array.isArray(parsed)) return { records: [], failed: true };
205
+ return { records: parsed as IssueSearchRecord[], failed: false };
208
206
  } catch {
209
207
  return { records: [], failed: true };
210
208
  }
211
209
  }
212
210
 
211
+ /** When one issue matches several searches it is shown under the highest-ranked role. */
212
+ const ISSUE_ROLE_RANK: Record<GitHubIssueItem["role"], number> = {
213
+ owner: 0,
214
+ assignee: 1,
215
+ author: 2,
216
+ };
217
+
213
218
  function toIssueItem(record: IssueSearchRecord, role: GitHubIssueItem["role"]): GitHubIssueItem {
214
219
  const labels = record.labels.map(({ name }) => name);
215
220
  const authorKind =
@@ -474,14 +479,27 @@ interface Snapshot {
474
479
  reviewRequestedScope: string[];
475
480
  inboxItems: GitHubInboxItem[];
476
481
  issueItems: GitHubIssueItem[];
482
+ /** Every role whose search returned each issue; a row shows only the highest-ranked one. */
483
+ issueRoles: Map<string, Set<GitHubIssueItem["role"]>>;
477
484
  issueTruncated: boolean;
478
485
  issueSearchFailures: number;
486
+ /** When each role's issue search last succeeded (ms); a role's kept issues age from here. */
487
+ issueFreshAt: Record<GitHubIssueItem["role"], number>;
488
+ /** Whether each role's list hit the search cap; a kept role keeps its flag. */
489
+ issueTruncatedBy: Record<GitHubIssueItem["role"], boolean>;
479
490
  enrichmentFailures: number;
480
491
  acknowledgedAt: string | null;
481
492
  }
482
493
 
483
- /** The expensive part: ~5 s of gh searches and GraphQL enrichment. */
484
- async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
494
+ /**
495
+ * The expensive part: ~5 s of gh searches and GraphQL enrichment. `previous` is the window's last
496
+ * snapshot: a failed issue search keeps its role's share of the issues it held, since an empty
497
+ * answer from a failed call says nothing about the issues. Only for the same viewer, and only
498
+ * while that role's last good search is within MAX_STALE_MS, so failures cannot hide behind old
499
+ * data forever (the coverage note keeps reporting them). A snapshot holding kept issues can still
500
+ * be served for up to MAX_STALE_MS more if the refreshes after it throw outright.
501
+ */
502
+ async function fetchSnapshot(windowDays: number, previous?: Snapshot): Promise<Snapshot> {
485
503
  const viewer = await viewerLogin();
486
504
  const since = new Date(Date.now() - windowDays * 24 * 60 * 60 * 1_000).toISOString().slice(0, 10);
487
505
  const [
@@ -502,15 +520,64 @@ async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
502
520
  searchIssues("owner", viewer, since),
503
521
  ]);
504
522
  const issueMap = new Map<string, GitHubIssueItem>();
505
- for (const record of ownedIssues.records) issueMap.set(record.id, toIssueItem(record, "owner"));
506
- for (const record of assignedIssues.records)
507
- issueMap.set(record.id, toIssueItem(record, "assignee"));
508
- for (const record of authoredIssues.records)
509
- issueMap.set(record.id, toIssueItem(record, "author"));
510
- const issueTruncated =
511
- authoredIssues.records.length === SEARCH_LIMIT ||
512
- assignedIssues.records.length === SEARCH_LIMIT ||
513
- ownedIssues.records.length === SEARCH_LIMIT;
523
+ const issueRoles = new Map<string, Set<GitHubIssueItem["role"]>>();
524
+ const addRole = (id: string, role: GitHubIssueItem["role"]) => {
525
+ const roles = issueRoles.get(id) ?? new Set<GitHubIssueItem["role"]>();
526
+ issueRoles.set(id, roles.add(role));
527
+ };
528
+ for (const [role, result] of [
529
+ ["owner", ownedIssues],
530
+ ["assignee", assignedIssues],
531
+ ["author", authoredIssues],
532
+ ] as const) {
533
+ for (const record of result.records) {
534
+ issueMap.set(record.id, toIssueItem(record, role));
535
+ addRole(record.id, role);
536
+ }
537
+ }
538
+ const searchedAt = Date.now();
539
+ const kept = previous?.viewer === viewer ? previous : undefined;
540
+ const searches = [
541
+ ["author", authoredIssues],
542
+ ["assignee", assignedIssues],
543
+ ["owner", ownedIssues],
544
+ ] as const;
545
+ const issueFreshAt = { author: 0, assignee: 0, owner: 0 };
546
+ const issueTruncatedBy = { author: false, assignee: false, owner: false };
547
+ const keptRoles = new Set<GitHubIssueItem["role"]>();
548
+ for (const [role, result] of searches) {
549
+ if (!result.failed) {
550
+ issueFreshAt[role] = searchedAt;
551
+ issueTruncatedBy[role] = result.records.length === SEARCH_LIMIT;
552
+ } else if (kept) {
553
+ issueFreshAt[role] = kept.issueFreshAt[role];
554
+ if (searchedAt - issueFreshAt[role] <= MAX_STALE_MS) {
555
+ keptRoles.add(role);
556
+ issueTruncatedBy[role] = kept.issueTruncatedBy[role];
557
+ }
558
+ }
559
+ }
560
+ // A kept row keeps every role it matched whose search failed. A role whose search succeeded
561
+ // without it has dropped it, but another failed role's search may still hold it.
562
+ for (const item of kept?.issueItems ?? []) {
563
+ let held = false;
564
+ for (const role of kept?.issueRoles.get(item.id) ?? [item.role]) {
565
+ if (!keptRoles.has(role)) continue;
566
+ addRole(item.id, role);
567
+ held = true;
568
+ }
569
+ // Fresh fields win over the kept row's.
570
+ if (held && !issueMap.has(item.id)) issueMap.set(item.id, item);
571
+ }
572
+ // The row shows the highest-ranked role among all that matched.
573
+ for (const [id, item] of issueMap) {
574
+ const roles = [...(issueRoles.get(id) ?? [item.role])];
575
+ const role = roles.reduce((best, next) =>
576
+ ISSUE_ROLE_RANK[next] > ISSUE_ROLE_RANK[best] ? next : best,
577
+ );
578
+ issueMap.set(id, { ...item, role });
579
+ }
580
+ const issueTruncated = Object.values(issueTruncatedBy).some(Boolean);
514
581
  const issueSearchFailures = [authoredIssues, assignedIssues, ownedIssues].filter(
515
582
  (res) => res.failed,
516
583
  ).length;
@@ -574,8 +641,11 @@ async function fetchSnapshot(windowDays: number): Promise<Snapshot> {
574
641
  reviewRequestedScope,
575
642
  inboxItems,
576
643
  issueItems,
644
+ issueRoles,
577
645
  issueTruncated,
578
646
  issueSearchFailures,
647
+ issueFreshAt,
648
+ issueTruncatedBy,
579
649
  enrichmentFailures: enrichment.failures,
580
650
  acknowledgedAt,
581
651
  };
@@ -598,7 +668,7 @@ export function projectSnapshot(snapshot: Snapshot, urls: string[]): ViewerScope
598
668
  }
599
669
  if (snapshot.issueSearchFailures > 0) {
600
670
  notes.push(
601
- `${snapshot.issueSearchFailures} GitHub issue search request${snapshot.issueSearchFailures === 1 ? "" : "s"} failed; issue list may be incomplete.`,
671
+ `${snapshot.issueSearchFailures} GitHub issue search request${snapshot.issueSearchFailures === 1 ? "" : "s"} failed; issue list may be stale or incomplete.`,
602
672
  );
603
673
  }
604
674
  const coverageNote =
@@ -663,7 +733,7 @@ function refreshWindow(windowDays: number): Promise<Snapshot> {
663
733
  const running = inflight.get(windowDays);
664
734
  if (running) return running;
665
735
  const started = Date.now();
666
- const promise = fetchSnapshot(windowDays)
736
+ const promise = fetchSnapshot(windowDays, snapshots.get(windowDays)?.snapshot)
667
737
  .then((snapshot) => {
668
738
  snapshots.set(windowDays, { snapshot, at: Date.now() });
669
739
  console.log(
@@ -720,6 +790,12 @@ export async function resolveViewerScope({
720
790
  }
721
791
  }
722
792
 
793
+ /** Test seam: waits for running refreshes to finish, keeping the cache. */
794
+ export async function settleViewerScopeRefreshes(): Promise<void> {
795
+ await Promise.allSettled([...inflight.values()]);
796
+ await stateQueue;
797
+ }
798
+
723
799
  /** Test seam: waits for running refreshes so tests do not bleed into each other. */
724
800
  export async function resetViewerScopeCache(): Promise<void> {
725
801
  await Promise.allSettled([...inflight.values()]);
@@ -853,7 +853,21 @@ async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise
853
853
  if (resolved) return resolved;
854
854
  }
855
855
  // One commit is checked and one is returned: another launch can move HEAD in between.
856
- const head = await runGit(baseRoot, ["rev-parse", "--verify", "HEAD^{commit}"], 3_000);
856
+ // `--quiet` makes an unborn HEAD (no commit yet) exit 1 without a message; a timeout or any
857
+ // other failure still surfaces as itself.
858
+ const head = await runGit(
859
+ baseRoot,
860
+ ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
861
+ 3_000,
862
+ ).catch((err: unknown) => {
863
+ if ((err as { code?: unknown } | null)?.code === 1) return "";
864
+ throw err;
865
+ });
866
+ if (!head) {
867
+ throw new Error(
868
+ `Base checkout ${baseRoot} has no recorded default branch for ${remote} and no commit checked out yet; run git remote set-head ${remote} --auto there, or make a first commit on the default branch.`,
869
+ );
870
+ }
857
871
  const branch = await currentBranch(baseRoot);
858
872
  if (branch?.startsWith("pr-radar/")) {
859
873
  throw new Error(
@@ -953,7 +967,7 @@ async function populateNewWorktree(baseRoot: string, worktreePath: string): Prom
953
967
  } catch (checkoutError) {
954
968
  try {
955
969
  // No short timeout: the cleanup must be allowed to finish.
956
- await runGit(baseRoot, ["worktree", "remove", "--force", worktreePath]);
970
+ await runGit(baseRoot, ["worktree", "remove", "--force", "--", worktreePath]);
957
971
  } catch (removalError) {
958
972
  throw new AggregateError(
959
973
  [checkoutError, removalError],
@@ -967,27 +981,35 @@ async function populateNewWorktree(baseRoot: string, worktreePath: string): Prom
967
981
  /**
968
982
  * Launches whose workspace is being prepared right now, one entry per repository and item. Two
969
983
  * launches for the same item would race into the same clone, branch and worktree (a double click,
970
- * or two devices), so a second one is refused instead of queued: the queue stays empty, and the
971
- * first launch's result is what the user sees.
984
+ * or two devices), so a second identical request gets the running launch's promise and both see one
985
+ * result. A second request that differs (another directory or mode) is refused instead, since the
986
+ * running launch's result would not answer it.
972
987
  */
973
- const launchesInFlight = new Set<string>();
988
+ const launchesInFlight = new Map<
989
+ string,
990
+ { signature: string; result: Promise<z.output<typeof prepareWorkspaceCwd.output>> }
991
+ >();
974
992
 
975
- export async function prepareWorkspaceCwdHandler(
993
+ export function prepareWorkspaceCwdHandler(
976
994
  input: z.output<typeof prepareWorkspaceCwd.input>,
977
995
  readSettings: ReadWorkspaceSettings,
978
996
  ): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
979
997
  const launchKey = `${input.repository.toLowerCase()}#${input.itemKind}-${input.prNumber}`;
980
- if (launchesInFlight.has(launchKey)) {
981
- throw new Error(
982
- `A launch for ${input.itemKind} #${input.prNumber} of ${input.repository} is already preparing its workspace; wait for it to finish, then try again.`,
998
+ const signature = JSON.stringify(input);
999
+ const running = launchesInFlight.get(launchKey);
1000
+ if (running) {
1001
+ if (running.signature === signature) return running.result;
1002
+ return Promise.reject(
1003
+ new Error(
1004
+ `A launch for ${input.itemKind} #${input.prNumber} of ${input.repository} is already preparing its workspace with different settings; wait for it to finish, then try again.`,
1005
+ ),
983
1006
  );
984
1007
  }
985
- launchesInFlight.add(launchKey);
986
- try {
987
- return await prepareLockedWorkspaceCwd(input, readSettings);
988
- } finally {
1008
+ const result = prepareLockedWorkspaceCwd(input, readSettings).finally(() => {
989
1009
  launchesInFlight.delete(launchKey);
990
- }
1010
+ });
1011
+ launchesInFlight.set(launchKey, { signature, result });
1012
+ return result;
991
1013
  }
992
1014
 
993
1015
  async function prepareLockedWorkspaceCwd(