Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: exclude absorbed upstream changes from goal-fidelity reviews (#7690)

[._.]/ Adam Eivy11c2c1ea75bf
diff --git a/server/lib/README.md b/server/lib/README.md
index c8027e2995..b2f3fe25ad 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -387,7 +387,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `frameQuality.js` | Scores decoded video frames so a chained render can CHOOSE its continuation anchor instead of taking whatever an end-seek lands on. `scoreFrame({width,height,data},{recency})` combines three terms over a raw single-channel buffer: log-compressed `gradientVariance` (focus), distance of `meanLuma` from mid-grey (exposure penalty, which rejects a fade-to-black or a blown highlight), and a small linear recency bonus that keeps the anchor near the cut when candidates are comparably clean. Usability and ranking are deliberately separate: `usable` gates on raw gradient variance against `MIN_SIGNAL_VARIANCE` alone, so only a mathematically degenerate frame is rejected and a legitimately dark low-key tail still qualifies — the same contract `imageFrameStats.js` keeps. Gating on the composite score instead would reject every night scene on the exposure term. `TAIL_WINDOW_SECONDS` is capped at the reach of the single `-sseof -1.0` seek this replaces: focus is systematically highest at the OLDEST candidate, so a wider window would widen the backward jump at each chain seam rather than tightening it. `pickBestFrame(paths)` decodes each candidate through `sharp` and returns the winner (or `null` when nothing decodes or every candidate is degenerate, so the caller degrades rather than failing a render); its `index` is the position in the array AS PASSED, because the caller turns that into the anchor's time offset. `MAX_CANDIDATES` is derived from the window, never set independently — the ffmpeg-side `-frames:v` cap truncates from the NEWEST end, exactly the frames recency prefers. `TAIL_WINDOW_SECONDS` / `CANDIDATE_FPS` / `MAX_CANDIDATES` define the window the caller decodes from. Consumer: `services/videoGen/local.js#extractLastFrame`. |
| `ffmpegRenderGuard.js` | `attachFfmpegRenderGuard(proc, {label, onSpawnError, onProcessError, onClose})` — shared spawn-state tracking + exactly-once `terminal` guard + pre-vs-post-spawn dispatch for the SSE ffmpeg render runners (musicVideo/render + videoTimeline/local). Owns the 'spawn'/'error'/'close' wiring (only the pre-spawn 'error' or 'close' finalizes; a post-spawn 'error' records only) and takes the service-specific finalize bodies as callbacks so each renderer keeps its own project-status/history behavior. |
| `gitArgs.js` | `PROTECTED_BRANCHES`, `validateFilePaths(files)`, `isGitStageableFilePath(file)` — pure command-arg builders/validators for `git.js` (reject injection/traversal in staged paths). `isGitStageableFilePath` is `validateFilePaths`' non-throwing twin, for callers that must refuse an unstageable path BEFORE writing the file rather than 500 on the commit. |
-| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` / `runWindowDiff(workspacePath, sinceMs, {maxChars})` — the run-window git probes: how many commits landed with a COMMITTER date inside a run's window (so a rebase/commit by the agent counts, a merely-pulled remote commit does not). The single machine-checkable "did this run commit anything?" primitive shared by finalize's success-criteria evaluation, run completion, runner completion, and orphan recovery — it replaced the unsatisfiable task-id commit-marker grep (#3637). Non-throwing: a non-repo, empty repo, or git timeout is 0. `runWindowDiff` is the diff half — the accumulated `<base>..HEAD` text for everything the run committed, base resolved with the same committer-date window so the two probes can't disagree about which commits are the run's. Every failure is a `reason` string with a `null` diff, never `''`: a git that could not answer must not read as a run that changed nothing. |
+| `gitCommitProbe.js` | `commitsSince(workspacePath, sinceMs)` / `committedDuringRun(workspacePath, sinceMs)` count commits by COMMITTER date for completion criteria. `runWindowDiff(workspacePath, sinceMs, {maxChars})` returns accumulated `<base>..HEAD` text, advancing the pre-window base to the remote-default merge base when ancestry proves it newer, so absorbed upstream changes are not graded as agent work (#7690). It uses local refs only; already-upstream agent commits are intentionally excluded. Old agent records still need only their timestamp, and an unavailable remote-default ref retains the time-window fallback. A failed comparison or unordered bases returns a `reason` with a `null` diff; `''` means a valid empty diff. The returned `base` names the actual comparison commit. |
| `gitForge.js` | `parseGitRemote`, `parseGitHubOwnerFromRemote`, `pickGhAccountForOwner`, `detectForgeCli`, `parsePullRequestUrl` — GitHub/GitLab remote + PR/MR URL parsers and forge/account selectors used by `git.js`. Pure except that `parseGitRemote` canonicalizes an ssh `Host` alias through `sshHostAlias.js`. |
| `sshHostAlias.js` | `resolveSshHostAlias`, `parseSshHostAliases` — resolves a personal SSH `Host` alias (`git@github-acme:…`, backed by `HostName github.com` in `~/.ssh/config`) to the host a remote actually connects to. Every remote-URL host parser (`gitForge.parseGitRemote`, `gitRemote.parseGitRemoteUrl`, `workTracker.hostFromOriginUrl`) canonicalizes through it, so multi-account checkouts classify as GitHub instead of an unreachable unknown host. |
| `gitOutputParsers.js` | `parseStatus`, `parseDiffStat`, `parseBranchVerboseLine`, `parseSubmoduleStatusLine`/`SUBMODULE_STATUS_RE`, `extractAgentSummary` — pure parsers turning git command output into structured data for `git.js`. `extractAgentSummary` anchors on `agentOutputMarkers`' completion marker so a TUI agent's PR body carries its sentinel summary, not the lifecycle telemetry above it. `isBenignConcurrentFetchRefRace(stderr)` reads a non-zero `git fetch` as a SUCCESS when its only failure is a lost compare-and-swap whose refs already hold the fetched commits — the routine outcome when the Git tab, `getRemoteBranches`, and CoS agent worktrees fetch one `.git` at once. |
@@ -401,7 +401,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and then reported it unrunnable, advising a restart that inherits the same PATH. Called at boot in BOTH processes that spawn provider CLIs (`services/bootstrap.js`, `cos-runner/index.js`) and again from `providerRuntimeInstaller.js`'s probe, because on a first install the prefix directory did not exist when boot looked. |
| `processEnv.js` | `stripDebugMallocEnv(env)` / `safeChildProcessEnv(extra)` — drop macOS `Malloc*` debug env vars before spawning a child. `safeChildProcessOptions(options)` adds that sanitized environment plus `windowsHide: true`, preventing detached PM2 subprocesses from opening transient Windows console UI; `buildSafeCliBaseEnv(env, provider)` allowlists runtime/delivery essentials and only the selected CLI's ambient provider auth before an AI CLI inherits the server environment. Route Node→Python and other background CLI spawns through the process helpers. Also `whichFirst(name)` — first-hit `which`/`where` PATH probe (safe options, 5s timeout) returning the absolute binary path or `null`; `whichFirstSync(name)` provides the same contract without the await; `findCommandOnPath(name, { env, cwd })` resolves an executable from the exact child environment without needing `which` itself on that PATH. `adoptPathDirs(dirs)` appends the ones that exist and are not already there to THIS process's `process.env.PATH` (case-insensitively on Windows), which fixes this process AND every child, since the env builders above derive from `process.env` — the only fix that reaches a CLI launched by BARE NAME through node-pty. Shared by `npmGlobalBin.js` and `services/llamaServerManager.js`'s winget-shim adoption. |
| `branchUpstreamGuard.js` | `enforceSafeBranchUpstream(repo, branch)` / `readBranchUpstream` / `isSafeBranchUpstream` — the agent-branch upstream invariant (#4172): a branch handed to a CoS agent tracks either NOTHING or its OWN ref, never `refs/heads/main`. `git worktree add -b <b> <path> origin/main` does not leave the branch untracked — `branch.autoSetupMerge` records `merge=refs/heads/main` — and `/do:pr` derives its push destination from that config (`git push <remote> HEAD:<merge>`), so the agent's work lands straight on the default branch with no PR. Prevention is `--no-track` at the `worktreeManager.js` creation sites; this is the backstop that also REPAIRS branches created before the fix (drops the bogus upstream, logs it) and throws only if the repair doesn't take. Fails CLOSED: `readBranchUpstream` returns `null` for could-not-read (distinct from `''` = genuinely unset), and an unverifiable upstream is refused rather than waved through — `worktreeManager.js` undoes the `worktree add` on refusal so the throw can't strand a tree. Pairs with `primaryCheckoutGuard.js`, which catches the other way agent work reaches `main`. |
-| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. |
+| `primaryCheckoutGuard.js` | `capturePrimaryCheckoutState(path)` / `detectPrimaryCheckoutDrift(baseline, {agentBranch})` + `PRIMARY_CHECKOUT_MUTATED_REASON`/`_CATEGORY` — the branch-jack detector (#3680): stamps the PRIMARY checkout's branch + HEAD onto a worktree agent's metadata at spawn (`agentLifecycle.js`) and re-reads it in the shared finalize path (`agentFinalization.js`), so a worktree-isolated agent that commits to the primary is recorded as a FAILURE naming the drifted branch, the commit count, and the `git reset --hard` recovery — instead of a silent "completed". Detect-and-report only: the reset discards commits, so it stays a human decision. Non-throwing (runs outside the request lifecycle); an unreadable checkout reports no drift rather than inventing one. `resolveRemoteDefaultRef(path)` resolves local origin/HEAD, origin/main, then origin/master to `{ref, sha}` or null without fetching; also used by run-window diffs. |
| `ptySpawnDiagnostics.js` | `diagnosePtySpawnFailure(err, {cwd, probeCwd, runtimeProbe})` + `probePtyRuntime(pty, cwd)` and the `PTY_UNAVAILABLE_PREFIX` / `PTY_WORKSPACE_MISSING_PREFIX` markers — turns node-pty’s one opaque `posix_spawn failed: No such file or directory` into a named fault. The executable is already cleared upstream (PATH resolve + `--version` probe), so a throw is either a `cwd` that vanished (cheap `existsSync`) or a PTY layer that cannot fork AT ALL — proven by re-forking a known-good command in a known-good directory; `diagnosed: false` means neither matched, and the caller re-throws rather than inventing a cause. **Retry policy is the caller’s and the two faults differ:** `agentTuiSpawning.js` matches only the PTY-layer prefix, mapping it to the actionable `runner-pty-unavailable` so the task blocks once with the repair, while a reaped workspace falls through to the retrying `spawn-rejected` because the next attempt provisions a fresh worktree. The motivating outage: an `npm ci` inside a CoS worktree emptied the primary checkout’s `server/node_modules` through a symlink, deleting the `spawn-helper` binary node-pty execs on every fork, while the already-loaded binding left the runner process itself looking healthy. |
| `pythonSetup.js` | Python venv / runner setup helpers. |
| `vttTranscript.js` | WebVTT/SRT → readable prose. `vttToPlainText(vtt)` (paragraph-joined transcript), `vttToLines(vtt)` (cleaned caption lines), `cleanCaptionLine(line)`. Collapses YouTube auto-captions' rolling repetition and strips inline `<c>`/timestamp markup. Used by the brain YouTube ingest. |
diff --git a/server/lib/gitCommitProbe.js b/server/lib/gitCommitProbe.js
index 2e4eaaee06..0bd2fe39aa 100644
--- a/server/lib/gitCommitProbe.js
+++ b/server/lib/gitCommitProbe.js
@@ -2,12 +2,11 @@
* Run-window git probes — the machine-checkable "what did this run leave
* behind?" primitives (#3637).
*
- * Two questions share one window definition, so they share one module: `did it
+ * Two questions share one module: `did it
* commit anything?` (the success criterion) and `what did it commit?` (the
- * accumulated diff the goal-fidelity review reads, #5994). Splitting them would
- * duplicate the "commits stamped inside the window are this run's" rule, and a
- * drift between the two would mean the gate reviewed a different set of commits
- * than the criterion counted.
+ * accumulated diff the goal-fidelity review reads, #5994). The count uses
+ * committer dates; the diff additionally excludes absorbed upstream history,
+ * which dates alone cannot attribute to the run (#7690).
*
* `commitsSince` replaced the `[task-<id>]` commit-marker grep that used to live in
* `agentRunTracking.js`: nothing in PortOS ever emitted that marker (the root
@@ -22,6 +21,7 @@
*/
import { execGit } from './execGit.js';
+import { resolveRemoteDefaultRef } from './primaryCheckoutGuard.js';
/**
* Count commits reachable from HEAD whose COMMITTER date falls inside the run
@@ -89,17 +89,23 @@ export async function committedDuringRun(workspacePath, sinceMs) {
}
/**
- * The ACCUMULATED diff of everything this run committed — the base being the
- * newest commit that predates the run window, so a run that landed five commits
- * is reviewed as the one change it actually made rather than five partial ones.
+ * The accumulated run-window diff, excluding history absorbed from the remote
+ * default branch. Start with the newest pre-window commit and advance to the
+ * remote-default merge base only when ancestry proves it is newer. Never use
+ * the remote tip directly: it can include work this checkout has not absorbed.
*
* Non-throwing, like its siblings, and every failure is a REASON rather than an
* empty diff. That distinction is the whole point: `''` would read as "this run
* changed nothing", and a consumer gating on the diff must never confuse a git
* that could not answer with a run that did nothing.
*
- * `--before` resolves the base off COMMITTER date, matching `commitsSince`'s
- * `--since` — so the two probes always agree on which commits belong to the run.
+ * No new persisted agent field is required: old records still supply startedAt.
+ * Without a resolvable local remote-default ref, retain the time-based fallback.
+ * This deliberately excludes agent work already reachable from that remote;
+ * it is a review of the remaining change, not exact authorship attribution.
+ * No fetch or other repository mutation is performed.
+ *
+ * `--before` resolves the initial base off COMMITTER date.
* A repo whose entire history falls inside the window has no such base; that is
* reported rather than diffed against the empty tree, because on a real
* workspace it means the window is wrong, not that the run wrote the repo.
@@ -125,9 +131,38 @@ export async function runWindowDiff(workspacePath, sinceMs, { maxChars = 60_000
{ ignoreExitCode: true, timeout: 10_000 },
).catch(() => null);
if (!baseResult || baseResult.exitCode !== 0) return decline('could not resolve the run window base commit');
- const base = baseResult.stdout.trim();
+ let base = baseResult.stdout.trim();
if (!base) return decline('no commit predates the run window');
+ const upstream = await resolveRemoteDefaultRef(workspacePath);
+ if (upstream) {
+ const mergeBaseResult = await execGit(
+ ['merge-base', 'HEAD', upstream.sha], workspacePath,
+ { ignoreExitCode: true, timeout: 10_000 },
+ ).catch(() => null);
+ const upstreamBase = mergeBaseResult?.exitCode === 0 ? mergeBaseResult.stdout.trim() : null;
+ if (!upstreamBase) return decline('could not resolve the absorbed upstream base');
+ if (upstreamBase !== base) {
+ const ancestry = await execGit(
+ ['merge-base', '--is-ancestor', base, upstreamBase], workspacePath,
+ { ignoreExitCode: true, timeout: 10_000 },
+ ).catch(() => null);
+ if (ancestry?.exitCode === 0) {
+ base = upstreamBase;
+ } else if (ancestry?.exitCode === 1) {
+ // A later pre-window agent commit must stay excluded. If neither base
+ // contains the other, one two-tree diff cannot exclude both histories.
+ const reverse = await execGit(
+ ['merge-base', '--is-ancestor', upstreamBase, base], workspacePath,
+ { ignoreExitCode: true, timeout: 10_000 },
+ ).catch(() => null);
+ if (reverse?.exitCode !== 0) return decline('run window and upstream bases could not be ordered');
+ } else {
+ return decline('could not compare the run window and upstream bases');
+ }
+ }
+ }
+
// `--no-ext-diff` so a user's configured external difftool can't replace the
// unified text (or block on a GUI); `--no-color` so escape codes don't reach
// a model reading it as source.
diff --git a/server/lib/gitCommitProbe.test.js b/server/lib/gitCommitProbe.test.js
index 0267b6fc92..ddc6853008 100644
--- a/server/lib/gitCommitProbe.test.js
+++ b/server/lib/gitCommitProbe.test.js
@@ -1,13 +1,24 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { writeFile } from 'node:fs/promises';
+import { join } from 'node:path';
vi.mock('./execGit.js', () => ({ execGit: vi.fn() }));
+vi.mock('./primaryCheckoutGuard.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ resolveRemoteDefaultRef: vi.fn(),
+}));
import { execGit } from './execGit.js';
+import { resolveRemoteDefaultRef } from './primaryCheckoutGuard.js';
import { commitsSince, committedDuringRun, runWindowDiff, toEpochMs } from './gitCommitProbe.js';
+import { makeGitSandbox, destroyGitSandbox, SKIP_HEAVY_INTEGRATION } from './gitTestRepo.js';
const SINCE = Date.parse('2026-08-08T18:23:30.000Z');
-beforeEach(() => vi.clearAllMocks());
+beforeEach(() => {
+ vi.resetAllMocks();
+ vi.mocked(resolveRemoteDefaultRef).mockResolvedValue(null);
+});
describe('commitsSince (#3637)', () => {
it('counts commits inside the run window, scoped by committer date', async () => {
@@ -120,8 +131,8 @@ describe('runWindowDiff (#5994)', () => {
truncated: false,
reason: null,
});
- // The window is resolved on committer date, exactly as `commitsSince` filters
- // on it — the two probes must never disagree about which commits are the run's.
+ // Older persisted records still work with only a timestamp, and a checkout
+ // without a remote default retains the original time-window fallback.
expect(execGit).toHaveBeenNthCalledWith(1,
['rev-list', '-n', '1', '--before=2026-08-08T18:23:30.000Z', 'HEAD'],
'/tmp/ws',
@@ -163,4 +174,95 @@ describe('runWindowDiff (#5994)', () => {
expect(result.diff).toContain('[diff truncated]');
expect(result.diff.length).toBeLessThan(200);
});
+
+ it('declines an unavailable upstream comparison instead of grading an unfiltered diff', async () => {
+ vi.mocked(resolveRemoteDefaultRef).mockResolvedValue({ ref: 'origin/main', sha: 'c'.repeat(40) });
+ vi.mocked(execGit).mockResolvedValueOnce(baseOk).mockRejectedValueOnce(new Error('timed out'));
+ expect(await runWindowDiff('/tmp/ws', SINCE)).toMatchObject({
+ diff: null, reason: 'could not resolve the absorbed upstream base',
+ });
+ expect(execGit.mock.calls.some(([args]) => args[0] === 'diff')).toBe(false);
+ });
+
+ it('declines incomparable pre-window agent and absorbed upstream bases', async () => {
+ vi.mocked(resolveRemoteDefaultRef).mockResolvedValue({ ref: 'origin/main', sha: 'c'.repeat(40) });
+ vi.mocked(execGit)
+ .mockResolvedValueOnce(baseOk)
+ .mockResolvedValueOnce({ exitCode: 0, stdout: 'c'.repeat(40), stderr: '' })
+ .mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: '' })
+ .mockResolvedValueOnce({ exitCode: 1, stdout: '', stderr: '' });
+ expect(await runWindowDiff('/tmp/ws', SINCE)).toMatchObject({
+ diff: null, reason: 'run window and upstream bases could not be ordered',
+ });
+ expect(execGit.mock.calls.some(([args]) => args[0] === 'diff')).toBe(false);
+ });
+});
+
+describe.skipIf(SKIP_HEAVY_INTEGRATION)('runWindowDiff real git history (#7690)', () => {
+ it.each(['rebase', 'merge'])('excludes upstream absorbed by %s while retaining all run commits', async (operation) => {
+ const { execGit: realExecGit } = await vi.importActual('./execGit.js');
+ const { resolveRemoteDefaultRef: realResolveRemoteDefaultRef } = await vi.importActual('./primaryCheckoutGuard.js');
+ vi.mocked(execGit).mockImplementation(realExecGit);
+ vi.mocked(resolveRemoteDefaultRef).mockImplementation(realResolveRemoteDefaultRef);
+ const sandbox = await makeGitSandbox();
+ const git = (args) => realExecGit(args, sandbox.repo);
+ const commit = async (file, text, date) => {
+ vi.stubEnv('GIT_COMMITTER_DATE', date);
+ await writeFile(join(sandbox.repo, file), text);
+ await git(['add', file]);
+ await git(['commit', '--date', date, '-m', 'fixture change']);
+ };
+ try {
+ const before = '2026-08-08T18:00:00Z';
+ vi.stubEnv('GIT_COMMITTER_DATE', before);
+ await git(['commit', '--amend', '--no-edit', '--date', before]);
+ const initial = (await git(['rev-parse', 'HEAD'])).stdout.trim();
+ // A nonstandard default verifies origin/HEAD resolution, including on a
+ // detached agent HEAD. Ref updates are local: no network or live remote.
+ await git(['branch', '-m', 'trunk']);
+ await git(['update-ref', 'refs/remotes/origin/trunk', initial]);
+ await git(['symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/trunk']);
+ await git(['checkout', '-b', 'agent']);
+ await commit('agent.txt', 'first change\n', '2026-08-08T18:24:00Z');
+ await git(['checkout', 'trunk']);
+ await commit('upstream.txt', 'other work\n', '2026-08-08T18:25:00Z');
+ const absorbed = (await git(['rev-parse', 'HEAD'])).stdout.trim();
+ await git(['update-ref', 'refs/remotes/origin/trunk', absorbed]);
+ await git(['checkout', 'agent']);
+ vi.stubEnv('GIT_COMMITTER_DATE', '2026-08-08T18:26:00Z');
+ await git(operation === 'rebase' ? ['rebase', 'trunk'] : ['merge', '--no-edit', 'trunk']);
+ await commit('agent.txt', 'first change\nsecond change\n', '2026-08-08T18:27:00Z');
+ await git(['checkout', '--detach']);
+ // A later upstream commit has NOT been absorbed; diffing against the
+ // remote tip would manufacture a deletion of this file.
+ const runHead = (await git(['rev-parse', 'HEAD'])).stdout.trim();
+ await git(['checkout', 'trunk']);
+ await commit('future-upstream.txt', 'not absorbed\n', '2026-08-08T18:28:00Z');
+ await git(['update-ref', 'refs/remotes/origin/trunk', 'HEAD']);
+ await git(['checkout', '--detach', runHead]);
+ // Characterize the old probe: its date-only diff contains unrelated work.
+ const oldBase = (await git(['rev-list', '-n', '1', '--before=2026-08-08T18:23:30Z', 'HEAD'])).stdout.trim();
+ expect((await git(['diff', `${oldBase}..HEAD`])).stdout).toContain('upstream.txt');
+ const result = await runWindowDiff(sandbox.repo, SINCE);
+ expect(result).toMatchObject({ base: absorbed, reason: null, truncated: false });
+ expect(result.diff).toContain('+first change');
+ expect(result.diff).toContain('+second change');
+ expect(result.diff).not.toContain('upstream.txt');
+ // A legacy record whose run started later must not re-include earlier
+ // agent work just because the remote-default merge base is older.
+ const later = await runWindowDiff(sandbox.repo, Date.parse('2026-08-08T18:26:30Z'));
+ expect(later.reason).toBeNull();
+ expect(later.diff).toContain('+second change');
+ expect(later.diff).not.toContain('+first change');
+ expect(later.diff).not.toContain('upstream.txt');
+ await git(['symbolic-ref', '--delete', 'refs/remotes/origin/HEAD']);
+ await git(['update-ref', '-d', 'refs/remotes/origin/trunk']);
+ const legacyFallback = await runWindowDiff(sandbox.repo, SINCE);
+ expect(legacyFallback).toMatchObject({ base: oldBase, reason: null });
+ expect(legacyFallback.diff).toContain('upstream.txt');
+ } finally {
+ vi.unstubAllEnvs();
+ await destroyGitSandbox(sandbox.scratch);
+ }
+ });
});
diff --git a/server/lib/primaryCheckoutGuard.js b/server/lib/primaryCheckoutGuard.js
index c5cf48b02b..20d32236ab 100644
--- a/server/lib/primaryCheckoutGuard.js
+++ b/server/lib/primaryCheckoutGuard.js
@@ -260,7 +260,7 @@ async function resolveUpstreamRef(checkoutPath, branch) {
*
* NON-THROWING, like the rest of the module.
*/
-async function resolveRemoteDefaultRef(checkoutPath) {
+export async function resolveRemoteDefaultRef(checkoutPath) {
for (const ref of ['origin/HEAD', 'origin/main', 'origin/master']) {
const result = await execGit(
['rev-parse', '--verify', '--quiet', `${ref}^{commit}`],