@getpaseo/server 0.16.0 → 0.16.2

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 (56) hide show
  1. package/dist/server/builtin-plugins/package.json +1 -1
  2. package/dist/server/builtin-plugins/worktree-include/server/copy.ts +162 -16
  3. package/dist/server/server/agent/agent-manager.js +9 -16
  4. package/dist/server/server/agent/providers/claude/agent.d.ts +1 -0
  5. package/dist/server/server/agent/providers/claude/agent.js +41 -7
  6. package/dist/server/server/agent/providers/claude/bypass-approval.d.ts +5 -0
  7. package/dist/server/server/agent/providers/claude/bypass-approval.js +37 -0
  8. package/dist/server/server/agent/providers/claude/model-discovery.d.ts +2 -0
  9. package/dist/server/server/agent/providers/claude/model-discovery.js +55 -11
  10. package/dist/server/server/agent/providers/codex-app-server-agent.js +3 -0
  11. package/dist/server/server/agent/providers/model-label.d.ts +5 -0
  12. package/dist/server/server/agent/providers/model-label.js +21 -0
  13. package/dist/server/server/agent/providers/omp/agent.d.ts +2 -2
  14. package/dist/server/server/agent/providers/omp/agent.js +23 -26
  15. package/dist/server/server/agent/providers/omp/map-omp-model.js +2 -1
  16. package/dist/server/server/agent/providers/omp/rpc-types.d.ts +4 -0
  17. package/dist/server/server/agent/providers/omp/rpc-types.js +8 -0
  18. package/dist/server/server/agent/providers/opencode-agent.js +15 -10
  19. package/dist/server/server/agent/providers/pi/agent.d.ts +1 -2
  20. package/dist/server/server/agent/providers/pi/agent.js +4 -28
  21. package/dist/server/server/agent/timeline-projection.d.ts +6 -0
  22. package/dist/server/server/agent/timeline-projection.js +12 -8
  23. package/dist/server/server/agent/tools/paseo-tools.js +8 -2
  24. package/dist/server/server/bootstrap.js +2 -2
  25. package/dist/server/server/file-observer/index.d.ts +1 -0
  26. package/dist/server/server/file-observer/index.js +14 -1
  27. package/dist/server/server/file-observer/internal/observation.js +4 -0
  28. package/dist/server/server/hub/relationship-controller.js +26 -15
  29. package/dist/server/server/hub/relationship-remote.d.ts +1 -1
  30. package/dist/server/server/hub/relationship-remote.js +2 -2
  31. package/dist/server/server/resolve-worktree-creation-intent.d.ts +1 -1
  32. package/dist/server/server/session/workspace-recovery/workspace-recovery-service.js +30 -4
  33. package/dist/server/server/test-fixtures/reconciliation-registries.d.ts +1 -0
  34. package/dist/server/server/websocket-server.d.ts +5 -0
  35. package/dist/server/server/websocket-server.js +10 -2
  36. package/dist/server/server/workspace-archive-service.js +10 -2
  37. package/dist/server/server/workspace-git-service.d.ts +1 -0
  38. package/dist/server/server/workspace-git-service.js +31 -5
  39. package/dist/server/server/workspace-registry.d.ts +2 -0
  40. package/dist/server/server/workspace-registry.js +2 -0
  41. package/dist/server/terminal/terminal-worker-process.js +16 -14
  42. package/dist/server/terminal/terminal-worker-socket-path.d.ts +15 -1
  43. package/dist/server/terminal/terminal-worker-socket-path.js +57 -9
  44. package/dist/server/terminal-worker/terminal-worker.mjs +51 -23
  45. package/dist/server/utils/checkout-git.js +9 -1
  46. package/dist/server/utils/worktree.d.ts +14 -1
  47. package/dist/server/utils/worktree.js +58 -7
  48. package/dist/server/web-ui/_expo/static/js/web/{index-c6834d1a59b83addc7491f02fc3b6494.js → index-3d51f4c450eeff5bd838a646e9c611f2.js} +24 -24
  49. package/dist/server/web-ui/_expo/static/js/web/index-3d51f4c450eeff5bd838a646e9c611f2.js.br +0 -0
  50. package/dist/server/web-ui/_expo/static/js/web/index-3d51f4c450eeff5bd838a646e9c611f2.js.gz +0 -0
  51. package/dist/server/web-ui/index.html +1 -1
  52. package/dist/server/web-ui/index.html.br +0 -0
  53. package/dist/server/web-ui/index.html.gz +0 -0
  54. package/package.json +7 -7
  55. package/dist/server/web-ui/_expo/static/js/web/index-c6834d1a59b83addc7491f02fc3b6494.js.br +0 -0
  56. package/dist/server/web-ui/_expo/static/js/web/index-c6834d1a59b83addc7491f02fc3b6494.js.gz +0 -0
@@ -65,6 +65,11 @@ const WATCH_RECOVERY_BASE_DELAY_MS = 30000;
65
65
  // restart, which kills running agents. Back off, but keep trying.
66
66
  const WATCH_RECOVERY_MAX_DELAY_MS = 300000;
67
67
  const WATCH_RECOVERY_MAX_BACKOFF_STEPS = 4;
68
+ // A startup scan that missed the subscribe deadline on a CPU-starved host misses it again on the
69
+ // next attempt, and every attempt repeats the full scan. Consecutive setup timeouts therefore
70
+ // keep doubling the recovery delay past the ladder cap, up to an hour.
71
+ const WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS = 3600000;
72
+ const WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS = 7;
68
73
  // Auxiliary reads may reuse cached values within this window; snapshots do not expire on read.
69
74
  const WORKSPACE_GIT_AUXILIARY_READ_TTL_MS = 15000;
70
75
  // Non-forced refresh triggers share this minimum gap to absorb watcher/self-heal bursts; force bypasses it.
@@ -854,7 +859,7 @@ export class WorkspaceGitServiceImpl {
854
859
  fallbackPolling: false,
855
860
  fallbackPollTimer: null,
856
861
  fallbackPollQuietTickCount: 0,
857
- recovery: { attemptCount: 0, timer: null, establishedAt: null },
862
+ recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
858
863
  listeners: new Set(),
859
864
  closed: false,
860
865
  };
@@ -875,9 +880,12 @@ export class WorkspaceGitServiceImpl {
875
880
  let removeAbortListener = () => { };
876
881
  let unsubscribePromise = null;
877
882
  let subscriptionPromise;
883
+ // Abandoning the race is not enough: the observer's startup scan would keep walking the
884
+ // tree after the deadline. Abort it so a timed-out attempt stops costing CPU.
885
+ const setupController = new AbortController();
878
886
  try {
879
887
  subscriptionPromise = this.deps
880
- .subscribe(watchPath, callback, options)
888
+ .subscribe(watchPath, callback, { ...options, signal: setupController.signal })
881
889
  .finally(onSubscribeSettled);
882
890
  }
883
891
  catch (error) {
@@ -894,12 +902,15 @@ export class WorkspaceGitServiceImpl {
894
902
  const timeoutPromise = new Promise((_resolve, reject) => {
895
903
  timeout = setTimeout(() => {
896
904
  outcome = "expired";
897
- reject(new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath));
905
+ const error = new WorkspaceGitWatcherSubscriptionTimeoutError(watchPath);
906
+ setupController.abort(error);
907
+ reject(error);
898
908
  }, WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS);
899
909
  });
900
910
  const disposalPromise = new Promise((_resolve, reject) => {
901
911
  const rejectForDisposal = () => {
902
912
  outcome = "expired";
913
+ setupController.abort(signal.reason);
903
914
  reject(signal.reason);
904
915
  };
905
916
  if (signal.aborted) {
@@ -1016,6 +1027,7 @@ export class WorkspaceGitServiceImpl {
1016
1027
  // `scheduleWorkingTreeWatchRecovery` only resets the ladder once this
1017
1028
  // one has survived long enough to prove itself durable.
1018
1029
  target.recovery.establishedAt = this.deps.now().getTime();
1030
+ target.recovery.setupTimeoutCount = 0;
1019
1031
  if (options?.replaceFallback && target.repoRoot !== null) {
1020
1032
  target.fallbackPolling = false;
1021
1033
  if (target.fallbackPollTimer) {
@@ -1034,6 +1046,7 @@ export class WorkspaceGitServiceImpl {
1034
1046
  return false;
1035
1047
  }
1036
1048
  this.logger.warn({ err: error, cwd: target.cwd }, "Failed to start working tree watcher; using degraded polling");
1049
+ this.noteWatchSetupFailure(target.recovery, error);
1037
1050
  if (!options?.replaceFallback) {
1038
1051
  this.startWorkingTreeWatchFallback(target, "watcher_setup_failed");
1039
1052
  }
@@ -1220,8 +1233,19 @@ export class WorkspaceGitServiceImpl {
1220
1233
  }
1221
1234
  recovery.establishedAt = null;
1222
1235
  recovery.attemptCount += 1;
1223
- return Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1236
+ const ladderDelayMs = Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1224
1237
  2 ** Math.min(recovery.attemptCount - 1, WATCH_RECOVERY_MAX_BACKOFF_STEPS), WATCH_RECOVERY_MAX_DELAY_MS);
1238
+ if (recovery.setupTimeoutCount === 0) {
1239
+ return ladderDelayMs;
1240
+ }
1241
+ const setupTimeoutDelayMs = Math.min(WATCH_RECOVERY_BASE_DELAY_MS *
1242
+ 2 ** Math.min(recovery.setupTimeoutCount - 1, WATCH_SETUP_TIMEOUT_MAX_BACKOFF_STEPS), WATCH_SETUP_TIMEOUT_RECOVERY_MAX_DELAY_MS);
1243
+ return Math.max(ladderDelayMs, setupTimeoutDelayMs);
1244
+ }
1245
+ noteWatchSetupFailure(recovery, error) {
1246
+ if (error instanceof WorkspaceGitWatcherSubscriptionTimeoutError) {
1247
+ recovery.setupTimeoutCount += 1;
1248
+ }
1225
1249
  }
1226
1250
  scheduleWorkingTreeWatchRecovery(target) {
1227
1251
  if (target.closed || target.subscription || target.recovery.timer) {
@@ -1648,7 +1672,7 @@ export class WorkspaceGitServiceImpl {
1648
1672
  fallbackPolling: false,
1649
1673
  fallbackPollTimer: null,
1650
1674
  fallbackPollQuietTickCount: 0,
1651
- recovery: { attemptCount: 0, timer: null, establishedAt: null },
1675
+ recovery: { attemptCount: 0, timer: null, establishedAt: null, setupTimeoutCount: 0 },
1652
1676
  intervalId: null,
1653
1677
  fetchInFlight: false,
1654
1678
  bufferedFetchMetadataEvents: [],
@@ -1765,6 +1789,7 @@ export class WorkspaceGitServiceImpl {
1765
1789
  // subscribe success alone, only record when this subscription was
1766
1790
  // established.
1767
1791
  target.recovery.establishedAt = this.deps.now().getTime();
1792
+ target.recovery.setupTimeoutCount = 0;
1768
1793
  if (options?.replaceFallback) {
1769
1794
  target.fallbackPolling = false;
1770
1795
  if (target.fallbackPollTimer) {
@@ -1786,6 +1811,7 @@ export class WorkspaceGitServiceImpl {
1786
1811
  return false;
1787
1812
  }
1788
1813
  this.logger.warn({ err: error, repoGitRoot: target.repoGitRoot }, "Failed to start repository metadata watcher; using degraded polling");
1814
+ this.noteWatchSetupFailure(target.recovery, error);
1789
1815
  if (!options?.replaceFallback) {
1790
1816
  this.startRepoMetadataFallback(target);
1791
1817
  }
@@ -31,6 +31,7 @@ declare const PersistedWorkspaceRecordSchema: z.ZodObject<{
31
31
  displayName: z.ZodString;
32
32
  title: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
33
33
  branch: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
34
+ head: z.ZodOptional<z.ZodString>;
34
35
  worktreeRoot: z.ZodDefault<z.ZodNullable<z.ZodString>>;
35
36
  baseBranch: z.ZodPipe<z.ZodOptional<z.ZodNullable<z.ZodString>>, z.ZodTransform<string | null, string | null | undefined>>;
36
37
  isPaseoOwnedWorktree: z.ZodDefault<z.ZodBoolean>;
@@ -63,6 +64,7 @@ export interface WorkspaceMutationContext {
63
64
  }
64
65
  export interface WorkspaceArchiveContext {
65
66
  autoArchivedChangeRequestUrl?: string;
67
+ head?: string;
66
68
  }
67
69
  export interface ProjectMutation {
68
70
  kind: "upsert" | "archive" | "remove";
@@ -60,6 +60,7 @@ const PersistedWorkspaceRecordSchema = z.object({
60
60
  .nullable()
61
61
  .optional()
62
62
  .transform((value) => value ?? null),
63
+ head: z.string().optional(),
63
64
  // Exact checkout/worktree root backing cwd. This differs from cwd when the
64
65
  // selected project is a subdirectory inside a repository. Persist it so
65
66
  // archive and recovery do not need the directory to still exist in order to
@@ -395,6 +396,7 @@ export class FileBackedWorkspaceRegistry extends FileBackedRegistry {
395
396
  ...existing,
396
397
  updatedAt: archivedAt,
397
398
  archivedAt,
399
+ head: context?.head,
398
400
  ...(context?.autoArchivedChangeRequestUrl
399
401
  ? { autoArchivedChangeRequestUrl: context.autoArchivedChangeRequestUrl }
400
402
  : {}),
@@ -12,7 +12,7 @@ import { attachFramedSocket } from "./terminal-worker-frames.js";
12
12
  import { createTerminalWorkerProcessInspector } from "./terminal-worker-processes.js";
13
13
  import { TERMINAL_WORKER_MARKER_ARG, terminalWorkerLogPath, terminalWorkerRecordPath, writeTerminalWorkerRecord, } from "./terminal-worker-record.js";
14
14
  import { createTerminalWorkerRecordPublisher } from "./terminal-worker-record-publisher.js";
15
- import { resolveTerminalWorkerSocketPath } from "./terminal-worker-socket-path.js";
15
+ import { listenOnTerminalWorkerSocket } from "./terminal-worker-socket-path.js";
16
16
  import { TERMINAL_WORKER_PROTOCOL_OVERRIDE_ENV, TERMINAL_WORKER_PROTOCOL_VERSION, } from "./terminal-worker-protocol.js";
17
17
  // The terminal worker owns every PTY. It runs detached from the daemon (re-parented by the
18
18
  // launcher below) so a daemon restart, crash or forced kill of the daemon's process tree does
@@ -613,23 +613,25 @@ function runWorker(argv) {
613
613
  }
614
614
  }
615
615
  async function start() {
616
- const socketPath = resolveTerminalWorkerSocketPath({
616
+ const { socketPath, listener } = await listenOnTerminalWorkerSocket({
617
617
  paseoHome: args.paseoHome,
618
618
  workerPid: process.pid,
619
619
  recordId: args.recordId,
620
+ listen: (candidatePath) => {
621
+ if (process.platform !== "win32") {
622
+ rmSync(candidatePath, { force: true });
623
+ }
624
+ const listening = createServer(handleConnection);
625
+ return new Promise((resolve, reject) => {
626
+ listening.once("error", reject);
627
+ listening.listen(candidatePath, () => {
628
+ listening.off("error", reject);
629
+ resolve(listening);
630
+ });
631
+ });
632
+ },
620
633
  });
621
- if (process.platform !== "win32") {
622
- rmSync(socketPath, { force: true });
623
- }
624
- const listening = createServer(handleConnection);
625
- await new Promise((resolve, reject) => {
626
- listening.once("error", reject);
627
- listening.listen(socketPath, () => {
628
- listening.off("error", reject);
629
- resolve();
630
- });
631
- });
632
- server = listening;
634
+ server = listener;
633
635
  if (process.platform !== "win32") {
634
636
  chmodSync(socketPath, PRIVATE_FILE_MODE);
635
637
  }
@@ -6,6 +6,14 @@ export interface TerminalWorkerSocketPathInput {
6
6
  tmpDir?: string;
7
7
  uid?: number;
8
8
  }
9
+ export interface TerminalWorkerSocketListenInput<T> extends TerminalWorkerSocketPathInput {
10
+ /** Binds a fresh listener at the path, removing any stale socket there first. */
11
+ listen: (socketPath: string) => Promise<T>;
12
+ }
13
+ export interface TerminalWorkerSocketListener<T> {
14
+ socketPath: string;
15
+ listener: T;
16
+ }
9
17
  export interface RejectedSocketCandidate {
10
18
  path: string;
11
19
  byteLength: number;
@@ -21,7 +29,13 @@ export declare function terminalWorkerSocketId(paseoHome: string, workerPid: num
21
29
  * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
22
30
  * tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
23
31
  * A shared root is never chmodded: an existing directory there is used only when it is a real
24
- * directory owned by this user with mode 0700.
32
+ * directory owned by this user with mode 0700. It does not bind; the worker listens through
33
+ * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
25
34
  */
26
35
  export declare function resolveTerminalWorkerSocketPath(input: TerminalWorkerSocketPathInput): string;
36
+ /**
37
+ * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
38
+ * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
39
+ */
40
+ export declare function listenOnTerminalWorkerSocket<T>(input: TerminalWorkerSocketListenInput<T>): Promise<TerminalWorkerSocketListener<T>>;
27
41
  //# sourceMappingURL=terminal-worker-socket-path.d.ts.map
@@ -13,10 +13,13 @@ const SOCKET_PATH_BYTE_BUDGET = {
13
13
  };
14
14
  const DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
15
15
  const OWNER_ONLY_MODE = 0o700;
16
+ // Bind errors that mean the directory's filesystem cannot hold a Unix socket. AFS and some other
17
+ // network filesystems pass the directory checks and then refuse AF_UNIX bind with EPERM.
18
+ const SOCKET_UNSUPPORTED_BIND_CODES = new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
16
19
  export class TerminalWorkerSocketPathError extends Error {
17
20
  constructor(rejected, budget) {
18
21
  super([
19
- `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
22
+ `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
20
23
  ...rejected.map((candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`),
21
24
  ].join("\n"));
22
25
  this.name = "TerminalWorkerSocketPathError";
@@ -32,17 +35,64 @@ export function terminalWorkerSocketId(paseoHome, workerPid) {
32
35
  * Picks (and creates) the socket path a worker listens on. Windows uses a named pipe; POSIX
33
36
  * tries $PASEO_HOME/terminal-worker/sock, then <tmpdir>/paseo-<uid>, then /tmp/paseo-<uid>.
34
37
  * A shared root is never chmodded: an existing directory there is used only when it is a real
35
- * directory owned by this user with mode 0700.
38
+ * directory owned by this user with mode 0700. It does not bind; the worker listens through
39
+ * `listenOnTerminalWorkerSocket`, which also skips directories that refuse a socket.
36
40
  */
37
41
  export function resolveTerminalWorkerSocketPath(input) {
38
42
  const platform = input.platform ?? process.platform;
39
- const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
40
43
  if (platform === "win32") {
41
- return `\\\\.\\pipe\\paseo-tw-${id}`;
44
+ return windowsPipePath(input);
42
45
  }
46
+ const budget = socketPathByteBudget(platform);
47
+ const rejected = [];
48
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
49
+ return candidate.path;
50
+ }
51
+ throw new TerminalWorkerSocketPathError(rejected, budget);
52
+ }
53
+ /**
54
+ * Listens on the first candidate path that accepts a socket. A bind refused by the filesystem
55
+ * moves on to the next candidate; any other listen error (EADDRINUSE, ...) is thrown as is.
56
+ */
57
+ export async function listenOnTerminalWorkerSocket(input) {
58
+ const { listen } = input;
59
+ const platform = input.platform ?? process.platform;
60
+ if (platform === "win32") {
61
+ const socketPath = windowsPipePath(input);
62
+ return { socketPath, listener: await listen(socketPath) };
63
+ }
64
+ const budget = socketPathByteBudget(platform);
65
+ const rejected = [];
66
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
67
+ try {
68
+ return { socketPath: candidate.path, listener: await listen(candidate.path) };
69
+ }
70
+ catch (error) {
71
+ const code = error.code;
72
+ if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code))
73
+ throw error;
74
+ rejected.push({
75
+ path: candidate.path,
76
+ byteLength: candidate.byteLength,
77
+ reason: `cannot bind a socket here (${code})`,
78
+ });
79
+ }
80
+ }
81
+ throw new TerminalWorkerSocketPathError(rejected, budget);
82
+ }
83
+ function windowsPipePath(input) {
84
+ return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
85
+ }
86
+ function socketFileId(input) {
87
+ return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
88
+ }
89
+ function socketPathByteBudget(platform) {
90
+ return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
91
+ }
92
+ /** Yields each candidate that fits the budget in an owner-only directory, in order. */
93
+ function* eligibleUnixSocketPaths(input, budget, rejected) {
43
94
  const uid = input.uid ?? process.getuid?.() ?? 0;
44
- const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
45
- const fileName = `tw-${id}.sock`;
95
+ const fileName = `tw-${socketFileId(input)}.sock`;
46
96
  const homeSocketDirectory = path.join(terminalWorkerDirectory(input.paseoHome), "sock");
47
97
  const candidates = [
48
98
  {
@@ -60,7 +110,6 @@ export function resolveTerminalWorkerSocketPath(input) {
60
110
  };
61
111
  }),
62
112
  ];
63
- const rejected = [];
64
113
  const seen = new Set();
65
114
  for (const candidate of candidates) {
66
115
  const socketPath = path.join(candidate.directory, fileName);
@@ -83,9 +132,8 @@ export function resolveTerminalWorkerSocketPath(input) {
83
132
  rejected.push({ path: socketPath, byteLength, reason: problem });
84
133
  continue;
85
134
  }
86
- return socketPath;
135
+ yield { path: socketPath, byteLength };
87
136
  }
88
- throw new TerminalWorkerSocketPathError(rejected, budget);
89
137
  }
90
138
  function prepareSharedRootDirectory(directory, uid) {
91
139
  try {
@@ -22006,11 +22006,12 @@ var SOCKET_PATH_BYTE_BUDGET = {
22006
22006
  };
22007
22007
  var DEFAULT_SOCKET_PATH_BYTE_BUDGET = 103;
22008
22008
  var OWNER_ONLY_MODE = 448;
22009
+ var SOCKET_UNSUPPORTED_BIND_CODES = /* @__PURE__ */ new Set(["EPERM", "EACCES", "EOPNOTSUPP", "ENOTSUP"]);
22009
22010
  var TerminalWorkerSocketPathError = class extends Error {
22010
22011
  constructor(rejected, budget) {
22011
22012
  super(
22012
22013
  [
22013
- `No terminal worker socket path fits ${budget} bytes in an owner-only directory:`,
22014
+ `No terminal worker socket path fits ${budget} bytes in an owner-only directory that accepts a socket:`,
22014
22015
  ...rejected.map(
22015
22016
  (candidate) => ` ${candidate.path} (${candidate.byteLength} bytes): ${candidate.reason}`
22016
22017
  )
@@ -22024,15 +22025,42 @@ function terminalWorkerSocketId(paseoHome, workerPid) {
22024
22025
  const digest = createHash("sha256").update(path4.resolve(paseoHome)).digest("hex");
22025
22026
  return `${digest.slice(0, 16)}-${workerPid}`;
22026
22027
  }
22027
- function resolveTerminalWorkerSocketPath(input) {
22028
+ async function listenOnTerminalWorkerSocket(input) {
22029
+ const { listen } = input;
22028
22030
  const platform = input.platform ?? process.platform;
22029
- const id = terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
22030
22031
  if (platform === "win32") {
22031
- return `\\\\.\\pipe\\paseo-tw-${id}`;
22032
+ const socketPath = windowsPipePath(input);
22033
+ return { socketPath, listener: await listen(socketPath) };
22032
22034
  }
22035
+ const budget = socketPathByteBudget(platform);
22036
+ const rejected = [];
22037
+ for (const candidate of eligibleUnixSocketPaths(input, budget, rejected)) {
22038
+ try {
22039
+ return { socketPath: candidate.path, listener: await listen(candidate.path) };
22040
+ } catch (error51) {
22041
+ const code = error51.code;
22042
+ if (!code || !SOCKET_UNSUPPORTED_BIND_CODES.has(code)) throw error51;
22043
+ rejected.push({
22044
+ path: candidate.path,
22045
+ byteLength: candidate.byteLength,
22046
+ reason: `cannot bind a socket here (${code})`
22047
+ });
22048
+ }
22049
+ }
22050
+ throw new TerminalWorkerSocketPathError(rejected, budget);
22051
+ }
22052
+ function windowsPipePath(input) {
22053
+ return `\\\\.\\pipe\\paseo-tw-${socketFileId(input)}`;
22054
+ }
22055
+ function socketFileId(input) {
22056
+ return terminalWorkerSocketId(input.paseoHome, input.workerPid) + "-" + input.recordId;
22057
+ }
22058
+ function socketPathByteBudget(platform) {
22059
+ return SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
22060
+ }
22061
+ function* eligibleUnixSocketPaths(input, budget, rejected) {
22033
22062
  const uid = input.uid ?? process.getuid?.() ?? 0;
22034
- const budget = SOCKET_PATH_BYTE_BUDGET[platform] ?? DEFAULT_SOCKET_PATH_BYTE_BUDGET;
22035
- const fileName = `tw-${id}.sock`;
22063
+ const fileName = `tw-${socketFileId(input)}.sock`;
22036
22064
  const homeSocketDirectory = path4.join(terminalWorkerDirectory(input.paseoHome), "sock");
22037
22065
  const candidates = [
22038
22066
  {
@@ -22050,7 +22078,6 @@ function resolveTerminalWorkerSocketPath(input) {
22050
22078
  };
22051
22079
  })
22052
22080
  ];
22053
- const rejected = [];
22054
22081
  const seen = /* @__PURE__ */ new Set();
22055
22082
  for (const candidate of candidates) {
22056
22083
  const socketPath = path4.join(candidate.directory, fileName);
@@ -22071,9 +22098,8 @@ function resolveTerminalWorkerSocketPath(input) {
22071
22098
  rejected.push({ path: socketPath, byteLength, reason: problem });
22072
22099
  continue;
22073
22100
  }
22074
- return socketPath;
22101
+ yield { path: socketPath, byteLength };
22075
22102
  }
22076
- throw new TerminalWorkerSocketPathError(rejected, budget);
22077
22103
  }
22078
22104
  function prepareSharedRootDirectory(directory, uid) {
22079
22105
  try {
@@ -22651,23 +22677,25 @@ function runWorker(argv) {
22651
22677
  }
22652
22678
  }
22653
22679
  async function start() {
22654
- const socketPath = resolveTerminalWorkerSocketPath({
22680
+ const { socketPath, listener } = await listenOnTerminalWorkerSocket({
22655
22681
  paseoHome: args.paseoHome,
22656
22682
  workerPid: process.pid,
22657
- recordId: args.recordId
22658
- });
22659
- if (process.platform !== "win32") {
22660
- rmSync2(socketPath, { force: true });
22661
- }
22662
- const listening = createServer(handleConnection);
22663
- await new Promise((resolve4, reject) => {
22664
- listening.once("error", reject);
22665
- listening.listen(socketPath, () => {
22666
- listening.off("error", reject);
22667
- resolve4();
22668
- });
22683
+ recordId: args.recordId,
22684
+ listen: (candidatePath) => {
22685
+ if (process.platform !== "win32") {
22686
+ rmSync2(candidatePath, { force: true });
22687
+ }
22688
+ const listening = createServer(handleConnection);
22689
+ return new Promise((resolve4, reject) => {
22690
+ listening.once("error", reject);
22691
+ listening.listen(candidatePath, () => {
22692
+ listening.off("error", reject);
22693
+ resolve4(listening);
22694
+ });
22695
+ });
22696
+ }
22669
22697
  });
22670
- server = listening;
22698
+ server = listener;
22671
22699
  if (process.platform !== "win32") {
22672
22700
  chmodSync3(socketPath, PRIVATE_FILE_MODE);
22673
22701
  }
@@ -1,6 +1,6 @@
1
1
  import { MAX_RELAY_WEBSOCKET_MESSAGE_BYTES } from "@getpaseo/protocol/websocket-message-limit";
2
2
  import { resolve, dirname, basename } from "path";
3
- import { open as openFile, readFile, stat as statFile, mkdtemp, copyFile, realpath, access, rm, } from "fs/promises";
3
+ import { open as openFile, readFile, stat as statFile, mkdtemp, copyFile, utimes, realpath, access, rm, } from "fs/promises";
4
4
  import { tmpdir } from "node:os";
5
5
  import { setImmediate } from "node:timers/promises";
6
6
  import { TTLCache } from "@isaacs/ttlcache";
@@ -2536,6 +2536,12 @@ export async function prepareAllChangesIndex(cwd, baseRef) {
2536
2536
  }
2537
2537
  // write-tree rewrites its index. A private snapshot prevents an index read from
2538
2538
  // invalidating the observation that requested it.
2539
+ //
2540
+ // Git re-reads a file whose stat matches its index entry only when the entry is
2541
+ // not older than the index file ("racy git"). A fresh copy would be newer than
2542
+ // every entry, so a same-size edit made in the tick the index was written would
2543
+ // read as unchanged. The copy takes the source's mtime, read before copying and
2544
+ // rounded down to the second, so it is never later than the source.
2539
2545
  export async function snapshotComparisonIndex(cwd) {
2540
2546
  const directory = await mkdtemp(resolve(tmpdir(), "paseo-comparison-index-"));
2541
2547
  const indexFile = resolve(directory, "index");
@@ -2548,7 +2554,9 @@ export async function snapshotComparisonIndex(cwd) {
2548
2554
  if (!source)
2549
2555
  throw new Error("Git did not return an index path");
2550
2556
  try {
2557
+ const { atime, mtimeMs } = await statFile(source);
2551
2558
  await copyFile(source, indexFile);
2559
+ await utimes(indexFile, atime, Math.floor(mtimeMs / 1000));
2552
2560
  }
2553
2561
  catch (error) {
2554
2562
  if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT")
@@ -108,6 +108,10 @@ export type WorktreeSource = {
108
108
  kind: "restore";
109
109
  branchName: string;
110
110
  baseRef: string | null;
111
+ } | {
112
+ kind: "restore-commit";
113
+ commit: string;
114
+ baseRef: string;
111
115
  } | {
112
116
  kind: "restore-from-base";
113
117
  baseRef: string;
@@ -226,6 +230,8 @@ export interface DeletePaseoWorktreeOptions {
226
230
  worktreesBaseRoot?: string;
227
231
  registryProven?: boolean;
228
232
  }
233
+ export declare function readWorktreeHead(worktreePath: string): Promise<string | null>;
234
+ export declare function readWorktreeHeadReference(worktreePath: string): Promise<string | null>;
229
235
  export declare function deletePaseoWorktree({ cwd, worktreePath, teardownCwds, worktreeSlug, worktreesRoot, paseoHome, worktreesBaseRoot, registryProven, }: DeletePaseoWorktreeOptions): Promise<void>;
230
236
  export declare function rollbackCreatedPaseoWorktree(options: DeletePaseoWorktreeOptions, cause: unknown): Promise<never>;
231
237
  /** Resolve the default placement once, before presenting it to creation hooks. */
@@ -233,5 +239,12 @@ export declare function resolveDefaultWorktreePath(options: Pick<CreateWorktreeO
233
239
  /**
234
240
  * Create a git worktree with proper naming conventions
235
241
  */
236
- export declare const createWorktree: ({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, }: CreateWorktreeOptions) => Promise<CreatedWorktree>;
242
+ export declare function createWorktree(options: CreateWorktreeOptions & {
243
+ source: Exclude<WorktreeSource, {
244
+ kind: "restore-commit";
245
+ }>;
246
+ }): Promise<CreatedWorktree>;
247
+ export declare function createWorktree(options: CreateWorktreeOptions): Promise<Omit<CreatedWorktree, "branchName"> & {
248
+ branchName: string | null;
249
+ }>;
237
250
  //# sourceMappingURL=worktree.d.ts.map
@@ -789,6 +789,35 @@ async function assertWorktreeBelongsToRepo(cwd, worktreePath) {
789
789
  throw new Error("Refusing to delete non-Paseo worktree");
790
790
  }
791
791
  }
792
+ export async function readWorktreeHead(worktreePath) {
793
+ if (!(await pathExists(join(worktreePath, ".git"))))
794
+ return null;
795
+ try {
796
+ const { stdout } = await runGitCommand(["rev-parse", "--verify", "HEAD^{commit}"], {
797
+ cwd: worktreePath,
798
+ });
799
+ return stdout.trim();
800
+ }
801
+ catch {
802
+ return null;
803
+ }
804
+ }
805
+ export async function readWorktreeHeadReference(worktreePath) {
806
+ if (!(await pathExists(join(worktreePath, ".git"))))
807
+ return null;
808
+ try {
809
+ const result = await runGitCommand(["symbolic-ref", "--quiet", "HEAD"], {
810
+ cwd: worktreePath,
811
+ acceptExitCodes: [0, 1],
812
+ });
813
+ if (result.exitCode === 0)
814
+ return result.stdout.trim();
815
+ return readWorktreeHead(worktreePath);
816
+ }
817
+ catch {
818
+ return null;
819
+ }
820
+ }
792
821
  export async function deletePaseoWorktree({ cwd, worktreePath, teardownCwds, worktreeSlug, worktreesRoot, paseoHome, worktreesBaseRoot, registryProven, }) {
793
822
  if (!worktreePath && !worktreeSlug) {
794
823
  throw new Error("worktreePath or worktreeSlug is required");
@@ -835,6 +864,12 @@ export async function deletePaseoWorktree({ cwd, worktreePath, teardownCwds, wor
835
864
  teardownCwd,
836
865
  });
837
866
  }
867
+ const commit = await readWorktreeHead(resolvedWorktree);
868
+ if (commit) {
869
+ await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
870
+ cwd: resolvedWorktree,
871
+ });
872
+ }
838
873
  }
839
874
  if (cwd) {
840
875
  try {
@@ -957,10 +992,7 @@ export async function resolveDefaultWorktreePath(options) {
957
992
  candidate = `${original}-${suffix++}`;
958
993
  return candidate;
959
994
  }
960
- /**
961
- * Create a git worktree with proper naming conventions
962
- */
963
- export const createWorktree = async ({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, }) => {
995
+ export async function createWorktree({ cwd, source, worktreeSlug, paseoHome, worktreesRoot, worktreePath: explicitWorktreePath, }) {
964
996
  const branchesBefore = source.kind === "checkout-branch" ||
965
997
  source.kind === "checkout-change-request" ||
966
998
  source.kind === "checkout-github-pr"
@@ -981,14 +1013,14 @@ export const createWorktree = async ({ cwd, source, worktreeSlug, paseoHome, wor
981
1013
  timeout: 120000,
982
1014
  });
983
1015
  worktreePath = await normalizePathForOwnership(worktreePath);
984
- if (sourcePlan.pushRemote) {
1016
+ if (sourcePlan.pushRemote && sourcePlan.branchName) {
985
1017
  await configureWorktreePushRemote({
986
1018
  cwd,
987
1019
  branchName: sourcePlan.branchName,
988
1020
  remote: sourcePlan.pushRemote,
989
1021
  });
990
1022
  }
991
- if (sourcePlan.trackingRemote) {
1023
+ if (sourcePlan.trackingRemote && sourcePlan.branchName) {
992
1024
  await configureWorktreeTrackingRemote({
993
1025
  cwd,
994
1026
  branchName: sourcePlan.branchName,
@@ -1017,7 +1049,7 @@ export const createWorktree = async ({ cwd, source, worktreeSlug, paseoHome, wor
1017
1049
  }
1018
1050
  throw error;
1019
1051
  }
1020
- };
1052
+ }
1021
1053
  async function resolveRestoredWorktreeSourcePlan(cwd, source) {
1022
1054
  await validateGitBranchName(cwd, source.branchName);
1023
1055
  await ensureLocalBranch(cwd, source.branchName);
@@ -1044,6 +1076,23 @@ async function resolveRestoredWorktreeSourcePlan(cwd, source) {
1044
1076
  addArguments: [source.branchName],
1045
1077
  };
1046
1078
  }
1079
+ async function resolveRestoredCommitSourcePlan(cwd, source) {
1080
+ let exactBase;
1081
+ if (isQualifiedRef(source.baseRef)) {
1082
+ try {
1083
+ exactBase = await resolveBaseBranchForWorktree(cwd, source.baseRef);
1084
+ }
1085
+ catch {
1086
+ // Restore the saved commit even when its comparison ref no longer exists.
1087
+ }
1088
+ }
1089
+ return {
1090
+ branchName: null,
1091
+ metadataBaseRefName: normalizeRequiredBaseBranch(source.baseRef),
1092
+ ...(exactBase ? { metadataBaseRef: exactBase } : {}),
1093
+ addArguments: ["--detach", source.commit],
1094
+ };
1095
+ }
1047
1096
  async function resolveRestoredWorktreeFromBasePlan(cwd, source) {
1048
1097
  await validateGitBranchName(cwd, source.branchName);
1049
1098
  const baseRef = await resolveBaseBranchForWorktree(cwd, source.baseRef);
@@ -1082,6 +1131,8 @@ async function resolveWorktreeSourcePlan({ cwd, source, desiredSlug, }) {
1082
1131
  return resolveBranchOffWorktreeSourcePlan(cwd, source, desiredSlug);
1083
1132
  case "restore":
1084
1133
  return resolveRestoredWorktreeSourcePlan(cwd, source);
1134
+ case "restore-commit":
1135
+ return resolveRestoredCommitSourcePlan(cwd, source);
1085
1136
  case "restore-from-base":
1086
1137
  return resolveRestoredWorktreeFromBasePlan(cwd, source);
1087
1138
  case "checkout-branch": {