opencode-github-sync 3.3.1 → 4.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +122 -7
  3. package/README.zh-CN.md +68 -5
  4. package/dist/cli/app.d.ts +3 -2
  5. package/dist/cli/app.d.ts.map +1 -1
  6. package/dist/cli/app.js +7 -5
  7. package/dist/cli/app.js.map +1 -1
  8. package/dist/cli/i18n.d.ts +12 -0
  9. package/dist/cli/i18n.d.ts.map +1 -1
  10. package/dist/cli/i18n.js +24 -0
  11. package/dist/cli/i18n.js.map +1 -1
  12. package/dist/cli/index.d.ts +14 -1
  13. package/dist/cli/index.d.ts.map +1 -1
  14. package/dist/cli/index.js +98 -1
  15. package/dist/cli/index.js.map +1 -1
  16. package/dist/cli/menu.d.ts.map +1 -1
  17. package/dist/cli/menu.js +21 -15
  18. package/dist/cli/menu.js.map +1 -1
  19. package/dist/core/autosync.d.ts +9 -3
  20. package/dist/core/autosync.d.ts.map +1 -1
  21. package/dist/core/autosync.js +45 -57
  22. package/dist/core/autosync.js.map +1 -1
  23. package/dist/core/categories.d.ts +3 -19
  24. package/dist/core/categories.d.ts.map +1 -1
  25. package/dist/core/categories.js +0 -85
  26. package/dist/core/categories.js.map +1 -1
  27. package/dist/core/compare.d.ts +1 -1
  28. package/dist/core/compare.d.ts.map +1 -1
  29. package/dist/core/compare.js +10 -1
  30. package/dist/core/compare.js.map +1 -1
  31. package/dist/core/configsync.d.ts +57 -0
  32. package/dist/core/configsync.d.ts.map +1 -0
  33. package/dist/core/configsync.js +310 -0
  34. package/dist/core/configsync.js.map +1 -0
  35. package/dist/core/fsx.d.ts +13 -1
  36. package/dist/core/fsx.d.ts.map +1 -1
  37. package/dist/core/fsx.js +72 -19
  38. package/dist/core/fsx.js.map +1 -1
  39. package/dist/core/history.d.ts +1 -1
  40. package/dist/core/history.d.ts.map +1 -1
  41. package/dist/core/history.js +3 -2
  42. package/dist/core/history.js.map +1 -1
  43. package/dist/core/index.d.ts +1 -0
  44. package/dist/core/index.d.ts.map +1 -1
  45. package/dist/core/index.js +1 -0
  46. package/dist/core/index.js.map +1 -1
  47. package/dist/core/lease.d.ts.map +1 -1
  48. package/dist/core/lease.js +5 -4
  49. package/dist/core/lease.js.map +1 -1
  50. package/dist/core/lock.d.ts.map +1 -1
  51. package/dist/core/lock.js +2 -1
  52. package/dist/core/lock.js.map +1 -1
  53. package/dist/core/manifest.d.ts +71 -0
  54. package/dist/core/manifest.d.ts.map +1 -0
  55. package/dist/core/manifest.js +302 -0
  56. package/dist/core/manifest.js.map +1 -0
  57. package/dist/core/migrate.d.ts +14 -0
  58. package/dist/core/migrate.d.ts.map +1 -0
  59. package/dist/core/migrate.js +207 -0
  60. package/dist/core/migrate.js.map +1 -0
  61. package/dist/core/notify.d.ts +17 -0
  62. package/dist/core/notify.d.ts.map +1 -1
  63. package/dist/core/notify.js +75 -7
  64. package/dist/core/notify.js.map +1 -1
  65. package/dist/core/overrides.d.ts +9 -29
  66. package/dist/core/overrides.d.ts.map +1 -1
  67. package/dist/core/overrides.js +29 -83
  68. package/dist/core/overrides.js.map +1 -1
  69. package/dist/core/paths.d.ts +21 -1
  70. package/dist/core/paths.d.ts.map +1 -1
  71. package/dist/core/paths.js +26 -0
  72. package/dist/core/paths.js.map +1 -1
  73. package/dist/core/repo.d.ts +4 -12
  74. package/dist/core/repo.d.ts.map +1 -1
  75. package/dist/core/repo.js +14 -32
  76. package/dist/core/repo.js.map +1 -1
  77. package/dist/core/settings.d.ts +66 -4
  78. package/dist/core/settings.d.ts.map +1 -1
  79. package/dist/core/settings.js +167 -15
  80. package/dist/core/settings.js.map +1 -1
  81. package/dist/core/setup.d.ts.map +1 -1
  82. package/dist/core/setup.js +3 -1
  83. package/dist/core/setup.js.map +1 -1
  84. package/dist/core/stage.d.ts +11 -16
  85. package/dist/core/stage.d.ts.map +1 -1
  86. package/dist/core/stage.js +94 -79
  87. package/dist/core/stage.js.map +1 -1
  88. package/dist/core/sync.d.ts +14 -0
  89. package/dist/core/sync.d.ts.map +1 -1
  90. package/dist/core/sync.js +186 -217
  91. package/dist/core/sync.js.map +1 -1
  92. package/dist/core/update.d.ts +13 -1
  93. package/dist/core/update.d.ts.map +1 -1
  94. package/dist/core/update.js +25 -4
  95. package/dist/core/update.js.map +1 -1
  96. package/dist/core/upstream.d.ts +96 -0
  97. package/dist/core/upstream.d.ts.map +1 -0
  98. package/dist/core/upstream.js +313 -0
  99. package/dist/core/upstream.js.map +1 -0
  100. package/dist/plugin/index.d.ts.map +1 -1
  101. package/dist/plugin/index.js +8 -0
  102. package/dist/plugin/index.js.map +1 -1
  103. package/package.json +2 -2
package/dist/core/sync.js CHANGED
@@ -1,19 +1,22 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
- import { disabledCategories, disabledPathspecs, isDisabledPath, restoreDisabled, snapshotDisabled, } from "./categories.js";
3
+ import { disabledCategories, isDisabledPath } from "./categories.js";
4
+ import { configStageIn, configStageOut, pendingConfigChanges, } from "./configsync.js";
4
5
  import { bridgeCredentials } from "./credentials.js";
5
- import { git, isGitRepo, parseNameStatus, parsePorcelainPaths, parsePorcelainZ, toGitError, } from "./git.js";
6
+ import { git, isGitRepo, parseNameStatus, parsePorcelainPaths, toGitError, } from "./git.js";
6
7
  import { LargeChangeError, evaluateGuard, writeLocalExcludes } from "./guard.js";
7
8
  import { commitMessage, hostAlias } from "./host.js";
8
- import { applyOverrides, configMatchesRepo, findConfigFile } from "./overrides.js";
9
- import { getDatabasePath, getRoots } from "./paths.js";
10
- import { recoveryRoot, saveToRecovery } from "./recovery.js";
11
- import { LOCAL_RUNTIME_PATHS, assertPushLanded, assertRemoteReachable, ensureRepo, excludePathspecs, headCommit, holdMachineFiles, isLocalRuntimePath, readStageOutMark, unstageLocalRuntimePaths, untrackMachineFiles, writeRepoMetadata, writeStageOutMark, } from "./repo.js";
9
+ import { effectiveRules, listUnlisted } from "./manifest.js";
10
+ import { ensureMigrated } from "./migrate.js";
11
+ import { loadOverrides } from "./overrides.js";
12
+ import { SESSIONS_DIR, STATE_DIR, getDatabasePath, getRoots, repoDir, } from "./paths.js";
13
+ import { recoveryRoot } from "./recovery.js";
14
+ import { LOCAL_RUNTIME_PATHS, assertPushLanded, assertRemoteReachable, ensureRepo, excludePathspecs, headCommit, isLocalRuntimePath, readStageOutMark, unstageLocalRuntimePaths, untrackMachineFiles, writeRepoMetadata, writeStageOutMark, } from "./repo.js";
12
15
  import { emptySummary, silentReporter, summarize, totalChanges, } from "./reporter.js";
13
16
  import { exportSessions, importSessions } from "./sessions.js";
14
- import { DEFAULT_SETTINGS, loadSettings, repoBranch, repoUrl } from "./settings.js";
17
+ import { DEFAULT_SETTINGS, loadPolicy, loadSettings, repoBranch, repoUrl, } from "./settings.js";
15
18
  import { sqliteAvailable } from "./sqlite.js";
16
- import { createStageContext, normalizeConfigForRepo, prunePluginCache, stageIn, stageOut, } from "./stage.js";
19
+ import { createStageContext, prunePluginCache, stageIn, stageOut } from "./stage.js";
17
20
  class SyncError extends Error {
18
21
  constructor(message) {
19
22
  super(message);
@@ -33,8 +36,29 @@ export class PushRaceError extends Error {
33
36
  /** Commit trailer naming the machine that produced a sync commit. */
34
37
  export const DEVICE_TRAILER = "Opencode-Sync-Device";
35
38
  const PUSH_RACE_RETRIES = 3;
39
+ function configCtx(ctx) {
40
+ return { roots: ctx.roots, repoRoot: ctx.root, settings: ctx.settings, reporter: ctx.reporter };
41
+ }
42
+ /** Bring the live config files into the working copy before git runs. */
43
+ function configIn(ctx, mirror) {
44
+ const staged = configStageIn(configCtx(ctx), mirror ? "mirror" : "normal", readStageOutMark(ctx.root));
45
+ ctx.baseline = staged.baseline;
46
+ }
47
+ /** Write the working copy's config files out to the live folder. */
48
+ function configOut(ctx, mode, label) {
49
+ const result = configStageOut(configCtx(ctx), {
50
+ mode,
51
+ baseline: ctx.baseline,
52
+ mark: readStageOutMark(ctx.root),
53
+ label,
54
+ });
55
+ if (result.written.length + result.deleted.length > 0) {
56
+ ctx.reporter.detail(`Config: wrote ${result.written.length}, removed ${result.deleted.length} file(s) here`);
57
+ }
58
+ }
36
59
  function prepare(options) {
37
60
  const roots = options.roots ?? getRoots();
61
+ ensureMigrated(roots);
38
62
  const settings = options.settings ?? loadSettings(roots.config);
39
63
  const remote = repoUrl(settings);
40
64
  if (!remote) {
@@ -42,7 +66,7 @@ function prepare(options) {
42
66
  "Run `opencode-sync init` to create one, or `opencode-sync link <owner/repo>` to use an existing one.");
43
67
  }
44
68
  return {
45
- root: roots.config,
69
+ root: repoDir(roots),
46
70
  branch: repoBranch(settings),
47
71
  remote,
48
72
  settings,
@@ -64,33 +88,34 @@ function toChangedFiles(result, excludeRuntime) {
64
88
  export async function push(options = {}) {
65
89
  const ctx = prepare(options);
66
90
  const { root, branch, reporter } = ctx;
67
- if (!fs.existsSync(root))
68
- throw new SyncError(`Config directory not found: ${root}`);
69
- const restoreMachineFiles = holdMachineFiles(root);
70
- try {
71
- const state = adoptRepo(ctx, options.adopt ?? "remote", "first-push");
72
- if (state === "adopted" && (options.adopt ?? "remote") === "remote" && !ctx.dryRun) {
73
- // The remote's files are now in the worktree, but the untracked trees
74
- // (skills, state, extra paths) still hold this machine's old contents.
75
- // Write the remote's versions out first; staging the stale trees in would
76
- // otherwise publish every skill this machine lacks as a deletion.
91
+ if (!fs.existsSync(ctx.roots.config)) {
92
+ throw new SyncError(`Config directory not found: ${ctx.roots.config}`);
93
+ }
94
+ fs.mkdirSync(root, { recursive: true });
95
+ const adopt = options.adopt ?? "remote";
96
+ const state = adoptRepo(ctx);
97
+ let mirror = false;
98
+ if (state === "adopted" && !ctx.dryRun) {
99
+ if (adopt === "remote") {
100
+ // The repository's files win the first link. Listed config files are
101
+ // written out (the replaced ones saved to recovery first), and the
102
+ // mirrored trees too: staging this machine's old trees in would
103
+ // otherwise publish every skill it lacks as a deletion.
104
+ configOut(ctx, "adopt", "first-push");
77
105
  stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
78
106
  writeStageOutMark(root);
79
107
  }
80
- assertRemoteReachable(root, branch, "Push", true);
81
- writeRepoMetadata(root);
82
- writeLocalExcludes(root, ctx.settings.guard?.skipDirs ?? []);
83
- return await runPush(ctx);
84
- }
85
- finally {
86
- // Staging rewrites the on-disk config into its shareable form. Whatever
87
- // happens next — success, conflict, network failure — this machine must be
88
- // left with its own effective configuration, not the stripped one.
89
- applyOverrides(ctx.roots.config);
90
- restoreMachineFiles();
108
+ else {
109
+ // This machine wins: its listed files replace the repository's.
110
+ mirror = true;
111
+ }
91
112
  }
113
+ assertRemoteReachable(root, branch, "Push", true);
114
+ writeRepoMetadata(root);
115
+ writeLocalExcludes(root, ctx.settings.guard?.skipDirs ?? []);
116
+ return await runPush(ctx, mirror);
92
117
  }
93
- async function runPush(ctx) {
118
+ async function runPush(ctx, mirror = false) {
94
119
  const { root, branch, reporter } = ctx;
95
120
  // A previous run that integrated remote commits but stopped before writing
96
121
  // them out leaves the real directories behind HEAD. Staging that stale tree
@@ -100,17 +125,19 @@ async function runPush(ctx) {
100
125
  const head = headCommit(root);
101
126
  if (!ctx.dryRun && mark && head && mark !== head) {
102
127
  reporter.step("Writing out changes from an earlier sync");
128
+ configOut(ctx, "lagging");
103
129
  stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
104
130
  writeStageOutMark(root);
105
131
  }
106
132
  reporter.step("Staging local files");
107
133
  await bridge(ctx, "database");
134
+ configIn(ctx, mirror || ctx.force);
108
135
  stageIn(createStageContext(root, ctx.settings, reporter, ctx.force, ctx.roots));
109
136
  const sessions = await maybeExportSessions(ctx);
110
137
  git(["add", "-A"], { cwd: root });
111
138
  unstageLocalRuntimePaths(root);
112
139
  untrackMachineFiles(root);
113
- unstageDisabled(ctx);
140
+ untrackPolicyDisabled(ctx);
114
141
  const staged = git(["diff", "--cached", "--name-status"], { cwd: root });
115
142
  const files = toChangedFiles(staged, true);
116
143
  const summary = summarize(files);
@@ -134,14 +161,7 @@ async function runPush(ctx) {
134
161
  // anything — and the result must reach the real directories, or the next
135
162
  // push would read everything new as deleted on this machine.
136
163
  reporter.step(`Fast-forwarding ${behind} remote commit(s)`);
137
- const aside = setAsideDisabled(ctx);
138
- let ff;
139
- try {
140
- ff = git(["merge", "--ff-only", `origin/${branch}`], { cwd: root });
141
- }
142
- finally {
143
- restoreDisabled(root, ctx.disabled, aside);
144
- }
164
+ const ff = git(["merge", "--ff-only", `origin/${branch}`], { cwd: root });
145
165
  if (!ff.ok)
146
166
  throw toGitError("Fast-forward", ff);
147
167
  await finishPush(ctx, true);
@@ -192,12 +212,63 @@ async function runPush(ctx) {
192
212
  async function finishPush(ctx, integrated) {
193
213
  if (integrated) {
194
214
  ctx.reporter.step("Writing out changes from other machines");
215
+ configOut(ctx, "normal");
195
216
  stageOut(createStageContext(ctx.root, ctx.settings, ctx.reporter, false, ctx.roots));
196
217
  await bridge(ctx, "file");
197
218
  await maybeImportSessions(ctx);
198
219
  }
199
220
  writeStageOutMark(ctx.root);
200
221
  }
222
+ /**
223
+ * Bring `origin/<branch>` into HEAD.
224
+ *
225
+ * A rebase comes first, for a linear history. When it stops on a conflict the
226
+ * push falls back to a plain merge: a rebase replays every local commit and
227
+ * drops merge commits, so a conflict already resolved by hand in a local
228
+ * merge would be hit again on every run and the machine would never recover.
229
+ * A merge applies both sides once and keeps that resolution. Only a conflict
230
+ * the merge cannot settle either is reported, by file name. A rebase that
231
+ * failed for another reason (network, a dirty tree) reports git's own words.
232
+ */
233
+ export function integrateRemote(root, branch, reporter = silentReporter) {
234
+ const rebase = git(["pull", "--rebase", "origin", branch], { cwd: root });
235
+ if (rebase.ok)
236
+ return;
237
+ if (!rebaseInProgress(root)) {
238
+ git(["rebase", "--abort"], { cwd: root });
239
+ throw toGitError("Pull before push", rebase);
240
+ }
241
+ const rebasePaths = conflictedPaths(root);
242
+ git(["rebase", "--abort"], { cwd: root });
243
+ const merge = git(["merge", "--no-edit", `origin/${branch}`], { cwd: root });
244
+ if (merge.ok) {
245
+ reporter.step(`Rebase stopped on ${rebasePaths.join(", ") || "a conflict"}; merged instead and resolved it`);
246
+ return;
247
+ }
248
+ const mergePaths = conflictedPaths(root);
249
+ git(["merge", "--abort"], { cwd: root });
250
+ const paths = mergePaths.length > 0 ? mergePaths : rebasePaths;
251
+ throw new SyncError(`The remote has changes that conflict with this machine${paths.length ? `: ${paths.join(", ")}` : ""}.\n` +
252
+ "Run `opencode-sync pull` to take the remote version, or `opencode-sync push --force` to overwrite it.");
253
+ }
254
+ function rebaseInProgress(root) {
255
+ const dir = git(["rev-parse", "--git-dir"], { cwd: root });
256
+ if (!dir.ok)
257
+ return false;
258
+ const gitDir = path.resolve(root, dir.stdout);
259
+ return (fs.existsSync(path.join(gitDir, "rebase-merge")) ||
260
+ fs.existsSync(path.join(gitDir, "rebase-apply")));
261
+ }
262
+ /** Paths a stopped rebase or merge is stuck on. Read before aborting. */
263
+ function conflictedPaths(root) {
264
+ const result = git(["diff", "--name-only", "--diff-filter=U"], { cwd: root });
265
+ return result.ok
266
+ ? result.stdout
267
+ .split("\n")
268
+ .map((l) => l.trim())
269
+ .filter(Boolean)
270
+ : [];
271
+ }
201
272
  /** Push the branch. Returns true when a rebase integrated remote commits. */
202
273
  function pushBranch(ctx) {
203
274
  const { root, branch, force, reporter } = ctx;
@@ -231,36 +302,23 @@ function pushBranch(ctx) {
231
302
  }
232
303
  // Another machine can publish between our rebase and our push. Losing that
233
304
  // race is contention, not failure: rebase onto the newcomer and try again.
234
- // Files in disabled categories are set aside so local-only edits never
235
- // block the rebase.
236
- const aside = setAsideDisabled(ctx);
237
305
  let integrated = false;
238
- try {
239
- for (let attempt = 1;; attempt++) {
240
- const before = headCommit(root);
241
- const rebase = git(["pull", "--rebase", "origin", branch], { cwd: root });
242
- if (!rebase.ok) {
243
- git(["rebase", "--abort"], { cwd: root });
244
- throw new SyncError("The remote has changes that conflict with this machine.\n" +
245
- "Run `opencode-sync pull` to take the remote version, or `opencode-sync push --force` to overwrite it.");
246
- }
247
- // The rebase moves HEAD only when it replayed local commits onto new
248
- // remote ones; an unchanged HEAD means nothing arrived.
249
- if (headCommit(root) !== before)
250
- integrated = true;
251
- const result = git(["push", "origin", branch], { cwd: root });
252
- if (result.ok)
253
- break;
254
- if (!isRejected(result))
255
- throw toGitError("Push", result);
256
- if (attempt >= PUSH_RACE_RETRIES) {
257
- throw new PushRaceError(`Another machine kept publishing first (${attempt} attempts). The next sync will retry.`);
258
- }
259
- reporter.step("Another machine pushed first; rebasing and retrying");
306
+ for (let attempt = 1;; attempt++) {
307
+ const before = headCommit(root);
308
+ integrateRemote(root, branch, reporter);
309
+ // The rebase moves HEAD only when it replayed local commits onto new
310
+ // remote ones; an unchanged HEAD means nothing arrived.
311
+ if (headCommit(root) !== before)
312
+ integrated = true;
313
+ const result = git(["push", "origin", branch], { cwd: root });
314
+ if (result.ok)
315
+ break;
316
+ if (!isRejected(result))
317
+ throw toGitError("Push", result);
318
+ if (attempt >= PUSH_RACE_RETRIES) {
319
+ throw new PushRaceError(`Another machine kept publishing first (${attempt} attempts). The next sync will retry.`);
260
320
  }
261
- }
262
- finally {
263
- restoreDisabled(root, ctx.disabled, aside);
321
+ reporter.step("Another machine pushed first; rebasing and retrying");
264
322
  }
265
323
  assertPushLanded(root, branch, "Push");
266
324
  return integrated;
@@ -286,50 +344,42 @@ function isRejected(result) {
286
344
  return /\((fetch first|non-fast-forward)\)|cannot lock ref .* but expected/i.test(`${result.stderr}\n${result.stdout}`);
287
345
  }
288
346
  // ── Disabled categories ─────────────────────────────────────────────────────
289
- function unstageDisabled(ctx) {
290
- if (ctx.disabled.length === 0)
291
- return;
292
- git(["reset", "-q", "--", ...disabledPathspecs(ctx.disabled)], { cwd: ctx.root });
293
- }
294
347
  /**
295
- * Copy the disabled categories aside and bring their tracked files back to
296
- * HEAD, so a rebase or reset can run on a clean tree. `restoreDisabled` puts
297
- * the local versions back afterwards.
348
+ * Drop the state and session mirrors from the index when the shared policy
349
+ * turns them off and this machine follows it (#14). Only a policy-backed
350
+ * "off" counts: when every machine agrees the folder is not shared, removing
351
+ * it stops stale copies from churning; one machine opting out on its own
352
+ * would just ping-pong with a machine that keeps adding it back. A machine
353
+ * that deliberately overrides the policy keeps publishing. Files on disk are
354
+ * never touched.
298
355
  */
299
- function setAsideDisabled(ctx) {
300
- if (ctx.disabled.length === 0)
301
- return null;
302
- const snapshot = snapshotDisabled(ctx.root, ctx.disabled);
303
- if (!snapshot)
304
- return null;
305
- // Untracked local-only files would block an incoming file at the same path.
306
- for (const rel of snapshot.files)
307
- fs.rmSync(path.join(ctx.root, rel), { force: true });
308
- const tracked = git(["ls-files", "--", ...disabledPathspecs(ctx.disabled)], { cwd: ctx.root });
309
- const files = tracked.ok ? tracked.stdout.split("\n").filter(Boolean) : [];
310
- if (files.length > 0)
311
- git(["checkout", "HEAD", "--", ...files], { cwd: ctx.root });
312
- return snapshot;
356
+ function untrackPolicyDisabled(ctx) {
357
+ const policy = loadPolicy(ctx.roots.config);
358
+ const specs = [];
359
+ if (policy.includeState === false && !ctx.settings.includeState) {
360
+ specs.push(`:(top,literal)${STATE_DIR}`);
361
+ }
362
+ if (policy.sessions?.enabled === false && !ctx.settings.sessions.enabled) {
363
+ specs.push(`:(top,literal)${SESSIONS_DIR}`);
364
+ }
365
+ if (specs.length === 0)
366
+ return;
367
+ git(["rm", "-r", "-q", "--cached", "--ignore-unmatch", "--", ...specs], { cwd: ctx.root });
313
368
  }
314
369
  // ── Pull ────────────────────────────────────────────────────────────────────
315
370
  export async function pull(options = {}) {
316
371
  const ctx = prepare(options);
317
372
  fs.mkdirSync(ctx.root, { recursive: true });
318
- const restoreMachineFiles = holdMachineFiles(ctx.root);
319
- try {
320
- return await runPull(ctx);
321
- }
322
- finally {
323
- restoreMachineFiles();
324
- }
373
+ return await runPull(ctx);
325
374
  }
326
375
  async function runPull(ctx) {
327
376
  const { root, branch, reporter, force } = ctx;
328
377
  if (!isGitRepo(root)) {
329
- const state = adoptRepo(ctx, "remote", "first-pull");
378
+ const state = adoptRepo(ctx);
330
379
  if (state === "fresh") {
331
380
  return done("pull", false, emptySummary(), [], "The sync repository is empty — push from another machine first.");
332
381
  }
382
+ configOut(ctx, force ? "force" : "adopt", "first-pull");
333
383
  stageOut(createStageContext(root, ctx.settings, reporter, force, ctx.roots));
334
384
  await bridge(ctx, "file");
335
385
  const sessions = await maybeImportSessions(ctx);
@@ -349,16 +399,14 @@ async function runPull(ctx) {
349
399
  }
350
400
  const behind = countCommits(root, `HEAD..origin/${branch}`);
351
401
  if (!force && behind === 0) {
352
- // Nothing incoming, so the worktree does not need to be touched at all.
353
- // Skipping the stash cycle here is what keeps a no-op pull fast on Windows.
354
- //
355
- // HEAD can still be ahead of what was last written out, when a push
356
- // integrated remote commits and stopped before writing them. Settle that
357
- // here; without a recorded mark nothing is known, so nothing is written.
402
+ // Nothing incoming. HEAD can still be ahead of what was last written out,
403
+ // when a push integrated remote commits and stopped before writing them.
404
+ // Settle that here; without a recorded mark nothing is known.
358
405
  const mark = readStageOutMark(root);
359
406
  const head = headCommit(root);
360
407
  if (!ctx.dryRun && mark && head && mark !== head) {
361
408
  reporter.step("Writing out changes from an earlier sync");
409
+ configOut(ctx, "lagging");
362
410
  stageOut(createStageContext(root, ctx.settings, reporter, false, ctx.roots));
363
411
  await bridge(ctx, "file");
364
412
  const sessions = await maybeImportSessions(ctx);
@@ -367,40 +415,28 @@ async function runPull(ctx) {
367
415
  }
368
416
  return done("pull", false, emptySummary(), [], "Already up to date", undefined, false);
369
417
  }
370
- const stageCtx = createStageContext(root, ctx.settings, reporter, force, ctx.roots);
371
- // The config file on disk carries this machine's overrides, so it always
372
- // differs from HEAD. Rewinding it to the committed form first means the
373
- // worktree is clean and the pull never has to stash-and-merge the one file
374
- // that would conflict on every single run.
375
- normalizeConfigForRepo(stageCtx);
376
- if (force && !ctx.dryRun)
377
- saveOverwritten(ctx, `origin/${branch}`, "force-pull");
378
- const aside = ctx.dryRun ? null : setAsideDisabled(ctx);
379
- let stashed = false;
418
+ // Local config edits go into the working copy first, so the stash below
419
+ // carries them across the reset exactly like 3.x carried worktree edits.
420
+ if (!ctx.dryRun)
421
+ configIn(ctx, false);
380
422
  let files = [];
381
423
  let summary = emptySummary();
382
- try {
383
- stashed = prepareWorktree(ctx);
384
- const nameStatus = git(["diff", "--name-status", "HEAD", `origin/${branch}`], { cwd: root });
385
- files = toChangedFiles(nameStatus, true).filter((f) => !isDisabledPath(f.path, ctx.disabled));
386
- summary = summarize(files);
387
- if (ctx.dryRun) {
388
- if (stashed)
389
- restoreStash(ctx);
390
- return done("pull", files.length > 0, summary, files, `${totalChanges(summary)} change(s) would be pulled`);
391
- }
392
- const reset = git(["reset", "--hard", `origin/${branch}`], { cwd: root });
393
- if (!reset.ok) {
394
- if (stashed)
395
- restoreStash(ctx);
396
- throw toGitError("Reset", reset);
397
- }
424
+ const stashed = ctx.dryRun ? false : prepareWorktree(ctx);
425
+ const nameStatus = git(["diff", "--name-status", "HEAD", `origin/${branch}`], { cwd: root });
426
+ files = toChangedFiles(nameStatus, true).filter((f) => !isDisabledPath(f.path, ctx.disabled));
427
+ summary = summarize(files);
428
+ if (ctx.dryRun) {
429
+ return done("pull", files.length > 0, summary, files, `${totalChanges(summary)} change(s) would be pulled`);
430
+ }
431
+ const reset = git(["reset", "--hard", `origin/${branch}`], { cwd: root });
432
+ if (!reset.ok) {
398
433
  if (stashed)
399
434
  restoreStash(ctx);
435
+ throw toGitError("Reset", reset);
400
436
  }
401
- finally {
402
- restoreDisabled(root, ctx.disabled, aside);
403
- }
437
+ if (stashed)
438
+ restoreStash(ctx);
439
+ configOut(ctx, force ? "force" : "normal", "force-pull");
404
440
  stageOut(createStageContext(root, ctx.settings, reporter, force, ctx.roots));
405
441
  await bridge(ctx, "file");
406
442
  const sessions = await maybeImportSessions(ctx);
@@ -408,12 +444,9 @@ async function runPull(ctx) {
408
444
  reporter.changes(summary, files);
409
445
  return done("pull", files.length > 0, summary, files, files.length > 0 ? `Pulled ${totalChanges(summary)} change(s)` : "Already up to date", sessions, true);
410
446
  }
411
- /** Re-apply machine-local settings and clean up caches after a pull. */
447
+ /** Record the write-out and clean up caches after a pull. */
412
448
  function finishPull(ctx) {
413
449
  writeStageOutMark(ctx.root);
414
- if (applyOverrides(ctx.roots.config)) {
415
- ctx.reporter.detail("Re-applied per-machine overrides");
416
- }
417
450
  const pruned = prunePluginCache(ctx.roots.config, ctx.roots.cache);
418
451
  if (pruned > 0)
419
452
  ctx.reporter.detail(`Removed ${pruned} stale plugin package(s) from the cache`);
@@ -551,10 +584,11 @@ async function maybeImportSessions(ctx) {
551
584
  }
552
585
  export function status(options = {}) {
553
586
  const roots = options.roots ?? getRoots();
587
+ ensureMigrated(roots);
554
588
  const settings = options.settings ?? loadSettings(roots.config);
555
589
  const branch = repoBranch(settings);
556
590
  const remote = repoUrl(settings);
557
- const root = roots.config;
591
+ const root = repoDir(roots);
558
592
  const base = {
559
593
  configured: Boolean(remote),
560
594
  remote,
@@ -565,8 +599,9 @@ export function status(options = {}) {
565
599
  dirty: 0,
566
600
  sessionsEnabled: settings.sessions.enabled,
567
601
  sessionShards: countShards(root),
568
- overridesActive: fs.existsSync(path.join(root, "opencode-sync.overrides.jsonc")),
602
+ overridesActive: Object.keys(loadOverrides(roots.config)).length > 0,
569
603
  machineAlias: hostAlias(settings.machineAlias),
604
+ unlisted: listUnlisted(roots.config, effectiveRules(root, settings), settings.guard?.skipDirs ?? []),
570
605
  };
571
606
  if (!remote || !isGitRepo(root))
572
607
  return base;
@@ -574,8 +609,14 @@ export function status(options = {}) {
574
609
  git(["fetch", "origin", branch], { cwd: root });
575
610
  base.ahead = countCommits(root, `origin/${branch}..HEAD`);
576
611
  base.behind = countCommits(root, `HEAD..origin/${branch}`);
612
+ // Pending work is what a push would publish: listed config files that
613
+ // differ from the working copy, plus anything uncommitted in it.
577
614
  const dirty = git(["status", "--porcelain", "--", ".", ...excludePathspecs()], { cwd: root });
578
- base.dirty = dirty.ok ? countRealChanges(root, dirty.stdout) : 0;
615
+ const changed = new Set([
616
+ ...(dirty.ok ? parsePorcelainPaths(dirty.stdout) : []),
617
+ ...pendingConfigChanges({ roots, repoRoot: root, settings }),
618
+ ]);
619
+ base.dirty = changed.size;
579
620
  const log = git(["log", "-1", "--format=%s%n%cI"], { cwd: root });
580
621
  if (log.ok) {
581
622
  const [subject, date] = log.stdout.split("\n");
@@ -590,86 +631,14 @@ function countShards(root) {
590
631
  return 0;
591
632
  return fs.readdirSync(dir).filter((f) => f.endsWith(".json.gz")).length;
592
633
  }
593
- /**
594
- * Count genuinely uncommitted files.
595
- *
596
- * With overrides in use the config file always differs from the committed
597
- * version, so a raw `git status` would report one modified file forever. That
598
- * entry is dropped when the only difference is the overrides themselves.
599
- */
600
- function countRealChanges(root, porcelain) {
601
- const paths = parsePorcelainPaths(porcelain);
602
- if (paths.length === 0)
603
- return 0;
604
- const configFile = findConfigFile(root);
605
- if (!configFile)
606
- return paths.length;
607
- const relative = path.relative(root, configFile).split(path.sep).join("/");
608
- const head = git(["show", `HEAD:${relative}`], { cwd: root });
609
- if (!configMatchesRepo(root, head.ok ? head.stdout : undefined))
610
- return paths.length;
611
- return paths.filter((file) => file !== relative).length;
612
- }
613
634
  // ── Helpers ─────────────────────────────────────────────────────────────────
614
635
  /**
615
- * Make the config directory a working copy of the remote.
616
- *
617
- * When the remote already has history and `mode` is `remote`, the files it
618
- * is about to overwrite are copied to recovery first, and files in disabled
619
- * categories are set aside and put back, so they stay this machine's own.
620
- */
621
- function adoptRepo(ctx, mode, label) {
622
- let aside = null;
623
- try {
624
- return ensureRepo({
625
- root: ctx.root,
626
- remote: ctx.remote,
627
- branch: ctx.branch,
628
- adopt: mode,
629
- beforeAdopt: (_root, ref) => {
630
- saveOverwritten(ctx, ref, label);
631
- aside = snapshotDisabled(ctx.root, ctx.disabled);
632
- },
633
- });
634
- }
635
- finally {
636
- restoreDisabled(ctx.root, ctx.disabled, aside);
637
- }
638
- }
639
- /**
640
- * Copy every local file that a move to `ref` would overwrite or delete into
641
- * the recovery folder. Called before a forced pull and before a first link
642
- * adopts the remote, the two moments local bytes are replaced wholesale.
636
+ * Make the tool's working copy a clone of the remote. The working copy holds
637
+ * nothing of the user's, so adopting the remote never overwrites user bytes
638
+ * here; the config folder is written separately, with recovery copies.
643
639
  */
644
- function saveOverwritten(ctx, ref, label) {
645
- const { root } = ctx;
646
- const candidates = new Set();
647
- const hasHead = git(["rev-parse", "--verify", "HEAD"], { cwd: root }).ok;
648
- if (hasHead) {
649
- const diff = git(["diff", "-z", "--name-only", "HEAD", ref], { cwd: root });
650
- for (const p of diff.ok ? diff.stdout.split("\0") : [])
651
- if (p)
652
- candidates.add(p);
653
- // `--untracked-files=all` lists each file in a new folder; the default
654
- // reports the folder alone, which is not a file and would be skipped
655
- // right before `git clean` deletes it.
656
- const dirty = git(["status", "-z", "--porcelain", "--untracked-files=all", "--", ".", ...excludePathspecs()], { cwd: root });
657
- for (const p of parsePorcelainZ(dirty.ok ? dirty.stdout : ""))
658
- candidates.add(p);
659
- }
660
- else {
661
- const files = git(["ls-tree", "-z", "-r", "--name-only", ref], { cwd: root });
662
- for (const p of files.ok ? files.stdout.split("\0") : [])
663
- if (p)
664
- candidates.add(p);
665
- }
666
- const entries = [...candidates]
667
- .filter((rel) => !isLocalRuntimePath(rel))
668
- .map((rel) => ({ source: path.join(root, rel), rel }));
669
- const dir = saveToRecovery(ctx.roots, label, entries);
670
- if (dir)
671
- ctx.reporter.detail(`Saved the replaced local files to ${dir}`);
672
- return dir;
640
+ function adoptRepo(ctx) {
641
+ return ensureRepo({ root: ctx.root, remote: ctx.remote, branch: ctx.branch, adopt: "remote" });
673
642
  }
674
643
  function countCommits(root, range) {
675
644
  const result = git(["rev-list", "--count", range], { cwd: root });