@omercnet/paseo-pr-radar 3.3.0-next.528.1 → 3.3.0-next.529.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.
@@ -8,11 +8,13 @@ interface AgentUpdate {
8
8
  requiresAttention?: unknown;
9
9
  attentionReason?: unknown;
10
10
  pendingPermissions?: unknown;
11
+ archivedAt?: unknown;
11
12
  }
12
13
 
13
14
  // The agent fields buildRadarSnapshot and toRadarAgent read, minus `updatedAt`. The daemon touches
14
15
  // `updatedAt` and re-publishes a running agent on every usage report, so refetching on it rescanned
15
16
  // the directory every second or two. `updatedAt` only orders agents inside a row; the poll keeps it.
17
+ // `archivedAt` is in, so archiving or restoring an agent that nothing else changed still refreshes.
16
18
  function rowFields(agent: AgentUpdate): string {
17
19
  return JSON.stringify([
18
20
  agent.workspaceId,
@@ -21,9 +23,14 @@ function rowFields(agent: AgentUpdate): string {
21
23
  agent.requiresAttention,
22
24
  agent.attentionReason,
23
25
  agent.pendingPermissions,
26
+ agent.archivedAt,
24
27
  ]);
25
28
  }
26
29
 
30
+ function isArchived(agent: AgentUpdate): boolean {
31
+ return typeof agent.archivedAt === "string";
32
+ }
33
+
27
34
  /**
28
35
  * Skips agent updates that cannot change a row: helpers (fixed at creation, so an upsert
29
36
  * identifies one and the later removal reuses that knowledge) and repeat upserts of a user agent
@@ -49,9 +56,15 @@ function quietUpdateFilter() {
49
56
  return true;
50
57
  }
51
58
  const fields = rowFields(payload.agent);
52
- if (shownFields.get(payload.agent.id) === fields) return true;
53
- shownFields.set(payload.agent.id, fields);
54
- return false;
59
+ const unchanged = shownFields.get(payload.agent.id) === fields;
60
+ // An archived agent has no row to keep current, so its snapshot (title, permissions, ...) is
61
+ // freed now instead of at removal. A repeat archive upsert then invalidates once more.
62
+ if (isArchived(payload.agent)) {
63
+ shownFields.delete(payload.agent.id);
64
+ } else {
65
+ shownFields.set(payload.agent.id, fields);
66
+ }
67
+ return unchanged;
55
68
  }
56
69
  if (payload.kind === "remove" && typeof payload.agentId === "string") {
57
70
  shownFields.delete(payload.agentId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omercnet/paseo-pr-radar",
3
- "version": "3.3.0-next.528.1",
3
+ "version": "3.3.0-next.529.1",
4
4
  "type": "module",
5
5
  "description": "A viewer-aware delivery queue for pull requests linked to Paseo workspaces.",
6
6
  "license": "MIT",
@@ -241,9 +241,7 @@ async function configuredFilterSafetyArgs(cwd: string): Promise<FilterOverride[]
241
241
  : undefined;
242
242
  if (code !== 1) {
243
243
  throw new Error(
244
- `Could not enumerate repository filter configuration in ${cwd}: ${
245
- err instanceof Error ? err.message : String(err)
246
- }`,
244
+ `Could not enumerate repository filter configuration in ${cwd}: ${errorMessage(err)}`,
247
245
  );
248
246
  }
249
247
  raw = Buffer.alloc(0);
@@ -706,27 +704,67 @@ async function assertNoIgnoredFileOverwrite(
706
704
  }
707
705
  }
708
706
 
709
- /**
710
- * Runs git and returns its stdout as UTF-8, failing closed when the output is not valid UTF-8.
711
- * `runGit` decodes lossily, which would mangle a non-UTF-8 filename and let a comparison miss it.
712
- */
713
- async function runGitLossless(
707
+ const NUL_BYTE = 0x00;
708
+ const TAB_BYTE = 0x09;
709
+ const SPACE_BYTE = 0x20;
710
+ const GITLINK_ENTRY_PREFIX = Buffer.from("160000 ");
711
+
712
+ /** Runs git and returns its stdout undecoded, so a caller can inspect names that are not UTF-8. */
713
+ async function runGitBytes(
714
714
  cwd: string,
715
715
  args: string[],
716
716
  timeout = COMMAND_TIMEOUT_MS,
717
- ): Promise<string> {
717
+ ): Promise<Buffer> {
718
718
  const { stdout } = await execFileAsync("git", [...GIT_SAFETY_ARGS, "-C", cwd, ...args], {
719
719
  timeout,
720
720
  maxBuffer: MAX_BUFFER_BYTES,
721
721
  env: gitEnv(),
722
722
  encoding: "buffer",
723
723
  });
724
- const raw = stdout as Buffer;
725
- const decoded = raw.toString("utf8");
726
- if (!Buffer.from(decoded, "utf8").equals(raw)) {
727
- throw new Error(`Git output in ${cwd} contains invalid UTF-8; refusing to proceed.`);
724
+ return stdout as Buffer;
725
+ }
726
+
727
+ /** Splits `-z` output on NUL into its non-empty records, byte for byte. */
728
+ function nulSeparatedEntries(raw: Buffer): Buffer[] {
729
+ const entries: Buffer[] = [];
730
+ let start = 0;
731
+ for (let end = raw.indexOf(NUL_BYTE); end !== -1; end = raw.indexOf(NUL_BYTE, start)) {
732
+ if (end > start) entries.push(raw.subarray(start, end));
733
+ start = end + 1;
734
+ }
735
+ if (start < raw.length) entries.push(raw.subarray(start));
736
+ return entries;
737
+ }
738
+
739
+ function hasPrefix(bytes: Buffer, prefix: Buffer): boolean {
740
+ return bytes.subarray(0, prefix.length).equals(prefix);
741
+ }
742
+
743
+ /** The path of an `ls-files -s -z` or `ls-tree -z` record: everything after its first tab. */
744
+ function entryPathBytes(entry: Buffer): Buffer {
745
+ return entry.subarray(entry.indexOf(TAB_BYTE) + 1);
746
+ }
747
+
748
+ /**
749
+ * The paths of the submodule (mode 160000) entries in `ls-files -s -z` output. Only these paths are
750
+ * decoded, and strictly: a lossy decode would mangle a non-UTF-8 submodule path and let the
751
+ * comparison against the incoming tree miss it, so that one case fails closed. Every other tracked
752
+ * name, whatever its bytes, is skipped undecoded.
753
+ */
754
+ function submodulePaths(dir: string, lsFilesOutput: Buffer): string[] {
755
+ const paths: string[] = [];
756
+ for (const entry of nulSeparatedEntries(lsFilesOutput)) {
757
+ if (!hasPrefix(entry, GITLINK_ENTRY_PREFIX)) continue;
758
+ const pathBytes = entryPathBytes(entry);
759
+ const path = pathBytes.toString("utf8");
760
+ if (!Buffer.from(path, "utf8").equals(pathBytes)) {
761
+ throw new Error(
762
+ `A submodule path in ${dir} is not valid UTF-8, so it cannot be checked against the incoming tree; refusing to proceed.`,
763
+ );
764
+ }
765
+ paths.push(path);
728
766
  }
729
- return decoded;
767
+ return paths;
730
768
  }
731
769
 
732
770
  /**
@@ -739,30 +777,25 @@ async function assertNoGitlinkToFileOverwrite(
739
777
  target: string,
740
778
  prNumber: number,
741
779
  ): Promise<void> {
742
- const gitlinks = (await runGitLossless(dir, ["ls-files", "-s", "-z"]))
743
- .split("\0")
744
- .filter((entry) => entry.startsWith("160000 "));
745
- if (gitlinks.length === 0) return;
746
- const gitlinkPaths = gitlinks
747
- .map((entry) => entry.slice(entry.indexOf("\t") + 1))
748
- .filter(Boolean);
780
+ const gitlinkPaths = submodulePaths(dir, await runGitBytes(dir, ["ls-files", "-s", "-z"]));
749
781
  if (gitlinkPaths.length === 0) return;
750
782
 
751
783
  // Returns the mode of the exact entry at `path` in the target tree (or null when absent). A leaf
752
784
  // produces exactly the entry at `path`; a directory produces only its children (`path/…`).
785
+ // Compared as bytes, so a sibling with a non-UTF-8 name can neither match nor break it.
753
786
  const targetEntryMode = async (path: string): Promise<string | null> => {
754
- const entries = (
755
- await runGitLossless(dir, ["ls-tree", "-z", target, "--", `:(literal)${path}`])
756
- )
757
- .split("\0")
758
- .filter(Boolean);
787
+ const wanted = Buffer.from(path, "utf8");
788
+ const childPrefix = Buffer.from(`${path}/`, "utf8");
789
+ const entries = nulSeparatedEntries(
790
+ await runGitBytes(dir, ["ls-tree", "-z", target, "--", `:(literal)${path}`]),
791
+ );
792
+ let hasChildren = false;
759
793
  for (const entry of entries) {
760
- if (entry.slice(entry.indexOf("\t") + 1) === path) return entry.slice(0, entry.indexOf(" "));
761
- }
762
- if (entries.some((entry) => entry.slice(entry.indexOf("\t") + 1).startsWith(`${path}/`))) {
763
- return "040000";
794
+ const entryPath = entryPathBytes(entry);
795
+ if (entryPath.equals(wanted)) return entry.subarray(0, entry.indexOf(SPACE_BYTE)).toString();
796
+ if (hasPrefix(entryPath, childPrefix)) hasChildren = true;
764
797
  }
765
- return null;
798
+ return hasChildren ? "040000" : null;
766
799
  };
767
800
 
768
801
  // A gitlink that becomes anything but another gitlink (file, symlink, directory, or removed)
@@ -789,15 +822,21 @@ async function assertNoGitlinkToFileOverwrite(
789
822
  }
790
823
  }
791
824
 
825
+ /** The checked-out branch, or null on a detached HEAD. A git failure is an error, not "detached". */
792
826
  async function currentBranch(repoDir: string): Promise<string | null> {
793
- const name = await runGit(repoDir, ["branch", "--show-current"], 3_000).catch(() => "");
827
+ const name = await runGit(repoDir, ["branch", "--show-current"], 3_000);
794
828
  return name || null;
795
829
  }
796
830
 
831
+ /** Remote branch names that stand in for a default branch the remote has not recorded. */
832
+ const CONVENTIONAL_DEFAULT_BRANCHES = ["main", "master"];
833
+
797
834
  /**
798
835
  * New issue branches start from the remote default branch. Without a recorded remote default the
799
- * current HEAD is used, but only when a remote-tracking branch already contains it: a PR branch, a
800
- * detached PR checkout or a local-only commit would carry unmerged, possibly untrusted code.
836
+ * current HEAD is used, but only when it is already on the conventional default branch (`main` or
837
+ * `master`) of the remote: a PR branch, a detached PR checkout or a local-only commit would carry
838
+ * unmerged, possibly untrusted code. Being on some other remote branch, such as a pushed PR branch,
839
+ * does not count.
801
840
  */
802
841
  async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise<string> {
803
842
  const remoteHead = await runGit(
@@ -813,30 +852,38 @@ async function resolveIssueStartPoint(baseRoot: string, remote: string): Promise
813
852
  ).catch(() => "");
814
853
  if (resolved) return resolved;
815
854
  }
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);
816
857
  const branch = await currentBranch(baseRoot);
817
858
  if (branch?.startsWith("pr-radar/")) {
818
859
  throw new Error(
819
860
  `Base checkout ${baseRoot} is on ${branch} and has no recorded default branch for ${remote}; check out the default branch there, or use another directory.`,
820
861
  );
821
862
  }
822
- const published = await runGit(
823
- baseRoot,
824
- [
825
- "for-each-ref",
826
- "--count=1",
827
- "--contains",
828
- "HEAD",
829
- "--format=%(refname)",
830
- `refs/remotes/${remote}`,
831
- ],
832
- 3_000,
833
- ).catch(() => "");
834
- if (!published) {
835
- throw new Error(
836
- `Base checkout ${baseRoot} has no recorded default branch for ${remote} and its HEAD is not on any ${remote} branch, so it may carry unmerged code; run git remote set-head ${remote} --auto there, or check out the default branch.`,
863
+ for (const name of CONVENTIONAL_DEFAULT_BRANCHES) {
864
+ // `show-ref --verify` takes only the exact full ref name. `for-each-ref` would also match a
865
+ // branch named `main/x` by prefix, and `rev-parse` falls back to a tag literally named
866
+ // `refs/remotes/origin/main`; a pushed branch or tag could be named either way.
867
+ const ref = await runGit(
868
+ baseRoot,
869
+ ["show-ref", "--verify", "--hash", `refs/remotes/${remote}/${name}`],
870
+ 3_000,
871
+ ).catch(() => "");
872
+ if (!ref) continue;
873
+ const tip = await runGit(baseRoot, ["rev-parse", "--verify", `${ref}^{commit}`], 3_000);
874
+ const published = await runGit(
875
+ baseRoot,
876
+ ["merge-base", "--is-ancestor", head, tip],
877
+ 3_000,
878
+ ).then(
879
+ () => true,
880
+ () => false,
837
881
  );
882
+ if (published) return head;
838
883
  }
839
- return runGit(baseRoot, ["rev-parse", "HEAD"], 3_000);
884
+ throw new Error(
885
+ `Base checkout ${baseRoot} has no recorded default branch for ${remote} and its HEAD is not on ${remote}/main or ${remote}/master, so it may carry unmerged code; run git remote set-head ${remote} --auto there, or check out the default branch.`,
886
+ );
840
887
  }
841
888
 
842
889
  async function refreshPrWorktree(
@@ -890,9 +937,62 @@ async function refreshIssueWorktree(worktreePath: string, localBranchName: strin
890
937
  await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
891
938
  }
892
939
 
940
+ function errorMessage(err: unknown): string {
941
+ return err instanceof Error ? err.message : String(err);
942
+ }
943
+
944
+ /**
945
+ * Materializes a worktree that `worktree add --no-checkout` just registered. When the checkout
946
+ * fails, the half-created worktree is removed, so the next request does not find it by branch and
947
+ * hand back an unpopulated directory. If that removal fails too, both errors are reported: the
948
+ * original cause must not be lost, and the leftover worktree needs to be named.
949
+ */
950
+ async function populateNewWorktree(baseRoot: string, worktreePath: string): Promise<void> {
951
+ try {
952
+ await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
953
+ } catch (checkoutError) {
954
+ try {
955
+ // No short timeout: the cleanup must be allowed to finish.
956
+ await runGit(baseRoot, ["worktree", "remove", "--force", worktreePath]);
957
+ } catch (removalError) {
958
+ throw new AggregateError(
959
+ [checkoutError, removalError],
960
+ `Checking out the new worktree ${worktreePath} failed (${errorMessage(checkoutError)}), and removing the half-created worktree failed too (${errorMessage(removalError)}); remove it with git worktree remove --force.`,
961
+ );
962
+ }
963
+ throw checkoutError;
964
+ }
965
+ }
966
+
967
+ /**
968
+ * Launches whose workspace is being prepared right now, one entry per repository and item. Two
969
+ * 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.
972
+ */
973
+ const launchesInFlight = new Set<string>();
974
+
893
975
  export async function prepareWorkspaceCwdHandler(
894
976
  input: z.output<typeof prepareWorkspaceCwd.input>,
895
977
  readSettings: ReadWorkspaceSettings,
978
+ ): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
979
+ 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.`,
983
+ );
984
+ }
985
+ launchesInFlight.add(launchKey);
986
+ try {
987
+ return await prepareLockedWorkspaceCwd(input, readSettings);
988
+ } finally {
989
+ launchesInFlight.delete(launchKey);
990
+ }
991
+ }
992
+
993
+ async function prepareLockedWorkspaceCwd(
994
+ input: z.output<typeof prepareWorkspaceCwd.input>,
995
+ readSettings: ReadWorkspaceSettings,
896
996
  ): Promise<z.output<typeof prepareWorkspaceCwd.output>> {
897
997
  if (!isValidRepositorySlug(input.repository)) {
898
998
  throw new Error(`Invalid repository name: ${input.repository}`);
@@ -1025,6 +1125,16 @@ export async function prepareWorkspaceCwdHandler(
1025
1125
  // CWD-WORKTREE: reuse existing worktree for this PR/issue branch if present (never reuse baseRoot).
1026
1126
  const resolvedBaseRoot = resolve(baseRoot);
1027
1127
  const existingWorktrees = await listWorktrees(baseRoot);
1128
+ // A CWD-BASE launch leaves the branch checked out in the base checkout, where `worktree add`
1129
+ // cannot also use it. Refuse, naming it, rather than fail inside git or quietly work in the base.
1130
+ const heldByBase = existingWorktrees.some(
1131
+ (wt) => wt.branch === localBranchName && resolve(wt.path) === resolvedBaseRoot,
1132
+ );
1133
+ if (heldByBase) {
1134
+ throw new Error(
1135
+ `Branch ${localBranchName} is checked out in the base checkout ${baseRoot} (an earlier CWD-BASE launch), so a worktree cannot use it too; switch that checkout to another branch, or launch with CWD-BASE.`,
1136
+ );
1137
+ }
1028
1138
  const existing = existingWorktrees.find(
1029
1139
  (wt) => wt.branch === localBranchName && resolve(wt.path) !== resolvedBaseRoot,
1030
1140
  );
@@ -1114,14 +1224,7 @@ export async function prepareWorkspaceCwdHandler(
1114
1224
  startPoint,
1115
1225
  ]);
1116
1226
  }
1117
- try {
1118
- await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
1119
- } catch (err) {
1120
- // The worktree is already registered; a failed checkout must not leave a half-created one.
1121
- // No short timeout here: cleanup must complete, and a removal failure propagates (not swallowed).
1122
- await runGit(baseRoot, ["worktree", "remove", "--force", worktreePath]);
1123
- throw err;
1124
- }
1227
+ await populateNewWorktree(baseRoot, worktreePath);
1125
1228
  } else {
1126
1229
  const prHead = await fetchPrHead(baseRoot, matchingRemote, input.prNumber);
1127
1230
  await assertBranchFastForwards(
@@ -1140,7 +1243,7 @@ export async function prepareWorkspaceCwdHandler(
1140
1243
  worktreePath,
1141
1244
  prHead,
1142
1245
  ]);
1143
- await runGit(worktreePath, ["checkout", "--force"], CLONE_TIMEOUT_MS);
1246
+ await populateNewWorktree(baseRoot, worktreePath);
1144
1247
  }
1145
1248
 
1146
1249
  return {