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

add repo-sync task: sync every managed app with origin, agent only for judgment calls

[._.]/ Adam Eivy4ba8fb534525
diff --git a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
index 0f8730a99f..af2f6fc711 100644
--- a/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
+++ b/client/src/components/cos/tabs/schedule/AppTaskCard.jsx
@@ -87,6 +87,7 @@ export default function AppTaskCard({ taskType, config, apps, onTrigger, onConfi
taskType={taskType}
apps={apps}
onTrigger={onTrigger}
+ installWide={config.installWide}
disabledReason={improvementDisabled ? IMPROVEMENT_DISABLED_TITLE : (pins.saving ? SAVING_TITLE : '')}
/>
<button
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 89fa9b7329..aef7a959e9 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -663,6 +663,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
taskType={taskType}
apps={apps}
onTrigger={onTrigger}
+ installWide={config.installWide}
// `updating` covers an in-flight pin write here, same race the card gates on.
disabledReason={improvementDisabled ? IMPROVEMENT_DISABLED_TITLE : (updating ? SAVING_TITLE : '')}
/>
diff --git a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx b/client/src/components/cos/tabs/schedule/RunTaskButton.jsx
index bf6fb2130d..78c1a38c3b 100644
--- a/client/src/components/cos/tabs/schedule/RunTaskButton.jsx
+++ b/client/src/components/cos/tabs/schedule/RunTaskButton.jsx
@@ -16,7 +16,7 @@ const MENU_WIDTH = 256; // w-64
// A named boolean per reason would mean every new reason edits this component,
// and — as the pin-saving gate showed — reaching only whichever call site the
// author had in mind.
-export default function RunTaskButton({ taskType, apps, onTrigger, disabledReason = '' }) {
+export default function RunTaskButton({ taskType, apps, onTrigger, installWide = false, disabledReason = '' }) {
const [open, setOpen] = useState(false);
const ref = useRef(null);
const activeApps = apps?.filter(app => !app.archived) || [];
@@ -45,9 +45,18 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReaso
if (disabled) setOpen(false);
}, [disabled]);
- if (activeApps.length === 0) {
+ // An install-wide task sweeps every managed app in ONE dispatch, so its real
+ // run is the app-less one. Without this the picker would be the only way to
+ // start it on any install that has apps, and every click would send an appId —
+ // silently reducing an install-wide sweep to a single repo.
+ if (activeApps.length === 0 || installWide) {
return (
- <span title={disabledReason || 'Run this task immediately (bypasses schedule)'} className="inline-block">
+ <span
+ title={disabledReason || (installWide
+ ? 'Run this task across every managed app in one sweep'
+ : 'Run this task immediately (bypasses schedule)')}
+ className="inline-block"
+ >
<button
type="button"
onClick={() => !disabled && onTrigger(taskType)}
@@ -56,7 +65,7 @@ export default function RunTaskButton({ taskType, apps, onTrigger, disabledReaso
className={triggerButtonClass(disabled)}
>
<Play size={14} />
- Run Now
+ {installWide ? 'Run on All Apps' : 'Run Now'}
</button>
</span>
);
diff --git a/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx b/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx
index 5a27be1541..0c7fd0893b 100644
--- a/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx
+++ b/client/src/components/cos/tabs/schedule/RunTaskButton.test.jsx
@@ -33,6 +33,21 @@ describe('RunTaskButton', () => {
expect(onTrigger).toHaveBeenCalledWith('review');
});
+ it('runs an install-wide task with NO app even when apps exist', async () => {
+ // The regression this guards: an install-wide sweep dispatches once for the
+ // WHOLE install, but the picker only ever calls onTrigger WITH an appId. Left
+ // to the default branch, every click on a machine that has apps would quietly
+ // reduce the sweep to a single repo, and the install-wide lane would be
+ // unreachable from the UI entirely.
+ const user = userEvent.setup();
+ const onTrigger = vi.fn();
+ render(<RunTaskButton taskType="repo-sync" apps={APPS} onTrigger={onTrigger} installWide />);
+ await user.click(screen.getByRole('button', { name: /Run on All Apps/i }));
+ expect(onTrigger).toHaveBeenCalledWith('repo-sync');
+ expect(onTrigger.mock.calls[0]).toHaveLength(1);
+ expect(screen.queryByText('Example App')).toBeNull();
+ });
+
it('lists only active apps and runs the task on the picked one', async () => {
const user = userEvent.setup();
const onTrigger = vi.fn();
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 865267db95..495e1308c6 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -1644,9 +1644,33 @@ export const MAX_TOTAL_SPAWNS = 5;
// allowlist — like `prAuthorFilter` / `issueAuthorFilter` — so a per-app
// override can disable an individual rectification behavior and survive
// sanitizeTaskMetadata.
+// repo-sync's per-app / per-schedule action toggles. Each is ON unless
+// explicitly `false` (branch-reconcile's opt-out convention), EXCEPT
+// `reapRemotes`, which mutates `origin` and is therefore opt-IN. Lives here so
+// the sanitizer's allowlist and services/repoSync.js read ONE list — the two
+// drifting would silently drop a toggle at the app-override boundary.
+export const REPO_SYNC_ACTION_KEYS = ['syncPush', 'syncPull', 'switchDefault', 'cleanupMerged', 'dropStashes', 'reapRemotes'];
+
const ALLOWED_TASK_METADATA_KEYS = [
...PIPELINE_BEHAVIOR_FLAGS, 'readOnly', 'claimFlow',
'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'finishAbandoned', 'autoClose',
+ // repo-sync's action toggles (REPO_SYNC_ACTION_KEYS above): publish branches
+ // strictly ahead of their upstream, fast-forward the default branch, return the
+ // checkout to it, delete merged branches, drop provably-redundant stashes, and
+ // (opt-IN, since it mutates origin) reap merged orphan remote branches.
+ // `cleanupMerged` deliberately reuses branch-reconcile's NAME because it means
+ // the same thing — but task metadata is stored per task type, so the two are
+ // independent settings. Turning it off on branch-reconcile does NOT turn it off
+ // here; each task type carries its own value.
+ ...REPO_SYNC_ACTION_KEYS,
+ // repo-sync's per-app opt-OUT. The sweep is install-wide by design, so it
+ // needs a key of its own rather than reading the per-app `enabled` flag next
+ // to it: createApp SEEDS `{ enabled: false }` for every task type, so
+ // `enabled` cannot distinguish "leave this repo alone" from "never configured",
+ // and reading it would exclude every app on a fresh install. `enabled` still
+ // governs whether the app gets its own SCHEDULED repo-sync run; this governs
+ // whether the install-wide sweep visits its checkout.
+ 'skipRepoSync',
// Throwaway-worktree posture for programmatic-I/O reasoning tasks (layered-
// intelligence): the worktree is discarded without a merge or PR so a reasoning
// agent can't land code. See agentWorktreeCleanup.js.
@@ -1684,6 +1708,17 @@ export const PR_AUTHOR_FILTERS = ['any', 'self', 'others'];
// vocabulary.
export const ISSUE_AUTHOR_FILTERS = ['self', 'collaborators', 'owner', 'any'];
+
+// repo-sync verify-mode vocabulary — when the coordinator agent is dispatched
+// after the deterministic sweep. 'always' verifies every run; 'when-changed'
+// (the default) verifies only a run that actually mutated a checkout, so a sweep
+// over an already-clean machine makes no provider call at all; 'never' dispatches
+// only when the sweep left something unresolved. An ESCALATION dispatches under
+// every mode. Kept here so the sanitizer and services/repoSync.js agree on the
+// vocabulary — and so the static task registry can name the default without
+// importing the git-heavy service (it is deliberately dependency-light).
+export const REPO_SYNC_VERIFY_MODES = ['always', 'when-changed', 'never'];
+export const DEFAULT_REPO_SYNC_VERIFY_MODE = 'when-changed';
// `issueExcludeLabels` — extra labels a user wants left for human contributors
// (e.g. `good first issue`) rather than auto-claimed by claim-issue/claim-work.
// Unioned with the fixed NON_ACTIONABLE_ISSUE_LABELS set at read time
@@ -1862,6 +1897,13 @@ export function sanitizeTaskMetadata(raw) {
clean.prAuthorFilter = raw.prAuthorFilter;
hasKeys = true;
}
+ // `verifyMode` decides when repo-sync dispatches its coordinator agent after a
+ // clean deterministic pass — constrained, so an arbitrary string can't reach the
+ // dispatch gate (which would fall back to the default anyway, silently).
+ if (Object.prototype.hasOwnProperty.call(raw, 'verifyMode') && REPO_SYNC_VERIFY_MODES.includes(raw.verifyMode)) {
+ clean.verifyMode = raw.verifyMode;
+ hasKeys = true;
+ }
// `issueAuthorFilter` gates claim-issue dispatch on issue authorship —
// constrained to a known value so a hand-edited config can't smuggle in an
// arbitrary string the claim flow would silently treat as "owner".
diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.js
index 6782b26983..91a31efcba 100644
--- a/server/services/cosTaskGenerator.js
+++ b/server/services/cosTaskGenerator.js
@@ -1813,6 +1813,20 @@ export async function generateSelfImprovementTaskForType(taskType, state) {
metadata.effort = interval.effort;
}
+ // repo-sync's install-wide sweep. This lane is what a global "Run Now" (no
+ // app) hits, and sweeping EVERY managed app in one run is the shape the task
+ // exists for — so the pre-step runs here, not only in the per-app lane. It
+ // returns `skip` when the sweep left nothing for an agent to do, which is the
+ // common case on an already-clean machine and costs no provider call.
+ const repoSync = await resolveRepoSyncBlock(null, taskType, metadata);
+ if (repoSync.skip) return null;
+ if (repoSync.block) {
+ // Function form — the report embeds branch names, git error text, and stash
+ // subjects, any of which may contain a dollar-sign backreference token, which a replacement STRING
+ // would read as a backreference (same reason as {referenceData}/{prData}).
+ description = description.replace(/\{repoSyncReport\}/g, () => repoSync.block);
+ }
+
const approval = await resolveConfidenceApproval(state, `self-improve:${taskType}`, `Task self-improve:${taskType}`, metadata);
stampApprovalReason(metadata, approval);
@@ -2532,6 +2546,78 @@ async function resolveBranchReconcileBlock(app, taskType, metadata, taskSchedule
return { skip: false, block };
}
+/**
+ * repo-sync deterministic pre-step: run the Tier-1 sync sweep (services/repoSync.js)
+ * over every managed app's checkout — or, in the per-app lane, over just that
+ * app's — and decide whether the coordinator agent is needed at all.
+ *
+ * This is the whole point of the task type: the sweep is what actually gets the
+ * machine back in sync (push/fast-forward/return-to-default/prune/drop-redundant
+ * -stashes), and it runs with NO provider call. The agent is dispatched only for
+ * what the sweep refused to do — a mid-flight merge or rebase, uncommitted work,
+ * a diverged branch, unpushed commits with no PR, a stash it could not prove
+ * redundant — or, under `verifyMode: 'when-changed'` (the default), to
+ * double-check a run that actually mutated something. A sweep that finds every
+ * repo already in the target state dispatches nothing.
+ *
+ * Returns `{ skip: true }` for every no-dispatch path (the sweep still ran and is
+ * logged), or `{ skip: false, block }` carrying `{repoSyncReport}`. Empty block
+ * for every non-repo-sync type.
+ */
+async function resolveRepoSyncBlock(app, taskType, metadata) {
+ if (taskType !== 'repo-sync') return { skip: false, block: '' };
+ const {
+ REPO_SYNC_ACTION_KEYS, syncRepos, resolveSyncTargets, summarizeSync,
+ shouldDispatchVerifier, formatRepoSyncReport
+ } = await import('./repoSync.js');
+ const { getActiveAgentIds } = await import('./agentState.js');
+
+ // Action toggles were merged (global → per-app override) + value-constrained by
+ // sanitizeTaskMetadata into `metadata`. Only keys actually present are carried,
+ // so an absent one keeps repoSync's own opt-out default rather than becoming
+ // `undefined` (which `actionOn` reads as ON — right answer, wrong reason).
+ const actions = Object.fromEntries(
+ REPO_SYNC_ACTION_KEYS.filter((key) => metadata[key] !== undefined).map((key) => [key, metadata[key]])
+ );
+
+ // `null` means the registry read FAILED, which is not "no apps" — sweeping
+ // nothing and reporting a clean machine would be a lie. Skip and let the next
+ // run retry (same treatment the on-demand engine gives an unreadable registry).
+ const apps = app ? [app] : await getActiveApps().catch(() => null);
+ if (!apps) {
+ emitLog('warn', `🔄 repo-sync skipped — the app registry could not be read`, { analysisType: taskType });
+ return { skip: true };
+ }
+ // Both lanes resolve through the same helper, so a repo-less app, an opt-out,
+ // and the per-app action overrides behave identically whether the run named an
+ // app or swept the install.
+ const targets = resolveSyncTargets(apps, actions);
+ if (!targets.length) {
+ emitLog('info', `🔄 repo-sync: no managed repositories to sweep`, { analysisType: taskType });
+ return { skip: true };
+ }
+
+ const results = await syncRepos(targets, { activeAgentIds: new Set(getActiveAgentIds()) })
+ .catch((err) => {
+ emitLog('warn', `repo-sync sweep failed: ${err.message}`, { analysisType: taskType });
+ return null;
+ });
+ // A sweep that threw outright is transient (a git/gh blip) — skip so the next
+ // run retries, rather than dispatching an agent against a report we don't have.
+ if (!results) return { skip: true };
+
+ const summary = summarizeSync(results);
+ emitLog('info', `🔄 repo-sync swept ${summary.repos} repo(s): ${summary.actionCount} action(s) applied, ${summary.escalationCount} item(s) need judgment`, { analysisType: taskType });
+
+ const verdict = shouldDispatchVerifier(summary, metadata.verifyMode);
+ if (!verdict.dispatch) {
+ emitLog('info', `🔄 repo-sync: ${verdict.reason} — no agent dispatched`, { analysisType: taskType });
+ return { skip: true };
+ }
+ emitLog('info', `🔄 repo-sync dispatching coordinator: ${verdict.reason}`, { analysisType: taskType });
+ return { skip: false, block: formatRepoSyncReport(results, { verifyReason: verdict.reason }) };
+}
+
/**
* issue-reconcile deterministic pre-step — scan the app's forge repo (GitHub via
* `gh`, GitLab via `glab`, or JIRA when explicitly configured) for ZOMBIE issues
@@ -2761,6 +2847,7 @@ async function buildImprovementTaskDescription({ promptTemplate, app, promptTask
.replace(/\{prData\}/g, () => blocks.prData)
.replace(/\{inFlightBranches\}/g, () => blocks.inFlightBranches)
.replace(/\{zombieIssues\}/g, () => blocks.zombieIssues)
+ .replace(/\{repoSyncReport\}/g, () => blocks.repoSyncReport || '')
.replace(/\{repoFullName\}/g, () => blocks.repoFullName)
.replace(/\{defaultBranch\}/g, () => blocks.defaultBranch)
.replace(/\{planConstraint\}/g, () => blocks.planConstraint)
@@ -2912,6 +2999,15 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
if (branchReconcile.skip) return null;
const inFlightBranchesBlock = branchReconcile.block;
+ // repo-sync: deterministic git pre-step that syncs this app's checkout with
+ // origin and carries whatever it refused to do into the prompt via
+ // {repoSyncReport}. (The install-wide sweep runs from the global lane —
+ // generateSelfImprovementTaskForType — which is what "Run Now" with no app
+ // triggers; this branch covers a run scoped to one app.)
+ const repoSync = await resolveRepoSyncBlock(app, taskType, metadata);
+ if (repoSync.skip) return null;
+ const repoSyncReportBlock = repoSync.block;
+
// issue-reconcile: deterministic forge pre-step that carries the zombie-issue
// set into the prompt via {zombieIssues}.
const issueReconcile = await resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule);
@@ -2989,6 +3085,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st
prData: prDataBlock,
inFlightBranches: inFlightBranchesBlock,
zombieIssues: zombieIssuesBlock,
+ repoSyncReport: repoSyncReportBlock,
repoFullName: prRepoFullName,
defaultBranch: prDefaultBranch,
planConstraint: planConstraintBlock
diff --git a/server/services/git.js b/server/services/git.js
index 92242a215d..9cadb6810e 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -36,8 +36,11 @@ export {
extractAgentSummary
};
-// Like execGit but catches rejections (e.g. timeout) into a failed-result shape
-const execGitSafe = (args, cwd, options) =>
+// Like execGit but catches rejections (e.g. timeout) into a failed-result shape.
+// Exported because every caller that wants `ignoreExitCode` semantics also has to
+// survive the two rejections `ignoreExitCode` does NOT suppress — a timeout and a
+// maxBuffer overflow — and each one hand-rolling that catch drops `stdout`.
+export const execGitSafe = (args, cwd, options) =>
execGit(args, cwd, options).catch(err => ({ exitCode: 1, stdout: '', stderr: err.message }));
/**
@@ -207,8 +210,8 @@ export function clearFetchCache() {
activeFetches.clear();
}
-function fetchOriginAttempt(dir, attempt) {
- return execGit(['fetch', 'origin'], dir).then(
+function fetchOriginAttempt(dir, attempt, prune = false) {
+ return execGit(prune ? ['fetch', '--prune', 'origin'] : ['fetch', 'origin'], dir).then(
() => {
recordFetchSuccess(dir);
return true;
@@ -226,13 +229,21 @@ function fetchOriginAttempt(dir, attempt) {
}
// Another PortOS surface or agent may advance the same remote ref mid-fetch.
if (attempt >= FETCH_MAX_ATTEMPTS || !isGitLockError(err.message)) throw err;
- return sleep(FETCH_RETRY_DELAY_MS).then(() => fetchOriginAttempt(dir, attempt + 1));
+ return sleep(FETCH_RETRY_DELAY_MS).then(() => fetchOriginAttempt(dir, attempt + 1, prune));
}
);
}
-export function fetchOrigin(dir) {
- return fetchOriginAttempt(dir, 1);
+/**
+ * Fetch origin with the concurrency handling a raw `git fetch` lacks: retries an
+ * `index.lock` collision, and treats a lost compare-and-swap on refs another
+ * PortOS surface already wrote as the SUCCESS it is.
+ * @param {string} dir
+ * @param {{prune?: boolean}} [opts] - `prune` also drops remote-tracking refs whose
+ * remote branch is gone, for callers that go on to reason about what origin still has.
+ */
+export function fetchOrigin(dir, { prune = false } = {}) {
+ return fetchOriginAttempt(dir, 1, prune);
}
/**
@@ -1228,7 +1239,7 @@ async function clearSequencerState(dir, gitDirPath) {
* @param {string} dir - Repo root to check
* @returns {Promise<string|null>} - Agent id, or null
*/
-async function findActiveAgentInWorkspace(dir) {
+export async function findActiveAgentInWorkspace(dir) {
const { getAgents } = await import('./cosAgentLifecycle.js').catch(() => ({ getAgents: null }));
if (!getAgents) return null;
const agents = await getAgents().catch(() => []);
diff --git a/server/services/repoSync.js b/server/services/repoSync.js
new file mode 100644
index 0000000000..8df4d89161
--- /dev/null
+++ b/server/services/repoSync.js
@@ -0,0 +1,819 @@
+/**
+ * Repo Sync — deterministic core for the `repo-sync` scheduled task.
+ *
+ * Walks every managed app's checkout (PortOS itself is one of them) and puts it
+ * back in the state a fresh piece of work wants to start from: on the default
+ * branch, level with origin in both directions, no leftover local branches or
+ * worktrees, and an empty stash list.
+ *
+ * Two tiers, in the same shape branchReconcile.js uses:
+ *
+ * Tier 1 (this module) — everything PROVABLE. Fetch, push branches that are
+ * strictly ahead of their upstream, fast-forward the default branch, return
+ * the checkout to the default branch when the branch it is on is already
+ * merged, delete merged branches/worktrees (delegated to
+ * `branchReconcile.reconcile`), and drop stash entries whose content is
+ * byte-identical to the default branch. No agent, no LLM call.
+ *
+ * Tier 2 (the caller) — everything that needs JUDGMENT is returned as an
+ * `escalations` list for a coordinator CoS agent: a half-finished
+ * merge/rebase, uncommitted work of unknown provenance, a branch that has
+ * diverged from its upstream, unpushed commits with no PR, a stash that
+ * is NOT provably redundant. This module never spawns an agent, so it stays
+ * pure enough to unit-test.
+ *
+ * NOTHING here can lose work. Every mutating step is gated on a property that
+ * makes it recoverable or a no-op:
+ * - push never uses `--force` and never runs on a branch that is behind.
+ * - the default branch only ever fast-forwards (`--ff-only`, or a
+ * `fetch origin <b>:<b>` refspec, which git itself refuses to non-FF).
+ * - the checkout only switches off a branch that is CLEAN and already merged.
+ * - branch/worktree deletion runs through branchReconcile's existing gates.
+ * - a stash is dropped only when every path it touches already has identical
+ * content on the default branch, i.e. applying it would produce no diff.
+ * Anything that fails one of those gates is REPORTED, never forced.
+ *
+ * SCOPE BOUNDARY with branch-reconcile: this task reports an in-flight branch
+ * (one that needs a PR opened, a conflict resolved, or a review driven) but does
+ * NOT drive it. That is branch-reconcile's job, and it wraps the same classified
+ * set in machinery this task has no equivalent of — the per-app openPr /
+ * resolveConflicts / autoMerge / finishAbandoned toggles, per-agent batching, the
+ * drain convergence guards, and the superseded ledger. Acting on those branches
+ * here would bypass all of it, so the coordinator prompt names branch-reconcile
+ * instead.
+ */
+
+import { existsSync } from 'node:fs';
+import { isAbsolute, join, resolve } from 'node:path';
+import {
+ execGitSafe, fetchOrigin, findActiveAgentInWorkspace, getBranch, getBranches,
+ getDefaultBranch, getStatusPorcelain, isBranchMergedInto, isRepo
+} from './git.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { mapWithConcurrency } from '../lib/mapWithConcurrency.js';
+import {
+ DEFAULT_REPO_SYNC_VERIFY_MODE, REPO_SYNC_ACTION_KEYS, REPO_SYNC_VERIFY_MODES, sanitizeTaskMetadata
+} from '../lib/cosValidation.js';
+import { stripManagedAgentOptionsFromOverride } from './taskScheduleRegistry.js';
+
+// The action-toggle vocabulary lives in lib/cosValidation.js beside the
+// allowlist that has to accept it — one list, so a new toggle cannot be added
+// to the sanitizer and missed here (or vice versa). Re-exported at the address
+// the generator reads it from.
+export { REPO_SYNC_ACTION_KEYS };
+
+/**
+ * An action is ON unless the config explicitly set it to false (opt-out).
+ *
+ * Deliberately a local copy of `branchReconcile.actionOn` rather than an import:
+ * that module is reached from here by a LAZY `import()` (its dependency graph
+ * pulls in `gh`, the worktree manager, and the superseded ledger), and a static
+ * import for a one-line predicate would put all of it back on this module's
+ * startup graph. Keep the two in step if the opt-out convention ever changes.
+ */
+const actionOn = (actions, key) => actions?.[key] !== false;
+
+/**
+ * Escalation vocabulary. Kept as a frozen map (rather than bare strings at the
+ * call sites) so the planner, the formatter, and the tests name the same set.
+ */
+export const ESCALATION_KINDS = Object.freeze({
+ OPERATION_IN_PROGRESS: 'operation-in-progress',
+ UNCOMMITTED_CHANGES: 'uncommitted-changes',
+ DETACHED_HEAD: 'detached-head',
+ DIVERGED_BRANCH: 'diverged-branch',
+ DIVERGED_DEFAULT: 'diverged-default',
+ UNPUSHED_BRANCH: 'unpushed-branch',
+ OFF_DEFAULT_BRANCH: 'off-default-branch',
+ STASH_ENTRIES: 'stash-entries',
+ IN_FLIGHT_BRANCH: 'in-flight-branch',
+ ORPHAN_REMOTE: 'orphan-remote',
+ ACTION_FAILED: 'action-failed',
+ SCAN_FAILED: 'scan-failed'
+});
+
+/**
+ * Half-finished git operations, mapped to the name a human would use. A repo in
+ * any of these states is the "we hit a merge or rebase conflict" case: Tier 1
+ * refuses to touch it at all (not even a fetch-driven fast-forward) and hands
+ * the whole repo to the agent, because every safety property above assumes a
+ * settled HEAD.
+ *
+ * Deliberately a superset of git.js's `SEQUENCER_STATE`, not a reuse of it: that
+ * list answers "what does a forced checkout fail to clear?" (so it omits
+ * `MERGE_HEAD`, which a checkout does clear) while this one answers "what makes
+ * a repo unsafe to sync?". Same rows, different questions — a marker can belong
+ * to one and not the other.
+ */
+const OPERATION_MARKERS = [
+ ['MERGE_HEAD', 'merge'],
+ ['rebase-merge', 'rebase'],
+ ['rebase-apply', 'rebase'],
+ ['CHERRY_PICK_HEAD', 'cherry-pick'],
+ ['REVERT_HEAD', 'revert'],
+ ['BISECT_LOG', 'bisect']
+];
+
+/**
+ * Cap on how many paths one stash may touch and still be auto-classified. A
+ * larger stash is reported instead: the `git diff --quiet <stash> <target> --
+ * <paths>` probe below would otherwise build an argv long enough to hit the
+ * platform limit, and a spawn that dies on E2BIG must not read as "not
+ * superseded" for a reason that has nothing to do with the stash.
+ */
+export const MAX_STASH_PATHS_FOR_AUTO_CLASSIFY = 200;
+
+/**
+ * How many stashes are classified at once. Each costs 2–3 git spawns, and every
+ * one of them is a rev-to-rev / tree-to-tree read — no index refresh, no
+ * working-tree read, no lock — so they are safe to overlap. Bounded so a
+ * checkout carrying dozens of stashes doesn't fork a hundred processes at once.
+ */
+const STASH_CLASSIFY_CONCURRENCY = 6;
+
+// ============================================================
+// Snapshot (Tier 1 reads)
+// ============================================================
+
+/**
+ * The half-finished git operation this checkout is in, or null.
+ * @param {string} repoPath
+ * @returns {Promise<string|null>}
+ */
+async function detectOperationInProgress(repoPath) {
+ const out = await execGitSafe(['rev-parse', '--git-dir'], repoPath, { ignoreExitCode: true });
+ const raw = (out.stdout || '').trim();
+ if (!raw) return null;
+ const gitDir = isAbsolute(raw) ? raw : join(repoPath, raw);
+ const found = OPERATION_MARKERS.find(([marker]) => existsSync(join(gitDir, marker)));
+ return found ? found[1] : null;
+}
+
+/**
+ * The TRACKED changed paths in a `git status --porcelain` dump — the set that
+ * decides whether this checkout may be switched or fast-forwarded.
+ *
+ * Untracked entries are excluded because they do not block a branch switch (git
+ * refuses only when a checkout would overwrite one, and that refusal is caught
+ * and escalated) and are never discarded. This is the path-returning sibling of
+ * git.js's `countDiscardable`, which applies the same filter for a count.
+ *
+ * Deliberately STRICTER than `worktreeManager.classifyWorktreeDirt`, which
+ * treats lockfile-only churn as clean: that carve-out is right for deciding
+ * whether an agent left real work behind, and wrong here — a regenerated
+ * lockfile is still a tracked modification a branch switch would carry across.
+ *
+ * Pure.
+ * @param {string} porcelain
+ * @returns {string[]}
+ */
+export function dirtyTrackedPaths(porcelain) {
+ return String(porcelain || '')
+ .split('\n')
+ .map((line) => line.trim())
+ .filter((line) => line && !line.startsWith('??'))
+ // Strip the status prefix, then take the post-rename name — `R old -> new`
+ // otherwise yields one path string naming two files.
+ .map((line) => line.replace(/^\S+\s+/, '').split(' -> ').pop().trim())
+ .filter(Boolean);
+}
+
+/**
+ * Parse `git stash list --format=%gd%x1f%H%x1f%P%x1f%gs`. The parent count comes
+ * along for free and tells us whether the entry even HAS an untracked-files
+ * commit (a third parent, present only for `git stash -u`), which saves a
+ * guaranteed-to-fail `ls-tree` spawn per ordinary stash.
+ * Pure.
+ * @param {string} stdout
+ * @returns {{ref:string, sha:string, parentCount:number, message:string}[]}
+ */
+export function parseStashList(stdout) {
+ return String(stdout || '')
+ .split('\n')
+ .map((line) => line.split('\x1f'))
+ .filter((parts) => parts.length >= 4 && parts[0].trim() && parts[1].trim())
+ .map(([ref, sha, parents, ...rest]) => ({
+ ref: ref.trim(),
+ sha: sha.trim(),
+ parentCount: parents.trim().split(/\s+/).filter(Boolean).length,
+ message: rest.join('\x1f').trim()
+ }));
+}
+
+/**
+ * Every path a stash commit carries — its tracked diff against its own base
+ * plus, when the stash was taken with `-u`, the untracked snapshot in its third
+ * parent. An unreadable read yields nothing from that half, which is also the
+ * safe direction: a path we cannot see cannot be proven redundant.
+ * @param {string} repoPath
+ * @param {string} sha - the stash commit
+ * @param {number} parentCount - from `parseStashList`; 3 ⇒ carries untracked files
+ * @returns {Promise<string[]>}
+ */
+async function stashPaths(repoPath, sha, parentCount) {
+ const [tracked, untracked] = await Promise.all([
+ execGitSafe(['diff', '--name-only', `${sha}^1`, sha], repoPath, { ignoreExitCode: true }),
+ parentCount >= 3
+ ? execGitSafe(['ls-tree', '-r', '--name-only', `${sha}^3`], repoPath, { ignoreExitCode: true })
+ : Promise.resolve({ exitCode: 1, stdout: '' })
+ ]);
+ const lines = (out) => (out.exitCode === 0 ? out.stdout : '').split('\n').map((l) => l.trim()).filter(Boolean);
+ return [...new Set([...lines(tracked), ...lines(untracked)])];
+}
+
+/**
+ * Is this stash's content ALREADY what the default branch holds?
+ *
+ * The test is content equality on exactly the paths the stash touches: if every
+ * one of them is byte-identical between the stash commit's tree and `target`,
+ * then applying the stash there produces no diff, so dropping it cannot lose
+ * anything. That is a strictly narrower (and provable) reading of the
+ * "SUPERSEDED" classification the `stash-cleanup` prompt asks a model to make by
+ * hand — everything this can't prove is left for that judgment call.
+ *
+ * Fails CLOSED in every direction: an unreadable path list, a too-large stash,
+ * or a git error all yield `superseded: false`.
+ *
+ * @param {string} repoPath
+ * @param {string} sha - the stash commit
+ * @param {string} target - ref to compare against (origin/<default>, or <default>)
+ * @param {number} [parentCount] - from `parseStashList`
+ * @returns {Promise<{superseded:boolean, reason:string}>}
+ */
+export async function classifyStash(repoPath, sha, target, parentCount = 2) {
+ const paths = await stashPaths(repoPath, sha, parentCount);
+ if (paths.length === 0) return { superseded: true, reason: 'empty stash (no changes recorded)' };
+ if (paths.length > MAX_STASH_PATHS_FOR_AUTO_CLASSIFY) {
+ return { superseded: false, reason: `touches ${paths.length} paths — too large to auto-classify` };
+ }
+ const diff = await execGitSafe(['diff', '--quiet', sha, target, '--', ...paths], repoPath, { ignoreExitCode: true });
+ if (diff.exitCode === 0) {
+ return { superseded: true, reason: `content identical to ${target} on all ${paths.length} path(s)` };
+ }
+ return { superseded: false, reason: `differs from ${target}` };
+}
+
+/**
+ * Read the whole checkout state one repo needs for a sync decision. Performs no
+ * mutation beyond the fetch (which only writes remote-tracking refs).
+ *
+ * Issued in waves rather than one long serial chain: everything inside a wave is
+ * an independent READ, and none of them contends for the index lock (`status` is
+ * the only one that can take it, and nothing else in its wave wants it).
+ *
+ * @param {string} repoPath
+ * @returns {Promise<object>} snapshot consumed by `planRepoSync`
+ */
+async function collectRepoState(repoPath) {
+ if (!await isRepo(repoPath)) return { repoPath, isRepo: false };
+
+ const [operationInProgress, origin] = await Promise.all([
+ detectOperationInProgress(repoPath),
+ getOriginInfo(repoPath).catch(() => null)
+ ]);
+ const hasOrigin = Boolean(origin?.hasOrigin);
+
+ // A repo mid-merge/rebase is reported and otherwise left completely alone —
+ // fetching is harmless but every later read describes a transient tree, and
+ // acting on it is exactly the case the user asked to route to an agent.
+ //
+ // Routed through git.js's `fetchOrigin`, not a raw `git fetch`: it retries an
+ // `index.lock` collision and treats a lost compare-and-swap on refs another
+ // PortOS surface already wrote as the success it is. Without that, a routine
+ // concurrent fetch would surface here as `scan-failed` — and an escalation
+ // dispatches the coordinator agent unconditionally, so a benign race would buy
+ // a provider call on the one task built to avoid making them.
+ let fetchError = null;
+ if (hasOrigin && !operationInProgress) {
+ fetchError = await fetchOrigin(repoPath, { prune: true }).then(() => null, (err) => err.message);
+ }
+
+ const [defaultBranch, headBranch, porcelain, branches, rawStashes, activeAgentId] = await Promise.all([
+ getDefaultBranch(repoPath).then((b) => b || 'main', () => 'main'),
+ getBranch(repoPath).catch(() => ''),
+ getStatusPorcelain(repoPath).catch(() => ''),
+ getBranches(repoPath).catch(() => []),
+ // The planner refuses to act on a repo mid-operation, so classifying its
+ // stashes (2–3 git spawns each) buys nothing.
+ operationInProgress
+ ? Promise.resolve([])
+ : execGitSafe(['stash', 'list', '--format=%gd%x1f%H%x1f%P%x1f%gs'], repoPath, { ignoreExitCode: true })
+ .then((r) => parseStashList(r.stdout)),
+ findActiveAgentInWorkspace(repoPath).catch(() => null)
+ ]);
+
+ const detached = headBranch === 'HEAD' || headBranch === '';
+ const currentBranch = detached ? null : headBranch;
+ const dirtyTracked = dirtyTrackedPaths(porcelain);
+ const remoteDefault = hasOrigin ? `origin/${defaultBranch}` : null;
+
+ // How the LOCAL default branch stands against origin's copy — the number that
+ // decides fast-forward vs "diverged, hand it to the agent". `getBranches`
+ // already parsed `%(upstream:track)` for every local branch, so the common
+ // case needs no extra spawn; the `rev-list` fallback covers a default branch
+ // that tracks something other than `origin/<default>` (or nothing at all).
+ const defaultEntry = branches.find((b) => b.name === defaultBranch);
+ const defaultDivergence = !remoteDefault
+ ? null
+ : defaultEntry?.tracking === remoteDefault
+ ? { ahead: defaultEntry.ahead, behind: defaultEntry.behind }
+ : await countAheadBehind(repoPath, defaultBranch, remoteDefault);
+
+ // Compare stashes against origin's default when we have it (that is what the
+ // branch will be after the fast-forward below) and the local default
+ // otherwise, so an offline machine still gets a correct — just staler — answer.
+ const stashTarget = remoteDefault && defaultDivergence ? remoteDefault : defaultBranch;
+
+ const [stashes, currentBranchMerged] = await Promise.all([
+ mapWithConcurrency(rawStashes, STASH_CLASSIFY_CONCURRENCY, async (entry) => ({
+ ...entry,
+ ...await classifyStash(repoPath, entry.sha, stashTarget, entry.parentCount)
+ .catch(() => ({ superseded: false, reason: 'classification failed' }))
+ })),
+ // Is the branch we are standing on already landed? `getBranches` cannot
+ // answer this — it computes `merged` with a `!b.current` guard, so the
+ // CURRENT branch is always reported unmerged. Ask directly, against origin's
+ // copy of the default branch when we have one (the local copy may not have
+ // been fast-forwarded yet, which would read a landed branch as unmerged).
+ // `isBranchMergedInto` also covers squash- and rebase-merges, and returns
+ // true for a branch carrying no unique commits at all (a bare pointer
+ // someone branched and never committed on).
+ currentBranch && currentBranch !== defaultBranch
+ ? isBranchMergedInto(repoPath, currentBranch, remoteDefault || defaultBranch).catch(() => false)
+ : Promise.resolve(false)
+ ]);
+
+ return {
+ repoPath,
+ isRepo: true,
+ fetchError,
+ defaultBranch,
+ remoteDefault,
+ currentBranch,
+ operationInProgress,
+ dirtyTracked,
+ branches,
+ defaultDivergence,
+ stashes,
+ activeAgentId,
+ currentBranchMerged
+ };
+}
+
+/**
+ * `{ahead, behind}` of `ref` relative to `base`, or null when either ref is
+ * unreadable (a branch with no remote-tracking counterpart yet).
+ * @param {string} repoPath
+ * @param {string} ref
+ * @param {string} base
+ * @returns {Promise<{ahead:number, behind:number}|null>}
+ */
+async function countAheadBehind(repoPath, ref, base) {
+ const out = await execGitSafe(['rev-list', '--left-right', '--count', `${base}...${ref}`], repoPath, { ignoreExitCode: true });
+ if (out.exitCode !== 0) return null;
+ const [behind, ahead] = (out.stdout || '').trim().split(/\s+/).map((n) => Number.parseInt(n, 10));
+ if (!Number.isFinite(ahead) || !Number.isFinite(behind)) return null;
+ return { ahead, behind };
+}
+
+// ============================================================
+// Planner (PURE)
+// ============================================================
+
+/**
+ * Decide what Tier 1 may do to this checkout and what has to go to the agent.
+ * Pure — takes a snapshot, returns steps + escalations, touches nothing.
+ *
+ * @param {object} state - `collectRepoState` output
+ * @param {object} [actions] - the per-app toggles (see REPO_SYNC_ACTION_KEYS)
+ * @returns {{steps:object[], escalations:object[]}}
+ */
+export function planRepoSync(state, actions = {}) {
+ const steps = [];
+ const escalations = [];
+ const escalate = (kind, detail) => escalations.push({ kind, detail });
+
+ if (!state?.isRepo) return { steps, escalations };
+
+ // A settled HEAD is the precondition for every safety property in this
+ // module, so a repo mid-operation gets no steps at all.
+ if (state.operationInProgress) {
+ escalate(ESCALATION_KINDS.OPERATION_IN_PROGRESS,
+ `a ${state.operationInProgress} is in progress — resolve it before this checkout can be synced`);
+ return { steps, escalations };
+ }
+
+ if (state.fetchError) {
+ escalate(ESCALATION_KINDS.SCAN_FAILED, `could not fetch from origin: ${state.fetchError}`);
+ }
+
+ const clean = state.dirtyTracked.length === 0;
+ if (!clean) {
+ escalate(ESCALATION_KINDS.UNCOMMITTED_CHANGES,
+ `${state.dirtyTracked.length} uncommitted change(s) on ${state.currentBranch || 'a detached HEAD'}: ${state.dirtyTracked.slice(0, 10).join(', ')}`);
+ }
+
+ if (!state.currentBranch) {
+ escalate(ESCALATION_KINDS.DETACHED_HEAD, 'HEAD is detached — no branch to sync or return from');
+ }
+
+ // --- push: a branch strictly AHEAD of its upstream is safe to publish. A
+ // branch that is also behind has diverged (someone rewrote the remote, or a
+ // peer pushed), and a non-forced push would just be rejected — that is a
+ // judgment call, not a sync step.
+ for (const branch of state.branches) {
+ if (!branch.tracking) {
+ // No upstream at all. Unpushed commits are unreviewed by definition; a
+ // bare pointer at the default branch's tip is just cruft the merged-branch
+ // cleanup handles, so only a branch with its own commits escalates.
+ if (branch.ahead > 0 && !branch.isDefault) {
+ escalate(ESCALATION_KINDS.UNPUSHED_BRANCH,
+ `${branch.name} has ${branch.ahead} local commit(s) and no upstream — never pushed, no PR`);
+ }
+ continue;
+ }
+ if (branch.ahead > 0 && branch.behind > 0) {
+ escalate(ESCALATION_KINDS.DIVERGED_BRANCH,
+ `${branch.name} is ${branch.ahead} ahead / ${branch.behind} behind ${branch.tracking} — needs a rebase or merge`);
+ continue;
+ }
+ if (branch.ahead > 0 && actionOn(actions, 'syncPush')) {
+ steps.push({ kind: 'push', branch: branch.name, ahead: branch.ahead });
+ }
+ }
+
+ // --- return to the default branch. Only ever off a branch that is CLEAN and
+ // whose commits are already in the default branch, so the switch can strand
+ // nothing. A dirty tree, a live agent, or unmerged commits are all reported
+ // instead: which of those the user wants done with the branch is precisely the
+ // judgment this module refuses to make.
+ const onDefault = state.currentBranch === state.defaultBranch;
+ if (!onDefault && state.currentBranch) {
+ if (!clean) {
+ escalate(ESCALATION_KINDS.OFF_DEFAULT_BRANCH,
+ `checkout is on ${state.currentBranch} with uncommitted changes — decide what to do with them before returning to ${state.defaultBranch}`);
+ } else if (state.activeAgentId) {
+ escalate(ESCALATION_KINDS.OFF_DEFAULT_BRANCH,
+ `checkout is on ${state.currentBranch} and agent ${state.activeAgentId} is running in it — left alone`);
+ } else if (state.currentBranchMerged !== true) {
+ escalate(ESCALATION_KINDS.OFF_DEFAULT_BRANCH,
+ `checkout is on ${state.currentBranch}, whose work is not in ${state.defaultBranch} yet — ship it before switching`);
+ } else if (actionOn(actions, 'switchDefault')) {
+ steps.push({ kind: 'switch-default', from: state.currentBranch, to: state.defaultBranch });
+ }
+ }
+
+ // --- fast-forward the default branch. `behind > 0 && ahead === 0` is exactly
+ // the fast-forwardable shape; anything else is a diverged local default, which
+ // is never resolved automatically (it holds commits origin does not).
+ const div = state.defaultDivergence;
+ if (div && div.behind > 0 && div.ahead === 0 && actionOn(actions, 'syncPull')) {
+ // A dirty tree only blocks the pull when the default branch is the one
+ // checked out — a refspec fetch into a non-checked-out branch never touches
+ // the working tree. No second escalation when it does block: the dirty tree
+ // was already reported above, and reporting one problem twice inflates the
+ // count that drives both the dispatch reason and the agent's stated workload.
+ const willBeOnDefault = onDefault || steps.some((s) => s.kind === 'switch-default');
+ if (!willBeOnDefault || clean) {
+ steps.push({ kind: 'ff-default', branch: state.defaultBranch, behind: div.behind, checkedOut: willBeOnDefault });
+ }
+ }
+ if (div && div.ahead > 0 && div.behind > 0) {
+ escalate(ESCALATION_KINDS.DIVERGED_DEFAULT,
+ `${state.defaultBranch} is ${div.ahead} ahead / ${div.behind} behind ${state.remoteDefault} — the default branch itself has diverged`);
+ }
+
+ // --- stashes. Only the provably-redundant ones are dropped; the rest are
+ // named so the agent (or the `stash-cleanup` task) can judge them.
+ const redundant = state.stashes.filter((s) => s.superseded);
+ const keep = state.stashes.filter((s) => !s.superseded);
+ if (actionOn(actions, 'dropStashes')) {
+ // Descending index order: `git stash drop` renumbers everything BELOW the
+ // entry it removes, so dropping the highest index first leaves every
+ // still-pending ref valid. The executor re-verifies each sha anyway.
+ for (const entry of [...redundant].sort((a, b) => stashIndex(b.ref) - stashIndex(a.ref))) {
+ steps.push({ kind: 'drop-stash', ref: entry.ref, sha: entry.sha, reason: entry.reason });
+ }
+ }
+ if (keep.length) {
+ escalate(ESCALATION_KINDS.STASH_ENTRIES,
+ `${keep.length} stash entr${keep.length === 1 ? 'y is' : 'ies are'} not provably redundant: `
+ + keep.map((s) => `${s.ref} "${s.message}" (${s.reason})`).join('; '));
+ }
+
+ return { steps, escalations };
+}
+
+/** Numeric index of a `stash@{N}` ref; -1 when unparseable. Pure. */
+export function stashIndex(ref) {
+ const m = /^stash@\{(\d+)\}$/.exec(String(ref || '').trim());
+ return m ? Number.parseInt(m[1], 10) : -1;
+}
+
+// ============================================================
+// Executor (Tier 1 writes)
+// ============================================================
+
+/**
+ * Run one planned step. Never forces, never discards. A step that fails becomes
+ * an `action-failed` escalation rather than throwing, because one stuck repo in
+ * a sweep must not abort the others.
+ *
+ * @param {string} repoPath
+ * @param {object} step
+ * @returns {Promise<{ok:boolean, step:object, detail?:string}>}
+ */
+async function runStep(repoPath, step) {
+ const fail = (detail) => ({ ok: false, step, detail });
+ // One place that decides what "the step failed" means and how git's output is
+ // summarized, so a fifth step kind can't invent a fifth answer.
+ const attempt = async (args) => {
+ const r = await execGitSafe(args, repoPath, { ignoreExitCode: true });
+ return r.exitCode === 0 ? { ok: true, step } : fail((r.stderr + r.stdout).trim().split('\n').slice(-3).join(' '));
+ };
+
+ if (step.kind === 'push') return attempt(['push', 'origin', step.branch]);
+ if (step.kind === 'switch-default') return attempt(['checkout', step.to]);
+
+ if (step.kind === 'ff-default') {
+ // Two shapes, both non-destructive by construction: `merge --ff-only`
+ // refuses anything that is not a fast-forward, and a `<branch>:<branch>`
+ // refspec fetch into a branch that is not checked out is refused by git for
+ // the same reason.
+ //
+ // Which one applies is re-read from HEAD rather than taken from the plan's
+ // `checkedOut` prediction. The prediction assumes the `switch-default` step
+ // queued ahead of this one SUCCEEDED; if it did not (a checkout blocked by an
+ // untracked file it would overwrite, say), `merge --ff-only origin/main`
+ // would run while still on the feature branch and merge the default branch
+ // INTO it — a real change to the wrong branch, from a step that is supposed
+ // to be a no-op-or-fast-forward.
+ const head = await getBranch(repoPath).catch(() => '');
+ return attempt(head === step.branch
+ ? ['merge', '--ff-only', `origin/${step.branch}`]
+ : ['fetch', 'origin', `${step.branch}:${step.branch}`]);
+ }
+
+ if (step.kind === 'drop-stash') {
+ // Re-resolve the ref before dropping: an earlier drop in this same run (or
+ // anything else that touched the stash list since the scan) renumbers the
+ // refs, and dropping the wrong index is the one irreversible mistake
+ // available here. Mismatch ⇒ skip, and the next run re-classifies.
+ const at = await execGitSafe(['rev-parse', step.ref], repoPath, { ignoreExitCode: true });
+ if (at.stdout.trim() !== step.sha) {
+ return fail(`${step.ref} no longer points at ${step.sha.slice(0, 8)} — skipped`);
+ }
+ return attempt(['stash', 'drop', step.ref]);
+ }
+
+ return fail(`unknown step kind '${step.kind}'`);
+}
+
+/**
+ * Human-readable one-liner for a planned/performed step. Pure.
+ * @param {object} step
+ * @returns {string}
+ */
+export function describeStep(step) {
+ switch (step.kind) {
+ case 'push': return `pushed ${step.branch} (${step.ahead} commit(s)) to origin`;
+ case 'switch-default': return `switched checkout from ${step.from} to ${step.to}`;
+ case 'ff-default': return `fast-forwarded ${step.branch} (${step.behind} behind origin)`;
+ case 'drop-stash': return `dropped ${step.ref} — ${step.reason}`;
+ default: return step.kind;
+ }
+}
+
+/**
+ * Sync ONE repo: snapshot → plan → execute → hand back what still needs a human
+ * or an agent. Never throws; a scan that blows up is reported as a `scan-failed`
+ * escalation so the sweep continues.
+ *
+ * @param {{repoPath:string, appId?:string, name?:string, actions?:object}} repo
+ * @param {{activeAgentIds?:Set<string>}} [deps]
+ * @returns {Promise<object>} per-repo result
+ */
+export async function syncRepo(repo, { activeAgentIds = new Set() } = {}) {
+ const { repoPath, appId = null, name = repoPath, actions = {} } = repo;
+ const base = { appId, name, repoPath, performed: [], escalations: [] };
+
+ if (!repoPath || !existsSync(repoPath)) {
+ return { ...base, missing: true, escalations: [{ kind: ESCALATION_KINDS.SCAN_FAILED, detail: `repo path does not exist: ${repoPath || '(unset)'}` }] };
+ }
+
+ const state = await collectRepoState(repoPath).catch((err) => ({ repoPath, isRepo: true, scanError: err.message }));
+ if (state.scanError) {
+ return { ...base, escalations: [{ kind: ESCALATION_KINDS.SCAN_FAILED, detail: state.scanError }] };
+ }
+ if (!state.isRepo) return { ...base, notARepo: true };
+
+ const { steps, escalations } = planRepoSync(state, actions);
+ const performed = [];
+ for (const step of steps) {
+ const result = await runStep(repoPath, step);
+ if (result.ok) {
+ performed.push(describeStep(step));
+ } else {
+ escalations.push({
+ kind: ESCALATION_KINDS.ACTION_FAILED,
+ detail: `${describeStep(step)} FAILED: ${result.detail}`
+ });
+ }
+ }
+
+ // Merged-branch + worktree cleanup is branchReconcile's job and its safety
+ // gates (locked worktrees, live claims, running agents, dirty trees) are the
+ // ones this task wants — so delegate rather than re-derive them. Its
+ // classified `inFlight` set is REPORTED, not driven: see the scope boundary in
+ // the module header for why finishing those branches belongs to
+ // branch-reconcile and not here.
+ if (actionOn(actions, 'cleanupMerged') && !state.operationInProgress) {
+ const { reconcile } = await import('./branchReconcile.js');
+ const result = await reconcile(repoPath, {
+ cleanup: true,
+ reapRemotes: actions.reapRemotes === true,
+ activeAgentIds
+ }).catch((err) => {
+ escalations.push({ kind: ESCALATION_KINDS.SCAN_FAILED, detail: `branch cleanup failed: ${err.message}` });
+ return null;
+ });
+ if (result) {
+ for (const branch of result.cleaned || []) performed.push(`deleted merged branch/worktree ${branch}`);
+ for (const entry of result.inFlight || []) {
+ escalations.push({
+ kind: ESCALATION_KINDS.IN_FLIGHT_BRANCH,
+ detail: `${entry.branch} is ${entry.state} — unfinished work that has not landed on ${state.defaultBranch}`
+ });
+ }
+ for (const entry of result.orphanRemotes?.reported || []) {
+ const branch = typeof entry === 'string' ? entry : entry.branch;
+ if (branch) {
+ escalations.push({
+ kind: ESCALATION_KINDS.ORPHAN_REMOTE,
+ detail: `origin/${branch} exists on the remote with nothing local pointing at it`
+ });
+ }
+ }
+ for (const branch of result.orphanRemotes?.reaped || []) performed.push(`deleted merged orphan remote branch origin/${branch}`);
+ }
+ }
+
+ return {
+ ...base,
+ defaultBranch: state.defaultBranch,
+ currentBranch: state.currentBranch,
+ performed,
+ escalations
+ };
+}
+
+/**
+ * Sweep every repo in `repos`, sequentially. Sequential on purpose: these are
+ * network + working-tree operations against the user's real checkouts, and a
+ * parallel sweep interleaves push output and git index locks across repos that
+ * may share a worktree parent.
+ *
+ * @param {{repoPath:string, appId?:string, name?:string, actions?:object}[]} repos
+ * @param {{activeAgentIds?:Set<string>}} [deps]
+ * @returns {Promise<object[]>}
+ */
+export async function syncRepos(repos, { activeAgentIds = new Set() } = {}) {
+ const results = [];
+ for (const repo of repos) {
+ results.push(await syncRepo(repo, { activeAgentIds }));
+ }
+ return results;
+}
+
+// ============================================================
+// Reporting
+// ============================================================
+
+/**
+ * Roll a sweep up into the numbers the caller's dispatch decision needs. Pure.
+ * @param {object[]} results
+ * @returns {{repos:number, mutated:number, actionCount:number, escalated:number, escalationCount:number}}
+ */
+export function summarizeSync(results) {
+ const list = Array.isArray(results) ? results : [];
+ return {
+ repos: list.length,
+ mutated: list.filter((r) => r.performed?.length).length,
+ actionCount: list.reduce((n, r) => n + (r.performed?.length || 0), 0),
+ escalated: list.filter((r) => r.escalations?.length).length,
+ escalationCount: list.reduce((n, r) => n + (r.escalations?.length || 0), 0)
+ };
+}
+
+/**
+ * Whether a coordinator agent should be dispatched after this sweep.
+ *
+ * An escalation ALWAYS dispatches — that is the "hit a conflict / found
+ * unfinished work" case the user asked to route to an agent. Beyond that the
+ * verify mode decides, and the default (`when-changed`) buys the double-check
+ * only for runs that actually changed something, so a scheduled sweep over an
+ * already-clean machine makes no provider call at all. Pure.
+ *
+ * @param {object} summary - `summarizeSync` output
+ * @param {string} [verifyMode]
+ * @returns {{dispatch:boolean, reason:string}}
+ */
+export function shouldDispatchVerifier(summary, verifyMode = DEFAULT_REPO_SYNC_VERIFY_MODE) {
+ if (summary.escalationCount > 0) {
+ return { dispatch: true, reason: `${summary.escalationCount} unresolved item(s) across ${summary.escalated} repo(s)` };
+ }
+ const mode = REPO_SYNC_VERIFY_MODES.includes(verifyMode) ? verifyMode : DEFAULT_REPO_SYNC_VERIFY_MODE;
+ if (mode === 'always') return { dispatch: true, reason: 'verify mode is `always`' };
+ if (mode === 'when-changed' && summary.actionCount > 0) {
+ return { dispatch: true, reason: `${summary.actionCount} action(s) applied across ${summary.mutated} repo(s) — verifying` };
+ }
+ return { dispatch: false, reason: mode === 'never' ? 'nothing to escalate (verify mode `never`)' : 'every repo was already in sync — nothing to verify' };
+}
+
+/**
+ * Render the sweep as the `{repoSyncReport}` block injected into the coordinator
+ * prompt. Pure.
+ * @param {object[]} results
+ * @param {{verifyReason?:string}} [opts]
+ * @returns {string}
+ */
+export function formatRepoSyncReport(results, { verifyReason = '' } = {}) {
+ const list = Array.isArray(results) ? results : [];
+ const summary = summarizeSync(list);
+ const lines = [
+ '## Programmatic sync pass — already applied',
+ '',
+ `Swept ${summary.repos} repo(s): ${summary.actionCount} action(s) applied, ${summary.escalationCount} item(s) left for you.`,
+ ];
+ if (verifyReason) lines.push('', `Dispatched because: ${verifyReason}.`);
+
+ for (const repo of list) {
+ lines.push('', `### ${repo.name}${repo.appId ? ` (${repo.appId})` : ''}`, `- Path: \`${repo.repoPath}\``);
+ if (repo.missing) { lines.push('- **Repo path does not exist.**'); continue; }
+ if (repo.notARepo) { lines.push('- Not a git repository — skipped.'); continue; }
+ lines.push(`- Branch: \`${repo.currentBranch || 'DETACHED'}\` (default: \`${repo.defaultBranch}\`)`);
+ if (repo.performed.length) {
+ lines.push('- Applied automatically:');
+ for (const action of repo.performed) lines.push(` - ${action}`);
+ } else {
+ lines.push('- Applied automatically: nothing (already in sync)');
+ }
+ if (repo.escalations.length) {
+ lines.push('- **Needs your judgment:**');
+ for (const esc of repo.escalations) lines.push(` - \`${esc.kind}\` — ${esc.detail}`);
+ } else {
+ lines.push('- Needs your judgment: nothing');
+ }
+ }
+ return lines.join('\n');
+}
+
+/**
+ * Resolve the repos a sweep covers from the managed-app registry.
+ *
+ * OPT-OUT, not opt-in: the whole point of this task is "every managed app", so
+ * an app is included unless it explicitly carries
+ * `taskTypeOverrides['repo-sync'].taskMetadata.skipRepoSync === true`.
+ *
+ * Deliberately NOT the neighbouring `enabled` flag, and not
+ * `isTaskTypeEnabledForApp`: both express the opt-IN convention the per-app
+ * SCHEDULED tasks want, and `createApp` seeds `{ enabled: false }` for every
+ * task type — so `enabled` cannot tell "leave this repo alone" apart from "never
+ * configured", and either reading would sweep nothing at all on a fresh install.
+ *
+ * Apps with no `repoPath` are skipped silently — an app registered for process
+ * management alone has no repo to sync. Two apps pointing at one checkout are
+ * swept once.
+ *
+ * @param {object[]} apps - `getActiveApps()` output
+ * @param {object} [actions] - schedule-level action toggles applied to each repo
+ * @returns {{repoPath:string, appId:string, name:string, actions:object}[]}
+ */
+export function resolveSyncTargets(apps, actions = {}) {
+ const seen = new Set();
+ const targets = [];
+ for (const app of apps || []) {
+ const repoPath = app?.repoPath;
+ if (!repoPath) continue;
+ // This reads the RAW app record, so the override goes through the same two
+ // steps a scheduled dispatch applies: drop the agent-options the task type
+ // manages internally (they are locked, and would otherwise ride along into
+ // the actions bag), then value-constrain what's left.
+ const override = sanitizeTaskMetadata(
+ stripManagedAgentOptionsFromOverride('repo-sync', app?.taskTypeOverrides?.['repo-sync']?.taskMetadata)
+ ) || {};
+ if (override.skipRepoSync === true) continue;
+ const key = resolve(repoPath);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ targets.push({
+ repoPath,
+ appId: app.id,
+ name: app.name || app.id,
+ // A per-app override may switch an individual action off for one repo
+ // (e.g. leave one checkout's stashes alone) without opting the repo out.
+ actions: { ...actions, ...override }
+ });
+ }
+ return targets;
+}
diff --git a/server/services/repoSync.test.js b/server/services/repoSync.test.js
new file mode 100644
index 0000000000..7efd285971
--- /dev/null
+++ b/server/services/repoSync.test.js
@@ -0,0 +1,657 @@
+/**
+ * Unit tests for the repo-sync deterministic core.
+ *
+ * The contract under test is a SAFETY contract, so the assertions are about the
+ * decisions and the exact git argv, never about re-deriving the implementation:
+ *
+ * - planRepoSync — the pure decision table. Which shapes earn an automatic step
+ * and which are handed to the agent instead.
+ * - the executor — that the argv it issues is the non-destructive form
+ * (`--ff-only`, a `<b>:<b>` refspec, a plain push with no `--force`), and that
+ * a stash drop re-verifies the sha it resolved during the scan.
+ * - classifyStash — a stash is "superseded" only when it is provably a no-op.
+ * - shouldDispatchVerifier — when an agent is spawned at all.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const execGitMock = vi.fn(async () => ({ stdout: '', stderr: '', exitCode: 0 }));
+vi.mock('../lib/execGit.js', () => ({ execGit: (...args) => execGitMock(...args) }));
+
+const gitMocks = {
+ // execGitSafe is git.js's own catch-into-a-failed-result wrapper; the suite
+ // routes it at the same mock so argv assertions see every call.
+ execGitSafe: vi.fn((...args) => execGitMock(...args)),
+ fetchOrigin: vi.fn(async () => undefined),
+ findActiveAgentInWorkspace: vi.fn(async () => null),
+ getBranch: vi.fn(async () => 'main'),
+ getBranches: vi.fn(async () => []),
+ getDefaultBranch: vi.fn(async () => 'main'),
+ getStatusPorcelain: vi.fn(async () => ''),
+ isBranchMergedInto: vi.fn(async () => false),
+ isRepo: vi.fn(async () => true)
+};
+vi.mock('./git.js', () => gitMocks);
+vi.mock('../lib/gitRemote.js', () => ({
+ getOriginInfo: vi.fn(async () => ({ hasOrigin: true, host: 'github.com' }))
+}));
+const reconcileMock = vi.fn(async () => ({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [], orphanRemotes: { reaped: [], reported: [] } }));
+vi.mock('./branchReconcile.js', () => ({ reconcile: (...args) => reconcileMock(...args) }));
+
+const {
+ ESCALATION_KINDS,
+ MAX_STASH_PATHS_FOR_AUTO_CLASSIFY,
+ classifyStash,
+ describeStep,
+ formatRepoSyncReport,
+ parseStashList,
+ planRepoSync,
+ resolveSyncTargets,
+ shouldDispatchVerifier,
+ dirtyTrackedPaths,
+ stashIndex,
+ summarizeSync,
+ syncRepo
+} = await import('./repoSync.js');
+
+/** A snapshot in the fully-synced end state; each test perturbs one thing. */
+const cleanState = (over = {}) => ({
+ repoPath: '/tmp/example-repo',
+ isRepo: true,
+ fetchError: null,
+ defaultBranch: 'main',
+ remoteDefault: 'origin/main',
+ currentBranch: 'main',
+ operationInProgress: null,
+ dirtyTracked: [],
+ branches: [{ name: 'main', current: true, tracking: 'origin/main', ahead: 0, behind: 0, isDefault: true, merged: false, worktree: false }],
+ defaultDivergence: { ahead: 0, behind: 0 },
+ stashes: [],
+ activeAgentId: null,
+ currentBranchMerged: false,
+ ...over
+});
+
+const branch = (name, over = {}) => ({
+ name, current: false, tracking: `origin/${name}`, ahead: 0, behind: 0, isDefault: false, merged: false, worktree: false, ...over
+});
+
+const kinds = (escalations) => escalations.map((e) => e.kind);
+const stepKinds = (steps) => steps.map((s) => s.kind);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ execGitMock.mockResolvedValue({ stdout: '', stderr: '', exitCode: 0 });
+ reconcileMock.mockResolvedValue({ defaultBranch: 'main', cleaned: [], inFlight: [], wip: [], skipped: [], orphanRemotes: { reaped: [], reported: [] } });
+});
+
+describe('dirtyTrackedPaths', () => {
+ it('keeps tracked changes and drops untracked ones', () => {
+ expect(dirtyTrackedPaths(' M server/index.js\n?? scratch.txt\nA new.js\n'))
+ .toEqual(['server/index.js', 'new.js']);
+ });
+
+ it('reports the post-rename name, not both halves as one path', () => {
+ expect(dirtyTrackedPaths('R server/old.js -> server/new.js\n')).toEqual(['server/new.js']);
+ });
+
+ it('is empty for a clean tree', () => {
+ expect(dirtyTrackedPaths('')).toEqual([]);
+ });
+});
+
+describe('parseStashList', () => {
+ it('parses ref, sha, parent count and message', () => {
+ const parsed = parseStashList('stash@{0}\x1fabc123\x1fp1 p2\x1fWIP on main: 1234 subject\nstash@{1}\x1fdef456\x1fp1 p2 p3\x1fOn feature: notes');
+ expect(parsed).toEqual([
+ { ref: 'stash@{0}', sha: 'abc123', parentCount: 2, message: 'WIP on main: 1234 subject' },
+ // Three parents ⇒ taken with `-u`, so it also carries untracked files.
+ { ref: 'stash@{1}', sha: 'def456', parentCount: 3, message: 'On feature: notes' }
+ ]);
+ });
+
+ it('drops malformed lines rather than yielding a half-parsed entry', () => {
+ expect(parseStashList('garbage\n\nstash@{0}\x1fabc\x1fp1 p2\x1fmsg')).toHaveLength(1);
+ });
+
+ it('keeps a message containing the separator intact', () => {
+ const [entry] = parseStashList('stash@{0}\x1fabc\x1fp1 p2\x1fa\x1fb');
+ expect(entry.message).toBe('a\x1fb');
+ });
+});
+
+describe('stashIndex', () => {
+ it('reads the numeric index and rejects anything else', () => {
+ expect(stashIndex('stash@{3}')).toBe(3);
+ expect(stashIndex('refs/stash')).toBe(-1);
+ expect(stashIndex(undefined)).toBe(-1);
+ });
+});
+
+describe('planRepoSync — refuses to act on an unsettled repo', () => {
+ it('plans nothing at all while a rebase is in progress', () => {
+ const { steps, escalations } = planRepoSync(cleanState({
+ operationInProgress: 'rebase',
+ currentBranch: 'feature/x',
+ dirtyTracked: ['a.js'],
+ defaultDivergence: { ahead: 0, behind: 4 }
+ }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.OPERATION_IN_PROGRESS]);
+ expect(escalations[0].detail).toContain('rebase');
+ });
+
+ it('reports a failed fetch without blocking the rest of the plan', () => {
+ const { escalations } = planRepoSync(cleanState({ fetchError: 'could not read from remote' }));
+ expect(kinds(escalations)).toContain(ESCALATION_KINDS.SCAN_FAILED);
+ });
+
+ it('does nothing to a repo that is already in the target state', () => {
+ const { steps, escalations } = planRepoSync(cleanState());
+ expect(steps).toEqual([]);
+ expect(escalations).toEqual([]);
+ });
+});
+
+describe('planRepoSync — publishing local commits', () => {
+ it('pushes a branch that is strictly ahead of its upstream', () => {
+ const { steps } = planRepoSync(cleanState({ branches: [branch('feature/x', { ahead: 2 })] }));
+ expect(steps).toEqual([{ kind: 'push', branch: 'feature/x', ahead: 2 }]);
+ });
+
+ it('never pushes a branch that has diverged — it escalates instead', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ branches: [branch('feature/x', { ahead: 2, behind: 3 })] }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.DIVERGED_BRANCH]);
+ });
+
+ it('escalates local commits on a branch with no upstream', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ branches: [branch('feature/x', { tracking: null, ahead: 4 })] }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.UNPUSHED_BRANCH]);
+ expect(escalations[0].detail).toContain('4 local commit(s)');
+ });
+
+ it('ignores an upstream-less branch carrying no commits of its own', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ branches: [branch('scratch', { tracking: null, ahead: 0 })] }));
+ expect(steps).toEqual([]);
+ expect(escalations).toEqual([]);
+ });
+
+ it('honours syncPush: false', () => {
+ const { steps } = planRepoSync(cleanState({ branches: [branch('feature/x', { ahead: 2 })] }), { syncPush: false });
+ expect(steps).toEqual([]);
+ });
+});
+
+describe('planRepoSync — the default branch', () => {
+ it('fast-forwards a default branch that is only behind', () => {
+ const { steps } = planRepoSync(cleanState({ defaultDivergence: { ahead: 0, behind: 5 } }));
+ expect(steps).toEqual([{ kind: 'ff-default', branch: 'main', behind: 5, checkedOut: true }]);
+ });
+
+ it('marks the fast-forward as not-checked-out when the checkout is elsewhere and stays', () => {
+ const { steps } = planRepoSync(cleanState({
+ currentBranch: 'feature/x',
+ currentBranchMerged: false,
+ branches: [branch('feature/x', { current: true, ahead: 0 })],
+ defaultDivergence: { ahead: 0, behind: 1 }
+ }));
+ expect(steps).toContainEqual({ kind: 'ff-default', branch: 'main', behind: 1, checkedOut: false });
+ });
+
+ it('never resolves a diverged default branch automatically', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ defaultDivergence: { ahead: 2, behind: 3 } }));
+ expect(stepKinds(steps)).not.toContain('ff-default');
+ expect(kinds(escalations)).toContain(ESCALATION_KINDS.DIVERGED_DEFAULT);
+ });
+
+ it('refuses to fast-forward the checked-out default branch over a dirty tree', () => {
+ const { steps, escalations } = planRepoSync(cleanState({
+ dirtyTracked: ['a.js'],
+ defaultDivergence: { ahead: 0, behind: 2 }
+ }));
+ expect(stepKinds(steps)).not.toContain('ff-default');
+ // Reported ONCE. A second escalation for the same dirty tree would inflate
+ // the count that drives both the dispatch reason and the "N items left for
+ // you" line the coordinator prompt shows.
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.UNCOMMITTED_CHANGES]);
+ });
+
+ it('honours syncPull: false', () => {
+ const { steps } = planRepoSync(cleanState({ defaultDivergence: { ahead: 0, behind: 5 } }), { syncPull: false });
+ expect(steps).toEqual([]);
+ });
+});
+
+describe('planRepoSync — returning to the default branch', () => {
+ const offDefault = (over = {}) => cleanState({
+ currentBranch: 'feature/x',
+ branches: [branch('feature/x', { current: true })],
+ ...over
+ });
+
+ it('switches back when the branch is clean and already merged', () => {
+ const { steps, escalations } = planRepoSync(offDefault({ currentBranchMerged: true }));
+ expect(steps).toEqual([{ kind: 'switch-default', from: 'feature/x', to: 'main' }]);
+ expect(escalations).toEqual([]);
+ });
+
+ it('will not switch away from uncommitted work', () => {
+ const { steps, escalations } = planRepoSync(offDefault({ currentBranchMerged: true, dirtyTracked: ['a.js'] }));
+ expect(stepKinds(steps)).not.toContain('switch-default');
+ expect(kinds(escalations)).toContain(ESCALATION_KINDS.OFF_DEFAULT_BRANCH);
+ });
+
+ it('will not switch a checkout an agent is running in', () => {
+ const { steps, escalations } = planRepoSync(offDefault({ currentBranchMerged: true, activeAgentId: 'agent-7' }));
+ expect(stepKinds(steps)).not.toContain('switch-default');
+ expect(escalations.find((e) => e.kind === ESCALATION_KINDS.OFF_DEFAULT_BRANCH).detail).toContain('agent-7');
+ });
+
+ it('will not switch off a branch whose work has not landed', () => {
+ const { steps, escalations } = planRepoSync(offDefault({ currentBranchMerged: false }));
+ expect(stepKinds(steps)).not.toContain('switch-default');
+ expect(escalations.find((e) => e.kind === ESCALATION_KINDS.OFF_DEFAULT_BRANCH).detail).toContain('not in main yet');
+ });
+
+ it('honours switchDefault: false', () => {
+ const { steps } = planRepoSync(offDefault({ currentBranchMerged: true }), { switchDefault: false });
+ expect(steps).toEqual([]);
+ });
+
+ it('escalates a detached HEAD instead of switching', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ currentBranch: null }));
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.DETACHED_HEAD]);
+ });
+});
+
+describe('planRepoSync — stashes', () => {
+ const stash = (index, superseded) => ({
+ ref: `stash@{${index}}`, sha: `sha${index}`, message: `entry ${index}`, superseded, reason: superseded ? 'identical' : 'differs', paths: 1
+ });
+
+ it('drops only the provably-redundant entries, highest index first', () => {
+ const { steps, escalations } = planRepoSync(cleanState({
+ stashes: [stash(0, true), stash(1, false), stash(2, true)]
+ }));
+ // Descending order matters: `git stash drop` renumbers everything below the
+ // entry it removes, so a low-index drop invalidates the refs queued after it.
+ expect(steps.map((s) => s.ref)).toEqual(['stash@{2}', 'stash@{0}']);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.STASH_ENTRIES]);
+ // The refs have to reach the agent — a bare count would not tell it WHICH.
+ expect(escalations[0].detail).toContain('stash@{1} "entry 1" (differs)');
+ expect(escalations[0].detail).not.toContain('stash@{0}');
+ });
+
+ it('reports but never drops when dropStashes is off', () => {
+ const { steps, escalations } = planRepoSync(cleanState({ stashes: [stash(0, true), stash(1, false)] }), { dropStashes: false });
+ expect(steps).toEqual([]);
+ expect(kinds(escalations)).toEqual([ESCALATION_KINDS.STASH_ENTRIES]);
+ });
+
+ it('leaves no escalation when every entry was redundant', () => {
+ const { escalations } = planRepoSync(cleanState({ stashes: [stash(0, true)] }));
+ expect(escalations).toEqual([]);
+ });
+});
+
+describe('classifyStash', () => {
+ /** Route each git call by its subcommand + args so order doesn't matter. */
+ const scriptGit = (handlers) => {
+ execGitMock.mockImplementation(async (args) => {
+ for (const [match, result] of handlers) {
+ if (args.join(' ').includes(match)) return { stdout: '', stderr: '', exitCode: 0, ...result };
+ }
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ };
+
+ it('treats a stash that records no change as redundant', async () => {
+ scriptGit([['diff --name-only', { stdout: '' }], ['ls-tree', { exitCode: 128 }]]);
+ const verdict = await classifyStash('/repo', 'sha1', 'origin/main');
+ expect(verdict).toEqual({ superseded: true, reason: 'empty stash (no changes recorded)' });
+ });
+
+ it('is redundant when every touched path is identical on the target', async () => {
+ scriptGit([
+ ['diff --name-only', { stdout: 'a.js\nb.js\n' }],
+ ['ls-tree', { exitCode: 128 }],
+ ['diff --quiet', { exitCode: 0 }]
+ ]);
+ const verdict = await classifyStash('/repo', 'sha1', 'origin/main');
+ expect(verdict.superseded).toBe(true);
+ expect(verdict.reason).toContain('all 2 path(s)');
+ // The comparison must be scoped to the stash's own paths — an unscoped diff
+ // would compare the whole worktree and never come back clean.
+ const diffCall = execGitMock.mock.calls.map(([args]) => args).find((args) => args[0] === 'diff' && args.includes('--quiet'));
+ expect(diffCall).toEqual(['diff', '--quiet', 'sha1', 'origin/main', '--', 'a.js', 'b.js']);
+ });
+
+ it('is NOT redundant when the target differs', async () => {
+ scriptGit([
+ ['diff --name-only', { stdout: 'a.js\n' }],
+ ['ls-tree', { exitCode: 128 }],
+ ['diff --quiet', { exitCode: 1 }]
+ ]);
+ expect((await classifyStash('/repo', 'sha1', 'origin/main')).superseded).toBe(false);
+ });
+
+ it('includes the untracked snapshot from the third parent in the comparison', async () => {
+ scriptGit([
+ ['diff --name-only', { stdout: 'a.js\n' }],
+ ['ls-tree', { stdout: 'scratch/new.txt\n' }],
+ ['diff --quiet', { exitCode: 1 }]
+ ]);
+ await classifyStash('/repo', 'sha1', 'origin/main', 3);
+ const diffCall = execGitMock.mock.calls.map(([args]) => args).find((args) => args[0] === 'diff' && args.includes('--quiet'));
+ expect(diffCall).toContain('scratch/new.txt');
+ });
+
+ it('skips the third-parent read for a stash that has no untracked half', async () => {
+ // Every stash NOT taken with `-u` has two parents, so `<sha>^3` cannot
+ // resolve — spawning it is a guaranteed failure per ordinary stash.
+ scriptGit([['diff --name-only', { stdout: 'a.js\n' }], ['diff --quiet', { exitCode: 0 }]]);
+ await classifyStash('/repo', 'sha1', 'origin/main', 2);
+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'ls-tree')).toBe(false);
+ });
+
+ it('refuses to auto-classify a stash too large to compare in one spawn', async () => {
+ const many = Array.from({ length: MAX_STASH_PATHS_FOR_AUTO_CLASSIFY + 1 }, (_, i) => `f${i}.js`).join('\n');
+ scriptGit([['diff --name-only', { stdout: many }], ['ls-tree', { exitCode: 128 }]]);
+ const verdict = await classifyStash('/repo', 'sha1', 'origin/main');
+ expect(verdict.superseded).toBe(false);
+ expect(verdict.reason).toContain('too large');
+ expect(execGitMock.mock.calls.some(([args]) => args.includes('--quiet'))).toBe(false);
+ });
+
+ it('fails closed when git errors out', async () => {
+ scriptGit([['diff --name-only', { stdout: 'a.js\n' }], ['ls-tree', { exitCode: 128 }], ['diff --quiet', { exitCode: 129 }]]);
+ expect((await classifyStash('/repo', 'sha1', 'origin/main')).superseded).toBe(false);
+ });
+});
+
+describe('syncRepo — the argv it issues is the non-destructive form', () => {
+ /**
+ * Drive syncRepo through a scripted snapshot by stubbing the reads
+ * collectRepoState makes, then assert the WRITE commands.
+ */
+ const arrange = ({ porcelain = '', branches = [], stashList = '', current = 'main', divergence = '0\t0' } = {}) => {
+ gitMocks.getBranches.mockResolvedValue(branches);
+ gitMocks.getStatusPorcelain.mockResolvedValue(porcelain);
+ gitMocks.getBranch.mockResolvedValue(current);
+ execGitMock.mockImplementation(async (args) => {
+ const line = args.join(' ');
+ if (line.startsWith('rev-parse --git-dir')) return { stdout: '.git', stderr: '', exitCode: 0 };
+ if (line.startsWith('rev-list')) return { stdout: divergence, stderr: '', exitCode: 0 };
+ if (line.startsWith('stash list')) return { stdout: stashList, stderr: '', exitCode: 0 };
+ return { stdout: '', stderr: '', exitCode: 0 };
+ });
+ };
+ // Only the MUTATING commands — the scan's `stash list` is a read, and the
+ // pruning fetch goes through git.js's `fetchOrigin`, not execGit. A refspec
+ // fetch (`main:main`) IS a write: it moves a local branch ref.
+ const writeCalls = () => execGitMock.mock.calls
+ .map(([args]) => args)
+ .filter((args) => ['push', 'checkout', 'merge'].includes(args[0])
+ || (args[0] === 'stash' && args[1] === 'drop')
+ || (args[0] === 'fetch' && args.some((a) => a.includes(':'))));
+
+ it('pushes without --force and fast-forwards with --ff-only', async () => {
+ // behind lands on the BRANCH entry: the snapshot reads the default branch's
+ // divergence from what `getBranches` already parsed, and only falls back to a
+ // `rev-list` spawn when the default branch tracks something else (exercised by
+ // the next test, where `main` is absent from the branch list).
+ arrange({ branches: [{ name: 'main', current: true, tracking: 'origin/main', ahead: 0, behind: 3, isDefault: true, merged: false }] });
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(writeCalls()).toEqual([['merge', '--ff-only', 'origin/main']]);
+ expect(result.performed).toEqual(['fast-forwarded main (3 behind origin)']);
+ expect(execGitMock.mock.calls.some(([args]) => args.includes('--force') || args.includes('-f'))).toBe(false);
+ });
+
+ it('updates a non-checked-out default branch with a refspec fetch git itself refuses to non-FF', async () => {
+ gitMocks.isBranchMergedInto.mockResolvedValue(false);
+ arrange({
+ current: 'feature/x',
+ branches: [{ name: 'feature/x', current: true, tracking: 'origin/feature/x', ahead: 0, behind: 0, isDefault: false, merged: false }],
+ divergence: '2\t0'
+ });
+ await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(writeCalls()).toEqual([['fetch', 'origin', 'main:main']]);
+ });
+
+ it('does not merge the default branch INTO a feature branch when the switch back fails', async () => {
+ // The plan queues switch-default then ff-default and predicts the checkout
+ // will be on main by then. If the checkout is refused, a `merge --ff-only
+ // origin/main` issued anyway would land main's commits ON the feature
+ // branch — a real change to the wrong branch. The executor re-reads HEAD.
+ gitMocks.isBranchMergedInto.mockResolvedValue(true);
+ arrange({
+ current: 'feature/x',
+ divergence: '2\t0',
+ branches: [{ name: 'feature/x', current: true, tracking: 'origin/feature/x', ahead: 0, behind: 0, isDefault: false, merged: false }]
+ });
+ const base = execGitMock.getMockImplementation();
+ // The checkout is refused (an untracked file would be overwritten), so HEAD
+ // never moves off the feature branch.
+ execGitMock.mockImplementation(async (args) => {
+ if (args[0] === 'checkout') return { stdout: '', stderr: 'error: Your local changes would be overwritten', exitCode: 1 };
+ return base(args);
+ });
+
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(writeCalls()).toEqual([['checkout', 'main'], ['fetch', 'origin', 'main:main']]);
+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'merge')).toBe(false);
+ expect(result.escalations.map((e) => e.kind)).toContain(ESCALATION_KINDS.ACTION_FAILED);
+ expect(result.performed).toContain('fast-forwarded main (2 behind origin)');
+ });
+
+ it('records a failed step as an action-failed escalation instead of throwing', async () => {
+ arrange({ branches: [{ name: 'feature/x', current: false, tracking: 'origin/feature/x', ahead: 1, behind: 0, isDefault: false, merged: false }] });
+ const base = execGitMock.getMockImplementation();
+ execGitMock.mockImplementation(async (args) => {
+ if (args[0] === 'push') return { stdout: '', stderr: '! [rejected] feature/x -> feature/x (fetch first)', exitCode: 1 };
+ return base(args);
+ });
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(result.performed).toEqual([]);
+ expect(result.escalations.map((e) => e.kind)).toEqual([ESCALATION_KINDS.ACTION_FAILED]);
+ expect(result.escalations[0].detail).toContain('rejected');
+ });
+
+ it('re-verifies a stash sha before dropping it and skips a shifted ref', async () => {
+ arrange({ stashList: 'stash@{0}\x1fSTASH_SHA\x1fp1 p2\x1fWIP' });
+ const base = execGitMock.getMockImplementation();
+ execGitMock.mockImplementation(async (args) => {
+ const line = args.join(' ');
+ // Prove the stash redundant during the scan…
+ if (line.startsWith('diff --name-only')) return { stdout: 'a.js\n', stderr: '', exitCode: 0 };
+ if (line.startsWith('ls-tree')) return { stdout: '', stderr: '', exitCode: 128 };
+ if (line.startsWith('diff --quiet')) return { stdout: '', stderr: '', exitCode: 0 };
+ // …then have the ref resolve to something else at drop time.
+ if (line === 'rev-parse stash@{0}') return { stdout: 'OTHER_SHA', stderr: '', exitCode: 0 };
+ return base(args);
+ });
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(execGitMock.mock.calls.some(([args]) => args[0] === 'stash' && args[1] === 'drop')).toBe(false);
+ expect(result.escalations[0].detail).toContain('no longer points at');
+ });
+
+ it('carries branchReconcile cleanup and in-flight branches through', async () => {
+ arrange();
+ reconcileMock.mockResolvedValue({
+ defaultBranch: 'main',
+ cleaned: ['feature/done'],
+ inFlight: [{ branch: 'feature/wip', state: 'NEEDS_PR' }],
+ wip: [],
+ skipped: [],
+ orphanRemotes: { reaped: ['feature/gone'], reported: [{ branch: 'feature/orphan' }] }
+ });
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(result.performed).toContain('deleted merged branch/worktree feature/done');
+ expect(result.performed).toContain('deleted merged orphan remote branch origin/feature/gone');
+ expect(result.escalations.map((e) => e.kind)).toEqual([ESCALATION_KINDS.IN_FLIGHT_BRANCH, ESCALATION_KINDS.ORPHAN_REMOTE]);
+ });
+
+ it('only reaps remote branches when reapRemotes is explicitly on', async () => {
+ arrange();
+ await syncRepo({ repoPath: process.cwd(), name: 'Example' });
+ expect(reconcileMock.mock.calls[0][1].reapRemotes).toBe(false);
+ reconcileMock.mockClear();
+ await syncRepo({ repoPath: process.cwd(), name: 'Example', actions: { reapRemotes: true } });
+ expect(reconcileMock.mock.calls[0][1].reapRemotes).toBe(true);
+ });
+
+ it('skips branch cleanup entirely when cleanupMerged is off', async () => {
+ arrange();
+ await syncRepo({ repoPath: process.cwd(), name: 'Example', actions: { cleanupMerged: false } });
+ expect(reconcileMock).not.toHaveBeenCalled();
+ });
+
+ it('reports a missing repo path rather than running git in the wrong directory', async () => {
+ const result = await syncRepo({ repoPath: '/nope/does/not/exist', name: 'Ghost' });
+ expect(result.missing).toBe(true);
+ expect(result.escalations[0].kind).toBe(ESCALATION_KINDS.SCAN_FAILED);
+ expect(execGitMock).not.toHaveBeenCalled();
+ });
+
+ it('skips a directory that is not a git repository', async () => {
+ gitMocks.isRepo.mockResolvedValueOnce(false);
+ const result = await syncRepo({ repoPath: process.cwd(), name: 'Not a repo' });
+ expect(result.notARepo).toBe(true);
+ expect(result.escalations).toEqual([]);
+ });
+});
+
+describe('describeStep', () => {
+ it('names each step in the terms the report uses', () => {
+ expect(describeStep({ kind: 'push', branch: 'feature/x', ahead: 2 })).toContain('pushed feature/x');
+ expect(describeStep({ kind: 'switch-default', from: 'feature/x', to: 'main' })).toContain('feature/x to main');
+ expect(describeStep({ kind: 'drop-stash', ref: 'stash@{0}', reason: 'identical' })).toContain('stash@{0}');
+ });
+});
+
+describe('summarizeSync / shouldDispatchVerifier', () => {
+ const results = (over = []) => over;
+
+ it('counts repos, actions and escalations', () => {
+ const summary = summarizeSync(results([
+ { performed: ['a', 'b'], escalations: [] },
+ { performed: [], escalations: [{ kind: 'x' }] },
+ { performed: [], escalations: [] }
+ ]));
+ expect(summary).toMatchObject({ repos: 3, mutated: 1, actionCount: 2, escalated: 1, escalationCount: 1 });
+ });
+
+ it('always dispatches when something needs judgment, whatever the mode', () => {
+ const summary = summarizeSync([{ performed: [], escalations: [{ kind: 'x' }] }]);
+ for (const mode of ['always', 'when-changed', 'never']) {
+ expect(shouldDispatchVerifier(summary, mode).dispatch).toBe(true);
+ }
+ });
+
+ it('does not spawn an agent for a sweep that changed nothing', () => {
+ const summary = summarizeSync([{ performed: [], escalations: [] }]);
+ expect(shouldDispatchVerifier(summary, 'when-changed').dispatch).toBe(false);
+ expect(shouldDispatchVerifier(summary, 'never').dispatch).toBe(false);
+ expect(shouldDispatchVerifier(summary, 'always').dispatch).toBe(true);
+ });
+
+ it('verifies a run that mutated something under the default mode', () => {
+ const summary = summarizeSync([{ performed: ['pushed x'], escalations: [] }]);
+ expect(shouldDispatchVerifier(summary).dispatch).toBe(true);
+ expect(shouldDispatchVerifier(summary, 'never').dispatch).toBe(false);
+ });
+
+ it('falls back to the default mode for an unrecognized value', () => {
+ const summary = summarizeSync([{ performed: ['pushed x'], escalations: [] }]);
+ expect(shouldDispatchVerifier(summary, 'whenever-i-feel-like-it').dispatch).toBe(true);
+ });
+});
+
+describe('formatRepoSyncReport', () => {
+ it('names every repo, what was applied and what was left', () => {
+ const report = formatRepoSyncReport([
+ { name: 'App One', appId: 'app-1', repoPath: '/repos/one', currentBranch: 'main', defaultBranch: 'main', performed: ['pushed feature/x (2 commit(s)) to origin'], escalations: [] },
+ { name: 'App Two', appId: 'app-2', repoPath: '/repos/two', currentBranch: 'feature/y', defaultBranch: 'main', performed: [], escalations: [{ kind: ESCALATION_KINDS.UNCOMMITTED_CHANGES, detail: '3 uncommitted change(s)' }] }
+ ], { verifyReason: '1 unresolved item(s)' });
+
+ expect(report).toContain('Swept 2 repo(s): 1 action(s) applied, 1 item(s) left for you.');
+ expect(report).toContain('Dispatched because: 1 unresolved item(s).');
+ expect(report).toContain('### App One (app-1)');
+ expect(report).toContain('pushed feature/x (2 commit(s)) to origin');
+ expect(report).toContain('`uncommitted-changes` — 3 uncommitted change(s)');
+ expect(report).toContain('Applied automatically: nothing (already in sync)');
+ });
+
+ it('calls out a repo whose path is gone', () => {
+ const report = formatRepoSyncReport([{ name: 'Ghost', repoPath: '/gone', missing: true, performed: [], escalations: [] }]);
+ expect(report).toContain('**Repo path does not exist.**');
+ });
+});
+
+describe('resolveSyncTargets', () => {
+ it('includes every managed app that has a repo path', () => {
+ const targets = resolveSyncTargets([
+ { id: 'a', name: 'App A', repoPath: '/repos/a' },
+ { id: 'b', name: 'App B', repoPath: '/repos/b' }
+ ]);
+ expect(targets.map((t) => t.appId)).toEqual(['a', 'b']);
+ });
+
+ it('is opt-OUT: only an explicit skipRepoSync excludes an app', () => {
+ const targets = resolveSyncTargets([
+ { id: 'a', name: 'App A', repoPath: '/repos/a', taskTypeOverrides: { 'repo-sync': { taskMetadata: { skipRepoSync: true } } } },
+ { id: 'b', name: 'App B', repoPath: '/repos/b', taskTypeOverrides: { 'other-task': { enabled: true } } },
+ { id: 'c', name: 'App C', repoPath: '/repos/c', taskTypeOverrides: {} }
+ ]);
+ expect(targets.map((t) => t.appId)).toEqual(['b', 'c']);
+ });
+
+ it('does not read the seeded per-app enabled flag as an opt-out', () => {
+ // createApp seeds `{ enabled: false }` for EVERY task type, so honouring it
+ // here would make the install-wide sweep visit nothing on a fresh install.
+ const targets = resolveSyncTargets([
+ { id: 'a', name: 'App A', repoPath: '/repos/a', taskTypeOverrides: { 'repo-sync': { enabled: false } } }
+ ]);
+ expect(targets.map((t) => t.appId)).toEqual(['a']);
+ });
+
+ it('skips apps with no repo and dedupes two apps sharing one checkout', () => {
+ const targets = resolveSyncTargets([
+ { id: 'a', name: 'App A', repoPath: '/repos/a' },
+ { id: 'b', name: 'App B' },
+ { id: 'c', name: 'App C', repoPath: '/repos/a/' }
+ ]);
+ expect(targets).toHaveLength(1);
+ expect(targets[0].appId).toBe('a');
+ });
+
+ it('layers a sanitized per-app override over the schedule-level toggles', () => {
+ const [target] = resolveSyncTargets(
+ [{ id: 'a', name: 'App A', repoPath: '/repos/a', taskTypeOverrides: { 'repo-sync': { taskMetadata: { dropStashes: false, notAnAllowedKey: true } } } }],
+ { syncPush: true, dropStashes: true }
+ );
+ expect(target.actions.syncPush).toBe(true);
+ expect(target.actions.dropStashes).toBe(false);
+ // The override is read off the RAW app record, so it must go through the
+ // same allowlist a scheduled dispatch uses.
+ expect(target.actions.notAnAllowedKey).toBeUndefined();
+ });
+
+ it('strips agent options the task type manages internally', () => {
+ // useWorktree/openPR/worktreeChangesExpected are locked for this task type;
+ // a per-app override must not smuggle them into the action bag.
+ const [target] = resolveSyncTargets([
+ { id: 'a', name: 'App A', repoPath: '/repos/a', taskTypeOverrides: { 'repo-sync': { taskMetadata: { useWorktree: true, openPR: true, syncPush: false } } } }
+ ]);
+ expect(target.actions.useWorktree).toBeUndefined();
+ expect(target.actions.openPR).toBeUndefined();
+ expect(target.actions.syncPush).toBe(false);
+ });
+
+ it('tolerates a missing app list', () => {
+ expect(resolveSyncTargets(null)).toEqual([]);
+ });
+});
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index 3e3ad92687..4ec72d2f98 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -25,6 +25,7 @@
"typing": "1f2758ce0bb62d789a21aec241549531",
"release-check": "64be10f6ac7bcf74d4fc257089fc179b",
"stash-cleanup": "1c12bac5aac6bb27008c40981e7db08c",
+ "repo-sync": "0a648d35d43b023b758226b9c709c8ea",
"jira-sprint-manager": "3e63c8a3bdf0d5a05a30faaa2dc07980",
"do-replan": "35660eb7b43e4259a6a9253ed288a1db",
"jira-status-report": "9d374a9d8ccb92c5c8fd0aa9899e79a5",
@@ -67,6 +68,7 @@
"data-safety": 1,
"simplify": 1,
"stash-cleanup": 2,
+ "repo-sync": 1,
"release-check": 11
},
"REFERENCE_WATCH_AUDITED_VERSION": 3,
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 83c1fe1f63..2fefeb4cf0 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -1582,6 +1582,48 @@ Run \`git stash list\`. For each \`stash@{N}\`:
Summarize: how many stashes were reviewed, how many were dropped (grouped by reason: superseded vs. stale/abandoned), and — for anything classified REAL UNLANDED WORK — what it is, which files it touches, and a recommendation (recover as a branch, cherry-pick specific hunks, or leave it for the user to decide). When in doubt about whether a stash is safe to drop, leave it in the stash and say so in the report rather than dropping it.`,
+ 'repo-sync': `[Improvement] Repo Sync — verify and finish the origin sync sweep
+
+A deterministic sweep has ALREADY run across every managed repository on this machine. It did everything it could prove safe: fetched, pushed branches strictly ahead of their upstream, fast-forwarded default branches, returned checkouts to their default branch where the current branch was clean and already merged, deleted merged branches + worktrees, and dropped stash entries whose content is byte-identical to the default branch.
+
+Your job is the part it refused to do: **finish what needs judgment, then verify the end state.** The target for every repo is — on the default branch, level with origin, no leftover local branches or worktrees, an empty stash list — **without losing any work.**
+
+{repoSyncReport}
+
+## Rules
+
+- **Never lose work.** No \`--force\` push, no \`reset --hard\`, no \`checkout -f\`, no \`stash clear\`, no \`clean -fd\`. If the only way forward would discard something unrecoverable, STOP and report it instead.
+- **Work in each repo's live checkout** (\`cd\` to the path listed for it). Do not create a worktree, do not commit application code, and do not open a PR for this task — its whole deliverable is repo state.
+- **Leave a checkout alone** when the report says an agent is running in it.
+- Re-run \`git status\`, \`git stash list\`, and \`git branch -vv\` yourself before acting — the report is a snapshot, and the sweep already changed things.
+
+## Handle each escalation kind
+
+- \`operation-in-progress\` — a merge/rebase/cherry-pick is half-finished. Read the conflicts. Resolve only the ones where one side is demonstrably a superset of the other (grep the file for the added identifiers and read the surrounding code — do not eyeball the diff). Where two live versions genuinely differ, run \`git rebase --abort\` / \`git merge --abort\` to return to the pre-operation state and report it — that is recoverable; a bad hand-merge is not.
+- \`uncommitted-changes\` — work the sweep found in the tree. Decide what it IS before touching it: \`git diff\` it, then check whether the default branch already contains the same change or a superset (this is common — work popped from a stash and redone on the default branch, or already merged under another branch). If it is already on the default branch, \`git checkout -- <file>\` those paths. If it is real unlanded work, commit it on a properly named branch and ship it (push + PR) rather than leaving it loose. If you cannot tell, LEAVE IT and report it.
+- \`off-default-branch\` — resolve whatever is blocking the return (the dirty tree, or the branch not being merged yet), then \`git checkout <default>\`.
+- \`diverged-branch\` / \`diverged-default\` — the local branch and its upstream both moved. Prefer \`git pull --rebase\` on a work branch. On the DEFAULT branch, inspect the local-only commits first (\`git log origin/<default>..<default>\`) — they are usually work that landed upstream under different SHAs, in which case moving the branch onto origin is correct, but confirm with \`git cherry origin/<default> <default>\` before assuming, and never discard a commit that has no patch-equivalent upstream.
+- \`unpushed-branch\` — local commits that were never pushed and have no PR. Push the branch and open a PR if the work is coherent; if it is already on the default branch under other commits, delete the branch. Anything ambiguous stays and gets reported.
+- \`in-flight-branch\` — a branch that needs a PR opened, a conflict resolved, or a review driven. **Report these; do not drive them here.** The \`branch-reconcile\` task owns that work and wraps it in machinery this task has none of — the per-app openPr / resolveConflicts / autoMerge toggles, per-agent batching, the drain convergence guards, and the superseded ledger — so finishing them here bypasses all of it. Name each one and recommend running \`branch-reconcile\`.
+- \`stash-entries\` — triage each one the way the stash-cleanup task does: \`git stash show -p stash@{N}\`, then check whether the default branch already has the same change or a superset. Drop only what is superseded or clearly stale/abandoned scratch (indices shift after every drop, so re-read \`git stash list\` each time). Leave real unlanded work in the stash and say what it is.
+- \`orphan-remote\` — a branch on origin with nothing local pointing at it. Report it rather than deleting it: it may belong to another machine, and \`branch-reconcile\` reaps the provably-merged ones under its own gates.
+- \`action-failed\` — the deterministic step hit something it could not handle. Read the error and finish it by hand, within the rules above.
+- \`scan-failed\` — investigate why (missing path, no origin, auth), and report.
+
+## Verify
+
+Once every escalation is handled, walk EVERY repository named above and confirm the end state, reporting the actual values:
+
+1. \`git status\` — on the default branch, clean tree (untracked build/env files are fine; name them).
+2. \`git log origin/<default>..<default>\` and \`git log <default>..origin/<default>\` — both empty.
+3. \`git branch -vv\` — no leftover local branches beyond the default and any long-lived ones.
+4. \`git worktree list\` — no stale worktrees.
+5. \`git stash list\` — empty, or only entries you deliberately kept.
+
+## Report
+
+Per repository: what you changed, what you deliberately left and why, and the five verification results above. End with a one-line verdict per repo — CLEAN, or what is still outstanding. If you left anything unresolved, say exactly what a human needs to decide.`,
+
'jira-sprint-manager': `[Improvement: {appName}] JIRA Sprint Manager
Triage and implement JIRA tickets for {appName}:
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 1569904dd4..281bc7b1cd 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -43,6 +43,7 @@ export const PROMPT_VERSIONS = {
'data-safety': 1, // v1: data/upgrade-safety audit (migrations, schema parity, version gates). Mode injected at dispatch.
'simplify': 1, // v1: dead-code/duplication audit. Mode injected at dispatch.
'stash-cleanup': 2, // v2: the STALE/ABANDONED heuristic names `AGENTS.md` (or `CLAUDE.md`) as the policy file to check before assuming a stash contradicts current architecture (#4852). v1: triage git stash list — supersession check against main, drop superseded/stale entries, leave real unlanded work in place. Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed).
+ 'repo-sync': 1, // v1: verify + finish the deterministic install-wide origin-sync sweep (services/repoSync.js) — resolve mid-flight merges/rebases, decide what to do with uncommitted work, land or report unpushed branches, triage the stashes it could not prove redundant. Net-new type (no PREVIOUS_DEFAULT_PROMPTS entry needed).
'release-check': 11, // v11: delegate release mechanics to bundled slashdo release and pin PortOS-configured reviewers. v10: the release-documentation search names the `AGENTS.md` (or `CLAUDE.md`) context instead of CLAUDE.md alone (#4852). v9: Step 1 reconciles missing GitHub Releases against git release tags (publishing any missing tag with .changelog/vX.Y.Z.md as body and --latest=false when a newer version exists) BEFORE evaluating if enough unreleased work has accumulated; v8: database-backed release tests are provisioned and run using the repo's documented isolated test database before the release PR gate; v7: Step 1 also reads the UNCOLLECTED changelog fragments (the fragment dir, plus whatever preview command that repo documents — release-check is a generic {appName} prompt, so it never names a PortOS script to run) and counts substantive entries across the assembled notes — reading only the staged `.changelog/NEXT.md` under-counts a release whose entries are still per-branch fragments, so a ready release reported as "not enough work". v6: generic {appName} body (older defaults hardcoded "PortOS")
};
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 6c9fdd5f40..90f37aaea6 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -39,6 +39,7 @@ import {
} from './taskScheduleConstants.js';
import {
DEFAULT_TASK_INTERVALS,
+ INSTALL_WIDE_TASK_TYPES,
MANAGED_AGENT_OPTIONS,
getTaskTypeDescription,
enforceBranchReconcileBatch,
@@ -57,9 +58,9 @@ export {
INTERVAL_TYPES, ON_DEMAND_ORIGINS, isRefillRequest
} from './taskScheduleConstants.js';
export {
- DEFAULT_BRANCHES_PER_AGENT, DEFAULT_TASK_INTERVALS, MANAGED_AGENT_OPTIONS,
- PERPETUAL_DRAIN_DISPATCH_CAP, SELF_IMPROVEMENT_TASK_TYPES, TASK_TYPE_DESCRIPTIONS,
- stripManagedAgentOptionsFromOverride
+ DEFAULT_BRANCHES_PER_AGENT, DEFAULT_TASK_INTERVALS, INSTALL_WIDE_TASK_TYPES,
+ MANAGED_AGENT_OPTIONS, PERPETUAL_DRAIN_DISPATCH_CAP, SELF_IMPROVEMENT_TASK_TYPES,
+ TASK_TYPE_DESCRIPTIONS, stripManagedAgentOptionsFromOverride
} from './taskScheduleRegistry.js';
export { loadSchedule } from './taskScheduleStore.js';
export {
@@ -1216,7 +1217,12 @@ export async function getScheduleStatus() {
successRate: learningInfo.successRate,
dataPoints: learningInfo.dataPoints,
adjustedIntervalMs: learningInfo.adjustedIntervalMs,
- recommendation: learningInfo.recommendation
+ recommendation: learningInfo.recommendation,
+ // Whether a "Run Now" with NO app is this type's real run (it sweeps every
+ // managed app in one dispatch). Served from the server registry rather than
+ // mirrored in client constants, so the UI cannot drift from the set the
+ // dispatch engines actually treat as install-wide.
+ installWide: INSTALL_WIDE_TASK_TYPES.has(taskType)
};
// Include default stage prompts for pipeline tasks so UI can display them
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 090a9d0da3..f8b8f06c37 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -104,6 +104,7 @@ vi.mock('./cosState.js', async () => {
import {
INTERVAL_TYPES,
+ INSTALL_WIDE_TASK_TYPES,
SELF_IMPROVEMENT_TASK_TYPES,
loadSchedule,
getTaskInterval,
@@ -232,6 +233,18 @@ describe('taskSchedule', () => {
})
})
+ describe('INSTALL_WIDE_TASK_TYPES', () => {
+ it('names only task types that really sweep the whole install', () => {
+ expect([...INSTALL_WIDE_TASK_TYPES]).toEqual(['repo-sync'])
+ })
+
+ it('every install-wide type is a registered task type', () => {
+ for (const t of INSTALL_WIDE_TASK_TYPES) {
+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain(t)
+ }
+ })
+ })
+
describe('TASK_TYPE_DESCRIPTIONS', () => {
// Guards against the "orphaned task" bug: a task type with no description
// entry falls back to a dasherized label ("claim work") in the schedule UI,
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index c8a5d8148b..7f1d2a5ca0 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -5,7 +5,7 @@
* so app configuration can consume task definitions without forming a cycle.
*/
-import { BRANCHES_PER_AGENT_MAX, BRANCHES_PER_AGENT_MIN } from '../lib/cosValidation.js';
+import { BRANCHES_PER_AGENT_MAX, BRANCHES_PER_AGENT_MIN, DEFAULT_REPO_SYNC_VERIFY_MODE } from '../lib/cosValidation.js';
import { isAuditTaskType, defaultFileIssuesFor } from '../lib/auditCatalog.js';
import { INTERVAL_TYPES } from './taskScheduleConstants.js';
@@ -46,6 +46,21 @@ export const SELF_IMPROVEMENT_TASK_TYPES = [
// coordinator posture, since a cleared stash is a repo-hygiene side effect,
// never a commit. See DEFAULT_TASK_PROMPTS['stash-cleanup'].
'stash-cleanup',
+ // Install-wide git hygiene sweep: for EVERY managed app (PortOS included) put
+ // the checkout back on its default branch, level with origin both ways, with
+ // no leftover local branches/worktrees and an empty stash list. A deterministic
+ // Tier-1 pass in services/repoSync.js does everything provable with no LLM call
+ // (push what is strictly ahead, fast-forward the default branch, return to it
+ // when the current branch is clean + already merged, delegate merged-branch and
+ // worktree deletion to branchReconcile, drop stashes whose content is identical
+ // to the default branch). It dispatches ONE coordinator agent only when the
+ // sweep leaves something needing judgment — a mid-flight merge/rebase,
+ // uncommitted work, a diverged branch, unpushed commits with no PR, a stash it
+ // could not prove redundant — or, under the default `verifyMode:
+ // 'when-changed'`, to double-check a run that actually mutated something.
+ // On-demand only, and GLOBAL: 'Run Now' with no app sweeps the whole install,
+ // which is the shape the task exists for. Non-committing coordinator posture.
+ 'repo-sync',
// PortOS-only: researches the current best local LLMs per category and
// refreshes the bundled suggested-models catalog (server/lib/localLlmCatalog.js)
// + the editorial family ranking (server/lib/localModelHeuristics.js), opening a
@@ -147,6 +162,15 @@ const CODE_REVIEWER_INTERVAL = { type: INTERVAL_TYPES.WEEKLY, enabled: false, we
* ship without the key at all (absent/`null` ⇒ unbounded, their work-detector's
* idle park remains the only brake) and only the reconcile scans carry a number.
*/
+/**
+ * Task types whose "Run Now" with NO app is the REAL run — they sweep every
+ * managed app in one dispatch rather than acting on one. Surfaced per task on
+ * `getScheduleStatus()` so the schedule UI can offer an "All apps" entry
+ * instead of forcing every run through the app picker (which would make the
+ * install-wide lane unreachable on any install that has apps).
+ */
+export const INSTALL_WIDE_TASK_TYPES = new Set(['repo-sync']);
+
export const PERPETUAL_DRAIN_DISPATCH_CAP = 5;
export const DEFAULT_BRANCHES_PER_AGENT = 3;
@@ -264,6 +288,15 @@ export const DEFAULT_TASK_INTERVALS = {
// there's no useful cadence for a stash a user hasn't necessarily touched
// since the last run — they trigger it when they notice stash clutter.
'stash-cleanup': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA } },
+ // repo-sync sweeps EVERY managed app's checkout in one run (see the type list
+ // above). Like stash-cleanup it runs in the live checkouts — a branch, a stash,
+ // and a worktree are all properties of the checkout they live in, so a CoS
+ // worktree would hide every one of them — and ships no code of its own.
+ // On-demand: the user runs it when they want a clean slate, and a cadence would
+ // switch branches under a checkout they may be sitting in. Every action toggle
+ // is ON except `reapRemotes`, which DELETES branches on origin and so stays
+ // opt-in even though the reconciler only ever reaps already-merged ones.
+ 'repo-sync': { type: INTERVAL_TYPES.ON_DEMAND, enabled: false, providerId: null, model: null, prompt: null, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, syncPush: true, syncPull: true, switchDefault: true, cleanupMerged: true, dropStashes: true, reapRemotes: false, verifyMode: DEFAULT_REPO_SYNC_VERIFY_MODE } },
'pr-reviewer': { type: INTERVAL_TYPES.CUSTOM, intervalMs: 7200000, enabled: false, weekdaysOnly: true, providerId: null, model: null, prompt: null, taskMetadata: { readOnly: true, pipeline: { stages: [{ name: 'Security Scan', promptKey: 'pr-reviewer-security', readOnly: true }, { name: 'Code Review & Merge', promptKey: 'pr-reviewer-review', readOnly: false }] } } },
'code-reviewer-a': { ...CODE_REVIEWER_INTERVAL },
'code-reviewer-b': { ...CODE_REVIEWER_INTERVAL },
@@ -358,7 +391,7 @@ export const MANAGED_AGENT_OPTIONS = {
// fields, so an unmanaged `worktreeChangesExpected` would silently go absent and the
// task bookkeeping would otherwise treat the clean worktree as missing code work.
...Object.fromEntries(
- ['branch-reconcile', 'branch-cleanup', 'issue-reconcile', 'jira-status-report']
+ ['branch-reconcile', 'branch-cleanup', 'issue-reconcile', 'jira-status-report', 'stash-cleanup', 'repo-sync']
.map((t) => [t, ['useWorktree', 'openPR', 'worktreeChangesExpected']])
),
// claim-issue's prompt creates its own claim/issue-<num> worktree (same
@@ -367,8 +400,7 @@ export const MANAGED_AGENT_OPTIONS = {
// claim-work delegates to one of the above prompt bodies, each of which
// creates its own worktree + PR — so the same lock applies to the router.
'claim-work': ['useWorktree', 'openPR', 'claimFlow'],
- 'release-check': ['useWorktree', 'openPR', 'worktreeChangesExpected', 'slashdoCommand'],
- 'stash-cleanup': ['useWorktree', 'openPR', 'worktreeChangesExpected']
+ 'release-check': ['useWorktree', 'openPR', 'worktreeChangesExpected', 'slashdoCommand']
};
// Strip managed-agent fields from a per-app override map before merging on top
@@ -461,6 +493,7 @@ export const TASK_TYPE_DESCRIPTIONS = {
'data-safety': 'Data/upgrade-safety audit — file issues (default) or implement fixes',
'simplify': 'Dead-code/duplication audit — file issues (default) or implement removals',
'stash-cleanup': 'Triage git stash list — drop entries superseded by or stale relative to main, leave real unlanded work in place',
+ 'repo-sync': 'Sync every managed app with origin — back on the default branch, pushed and pulled, merged branches/worktrees and redundant stashes cleared',
'refresh-local-llm-catalog': "Refresh PortOS's bundled suggested local-model catalog + editorial ranking (PortOS repo only)",
'plan-feature': "Brainstorm one feature and file its decision-complete plan to the app's work tracker (no code)",
'layered-intelligence': "Read this app's goals + telemetry, ask a reasoning model for one improvement, and file one deduplicated tracker issue — no code, no agent"
diff --git a/server/services/taskTypeHooks.js b/server/services/taskTypeHooks.js
index 378362bbdb..baf025819d 100644
--- a/server/services/taskTypeHooks.js
+++ b/server/services/taskTypeHooks.js
@@ -141,7 +141,7 @@ export function resolveTaskHookType(task) {
*/
export const NON_COMMITTING_COORDINATOR_TASK_TYPES = new Set([
'branch-reconcile', 'issue-reconcile', 'branch-cleanup', 'jira-status-report', 'release-check',
- 'stash-cleanup',
+ 'stash-cleanup', 'repo-sync',
]);
/**
diff --git a/server/services/workflow.js b/server/services/workflow.js
index 80e1aaa2ef..4cf054342b 100644
--- a/server/services/workflow.js
+++ b/server/services/workflow.js
@@ -42,7 +42,7 @@ export const WORKFLOW_STAGES = [
id: 'hygiene',
label: 'Hygiene',
description: 'Reset state: clean up merged branches and stale agent data so downstream stages start clean.',
- taskTypes: ['branch-reconcile', 'stash-cleanup'],
+ taskTypes: ['repo-sync', 'branch-reconcile', 'stash-cleanup'],
jobIds: ['job-agent-data-cleanup']
},
{